diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..e62b6dabd23e9bcadc58d7896d5f2b6ca83694da 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.so filter=lfs diff=lfs merge=lfs -text +*.so.* filter=lfs diff=lfs merge=lfs -text +*.a filter=lfs diff=lfs merge=lfs -text +*.a.* filter=lfs diff=lfs merge=lfs -text +duix-android/dh_aigc_android/duix-sdk/src/main/cpp/linux/gjgpgmain filter=lfs diff=lfs merge=lfs -text diff --git a/duix-android/dh_aigc_android/.gitignore b/duix-android/dh_aigc_android/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..094ba2d776c830090adb0938251e3c5dfdb953ae --- /dev/null +++ b/duix-android/dh_aigc_android/.gitignore @@ -0,0 +1,25 @@ +*.iml +.gradle +/local.properties +/.idea/ +.DS_Store +/build/ +*/build/ +*/*/build/ +*/debug/ +*/release/ +/captures +.externalNativeBuild +.cxx +*.bat +*.apk +output-metadata.json +# app用到zip的请忽略 +# 自定义了local.properties的请删除这条 +local.properties +~$* +gradlew +.idea +# 自定义了根目录gradle/gradle-wrapper.properties的请删除这条(不推荐自定义) +#gradle +build diff --git a/duix-android/dh_aigc_android/README.md b/duix-android/dh_aigc_android/README.md new file mode 100644 index 0000000000000000000000000000000000000000..912eefd5e3502106e0061f86986c43014fc0ad0f --- /dev/null +++ b/duix-android/dh_aigc_android/README.md @@ -0,0 +1,268 @@ +# DUIX-SDK +2D虚拟数字人SDK,可以通过语音完成对虚拟人实时驱动。 + +## 一、产品介绍 + +2D 数字人虚拟人SDK ,可以通过语音完成对虚拟人实时驱动。 + +### 1. 适用场景 + +部署成本低: 无需客户提供技术团队进行配合,支持低成本快速部署在多种终端及大屏; +网络依赖小:可落地在地铁、银行、政务等多种场景的虚拟助理自助服务上; +功能多样化:可根据客户需求满足视频、媒体、客服、金融、广电等多个行业的多样化需求 + +### 2. 核心功能 + +提供定制形象的 AI 主播,智能客服等多场景形象租赁,支持客户快速部署和低成本运营; +专属形象定制:支持定制专属的虚拟助理形象,可选低成本或深度形象生成; +播报内容定制:支持定制专属的播报内容,应用在培训、播报等多种场景上; +实时互动问答:支持实时对话,也可定制专属问答库,可满足咨询查询、语音闲聊、虚拟陪伴、垂类场景的客服问答等需求。 + +## 二、SDK集成 + +### 1. 支持的系统和硬件版本 + +| 项目 | 描述 | +|--------|------------------------------------------------------------------| +| 系统 | 支持 Android 7.0+ ( API Level 24 )到 Android 13 ( API Level 33 )系统。 | +| CPU架构 | armeabi-v7a, arm64-v8a | +| 硬件要求 | 要求设备 CPU4 核极以上,内存 4G 及以上。可用存储空间 500MB 及以上。 | +| 网络 | 支持 WIF 及移动网络。如果使用云端问答库,设备带宽(用于数字人的实际带宽)期望 10mbps 及以上。 | +| 开发 IDE | Android Studio Giraffe \mid 2022.3.1 Patch 2 | +| 内存要求 | 可用于数字人的内存 >= 400MB | + +##两个人物模型(切换男女形象,修改./duix-android/dh_aigc_android/test/src/main/java/ai/guiji/duix/test/ui/activity/MainActivity.kt的modelUrl变量即可) +``` + 女:https://cdn.guiji.ai/duix/digital/model/1712034391673/bendi1_0329.zip + 男:https://digital-public.obs.cn-east-3.myhuaweicloud.com/duix/digital/model/1706009711636/liangwei_540s.zip +``` + +### 2. SDK集成 + +引入 sdk aar 包: duix_client_sdk_release_${version}.aar +app 目录新建 libs 目录,放入 aar 包,在 build.gradle 中增加配置如下 + +```gradle +dependencies { + // 使用阿里ASR需要将nuisdk-release.aar放到libs目录下(必选) + implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs') + // sdk 中使用到 exoplayer 处理音频(必选) + implementation 'com.google.android.exoplayer:exoplayer:2.14.2' + + // 云端问答接口使用的SSE组件(非必选) + implementation 'com.squareup.okhttp3:okhttp-sse:4.10.0' + + ... +} +``` + +权限要求, AndroidManifest.xml中,增加如下配置 + +```xml + + + + + + + + + + +``` + +## 三、SDK调用及API说明 + +### 1. 初始化SDK + +在渲染页onCreate()阶段构建DUIX对象并添加回调事件 + +```kotlin +duix = DUIX(mContext, baseDir, modelDir, mDUIXRender) { event, msg, info -> + when (event) { + ai.guiji.duix.sdk.client.Constant.CALLBACK_EVENT_INIT_READY -> { + initOK() + } + + ai.guiji.duix.sdk.client.Constant.CALLBACK_EVENT_INIT_ERROR -> { + + } + // ... + + } +} +// 异步回调结果 +duix?.init() +``` + + + +DUIX对象构建说明: + +| 参数 | 类型 | 描述 | +| -------- | ---------- | ------------------------------------------------------------ | +| context | Context | 系统上下文 | +| baseDir | String | 存放模型驱动的配置文件,需要自行管理. 可将压缩文件解压到外部存储并提供文件夹路径 | +| modelDir | String | 存放模型文件的文件夹,需要自行管理. 可将压缩文件解压到外部存储并提供文件夹路径 | +| render | RenderSink | 渲染数据接口,sdk提供了默认的渲染组件继承自该接口,也可以自己实现 | +| callback | Callback | SDK处理的各种回调事件 | + +参考demo LiveActivity示例 + +### 2. 获取SDK模型初始化状态 + +```kotlin +object : Callback { + fun onEvent(event: String, msg: String, info: Object) { + when (event) { + "init.ready" -> { + // SDK模型初始化成功 + } + + "init.error" -> { + //初始化失败 + Log.e(TAG, "init error: $msg") + } + // ... + + } + } +} +``` + +### 3. 数字人形象展示 + +使用RenderSink接口接受渲染帧数据,SDK中提供了该接口实现DUIXRenderer.java。也可以自己实现该接口自定义渲染。 +其中RenderSink的定义如下: + +```java +/** + * 渲染管道,通过该接口返回渲染数据 + */ +public interface RenderSink { + + // frame中的buffer数据以bgr顺序排列 + void onVideoFrame(ImageFrame imageFrame); + +} +``` + +使用DUIXRenderer及DUIXTextureView控件简单实现渲染展示,该控件支持透明通道可以自由设置背景及前景: + +```kotlin +override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // ... + mDUIXRender = + DUIXRenderer( + mContext, + binding.glTextureView + ) + + binding.glTextureView.setEGLContextClientVersion(GL_CONTEXT_VERSION) + binding.glTextureView.setEGLConfigChooser(8, 8, 8, 8, 16, 0) // 透明 + binding.glTextureView.isOpaque = false // 透明 + binding.glTextureView.setRenderer(mDUIXRender) + binding.glTextureView.renderMode = + GLSurfaceView.RENDERMODE_WHEN_DIRTY // 一定要在设置完Render之后再调用 + + duix = DUIX(mContext, duixOptions, mDUIXRender) { event, msg, _ -> + } + // ... +} +``` + +### 4. 启动数字人播报 + +在初始化成功后,可以播放音频以驱动形象 + +```kotlin +duix?.playAudio(wavPath) +``` + +参数说明: + +| 参数 | 类型 | 描述 | +|---------|--------|-----------------------------| +| wavPath | String | 16k采样率单通道的wav文件地址或https网络地址 | + +音频播放状态及进度回调: + +```kotlin +object : Callback { + fun onEvent(event: String, msg: String, info: Object) { + when (event) { + // ... + + "play.start" -> { + // 开始播放音频 + } + + "play.end" -> { + // 完成播放音频 + } + "play.error" -> { + // 音频播放异常 + } + "play.progress" -> { + // 音频播放进度 + } + + } + } +} + +``` + +### 5. 终止当前播报 + +当数字人正在播报时调用该接口终止播报。 + +函数定义: + +``` +boolean stopAudio(); +``` + +调用示例如下: + +```kotlin +duix?.stopAudio() +``` + +### 6. 播放动作区间 + +当模型中支持播放动作区间时可使用该函数播放多做区间,多个时随机播放。 + +函数定义: + +``` +void motion(); +``` + +调用示例如下: + +```kotlin +duix?.motion() +``` + +### + +### 四. Proguard配置 + +如果代码使用了混淆,请在proguard-rules.pro中配置: + +``` +-keep class com.btows.ncnntest.**{*; } +-dontwarn com.squareup.okhttp3.** +-keep class com.squareup.okhttp3.** { *;} +``` + +## 五、注意事项 + +1. 驱动渲染必须正确的配置基础配置文件夹和对应模型文件夹的存储路径。 +2. 播放的音频文件不宜过大,过大的音频导入会导致大量消耗CPU,从而造成绘制卡顿。 + + + +## 六、版本记录 diff --git a/duix-android/dh_aigc_android/android_glide_lint.xml b/duix-android/dh_aigc_android/android_glide_lint.xml new file mode 100644 index 0000000000000000000000000000000000000000..90c96a4f60566b2bf7f4cd2da58c3053ce1ee233 --- /dev/null +++ b/duix-android/dh_aigc_android/android_glide_lint.xml @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/duix-android/dh_aigc_android/build.gradle b/duix-android/dh_aigc_android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..d22ff0ce792960a3b1c3a20a83e1bfc76a4755ec --- /dev/null +++ b/duix-android/dh_aigc_android/build.gradle @@ -0,0 +1,39 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + repositories { + + maven { url 'https://maven.aliyun.com/repository/public/' } + maven { url 'https://maven.aliyun.com/repository/central' } + maven { url 'https://maven.aliyun.com/repository/google' } + maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } + maven { url 'https://jitpack.io' } + maven { url 'https://repo1.maven.org/maven2/' } + google() + } + dependencies { + classpath 'com.android.tools.build:gradle:8.1.2' + classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10' + } +} + +allprojects { + repositories { + + maven { url 'https://maven.aliyun.com/repository/public/' } + maven { url 'https://maven.aliyun.com/repository/central' } + maven { url 'https://maven.aliyun.com/repository/google' } + maven { url 'https://maven.aliyun.com/repository/gradle-plugin' } + maven { url 'https://jitpack.io' } + maven { url 'https://repo1.maven.org/maven2/' } + google() + } +} + +ext { + compileSdkVersion = 33 + buildToolsVersion = '30.0.2' + minSdkVersion = 24 + targetSdkVersion = 33 + versionCode = 2 + versionName = "0.0.2" +} diff --git a/duix-android/dh_aigc_android/demo.jks b/duix-android/dh_aigc_android/demo.jks new file mode 100644 index 0000000000000000000000000000000000000000..3cfe0f594f0f2bcf1d273354d7c8d0066868a86c Binary files /dev/null and b/duix-android/dh_aigc_android/demo.jks differ diff --git a/duix-android/dh_aigc_android/duix-sdk/.gitignore b/duix-android/dh_aigc_android/duix-sdk/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..42afabfd2abebf31384ca7797186a27a4b7dbee8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/build.gradle b/duix-android/dh_aigc_android/duix-sdk/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..d4f1a8ae4bac60de29c572be4e4786964b0f8c54 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/build.gradle @@ -0,0 +1,68 @@ +plugins { + id 'com.android.library' +} + +android { + namespace 'ai.guiji.duix.sdk.client' + compileSdk 33 + + defaultConfig { + minSdk 24 + versionCode 4 + versionName '3.0.3' + + externalNativeBuild { + cmake { + abiFilters 'arm64-v8a', "armeabi-v7a" + cppFlags "-std=c++17", "-fexceptions" + //arguments "-DANDROID_STL=c++_shared","-DANDROID_TOOLCHAIN=clang" + } + } + } + + buildTypes { + debug { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + + buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"") + buildConfigField('int', 'VERSION_CODE', "${defaultConfig.versionCode}") + } + + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + + buildConfigField("String", "VERSION_NAME", "\"${defaultConfig.versionName}\"") + buildConfigField('int', 'VERSION_CODE', "${defaultConfig.versionCode}") + + android.libraryVariants.all { variant -> + variant.outputs.all { + outputFileName = "duix_client_sdk_${buildType.name}_${defaultConfig.versionName}.aar" + } + } + } + } + + externalNativeBuild { + cmake { + path "src/main/cpp/CMakeLists.txt" + version "3.10.2" + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +// kotlinOptions { +// jvmTarget = '1.8' +// } +} + +dependencies { + + implementation 'com.google.android.exoplayer:exoplayer:2.14.2' + implementation "org.java-websocket:Java-WebSocket:1.5.1" + implementation 'com.squareup.okhttp3:okhttp-sse:4.10.0' +} \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/consumer-rules.pro b/duix-android/dh_aigc_android/duix-sdk/consumer-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/duix-android/dh_aigc_android/duix-sdk/proguard-rules.pro b/duix-android/dh_aigc_android/duix-sdk/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..a541d5df11e817a798ec59dc442d8e9355afefeb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/proguard-rules.pro @@ -0,0 +1,104 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + +-optimizationpasses 5 #指定代码的压缩级别 0 - 7,一般都是5,无需改变 +-dontusemixedcaseclassnames #不使用大小写混合 +#告诉Proguard 不要跳过对非公开类的处理,默认是跳过 +-dontskipnonpubliclibraryclasses #如果应用程序引入的有jar包,并且混淆jar包里面的class +-verbose #混淆时记录日志(混淆后生产映射文件 map 类名 -> 转化后类名的映射 +#指定混淆时的算法,后面的参数是一个过滤器 +#这个过滤器是谷歌推荐的算法,一般也不会改变 +-optimizations !code/simplification/arithmetic,!field/*,!class/merging/* +#类型转换错误 添加如下代码以便过滤泛型(不写可能会出现类型转换错误,一般情况把这个加上就是了),即避免泛型被混淆 +-keepattributes Signature +#假如项目中有用到注解,应加入这行配置,对JSON实体映射也很重要,eg:fastjson +-keepattributes *Annotation* +#抛出异常时保留代码行数 +-keepattributes SourceFile,LineNumberTable +#保持 native 的方法不去混淆 +-keepclasseswithmembernames class * { + native ; +} + +#保持指定规则的方法不被混淆(Android layout 布局文件中为控件配置的onClick方法不能混淆) +-keepclassmembers class * extends android.app.Activity { + public void *(android.view.View); +} +#保持自定义控件指定规则的方法不被混淆 +-keep public class * extends android.view.View { + public (android.content.Context); + public (android.content.Context, android.util.AttributeSet); + public (android.content.Context, android.util.AttributeSet, int); + public void set*(...); +} +#保持枚举 enum 不被混淆 +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} +#保持 Parcelable 不被混淆(aidl文件不能去混淆) +-keep class * implements android.os.Parcelable { + public static final android.os.Parcelable$Creator *; +} +#需要序列化和反序列化的类不能被混淆(注:Java反射用到的类也不能被混淆) +-keepnames class * implements java.io.Serializable +#保护实现接口Serializable的类中,指定规则的类成员不被混淆 +-keepclassmembers class * implements java.io.Serializable { + static final long serialVersionUID; + private static final java.io.ObjectStreamField[] serialPersistentFields; + !static !transient ; + private void writeObject(java.io.ObjectOutputStream); + private void readObject(java.io.ObjectInputStream); + java.lang.Object writeReplace(); + java.lang.Object readResolve(); +} +#保持R文件不被混淆,否则,你的反射是获取不到资源id的 +-keep class **.R$* { *; } + +-keepclassmembers class * { + public (org.json.JSONObject); +} + +-keepclassmembers enum * { + public static **[] values(); + public static ** valueOf(java.lang.String); +} + + +#以下针对App本身设置 + + +-keep class com.btows.ncnntest.**{*; } + +-keep class ai.guiji.duix.sdk.client.render.** {*;} +-keep class ai.guiji.duix.sdk.client.render.**$* {*;} +-keep class ai.guiji.duix.sdk.client.bean.** {*;} +-keep class ai.guiji.duix.sdk.client.DUIX{*; } +-keep class ai.guiji.duix.sdk.client.DUIX$* {*;} +-keep class ai.guiji.duix.sdk.client.Constant{*; } +-keep class ai.guiji.duix.sdk.client.Constant* {*;} +-keep class ai.guiji.duix.sdk.client.DUIXOptions{*; } +-keep class ai.guiji.duix.sdk.client.DUIXOptions* {*;} +-keep class ai.guiji.duix.sdk.client.Callback{*; } +-keep class ai.guiji.duix.sdk.client.Callback* {*;} +-keep class ai.guiji.duix.sdk.client.render.DUIXTextureView{*; } +-keep class ai.guiji.duix.sdk.client.render.DUIXTextureView$* {*;} \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/AndroidManifest.xml b/duix-android/dh_aigc_android/duix-sdk/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..a8800291f3c2fb5aa0455bb8d4341b7f5528aeeb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/Android.mk64 b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/Android.mk64 new file mode 100644 index 0000000000000000000000000000000000000000..cc93d444e645902a3321cf140b31d24c229bf4a8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/Android.mk64 @@ -0,0 +1,86 @@ +#/**************************************************************************** +#* Cartoonifier, for Android. +#***************************************************************************** +#* by Shervin Emami, 5th Dec 2012 (shervin.emami@gmail.com) +#* http://www.shervinemami.info/ +#***************************************************************************** +#* Ch1 of the book "Mastering OpenCV with Practical Computer Vision Projects" +#* Copyright Packt Publishing 2012. +#* http://www.packtpub.com/cool-projects-with-opencv/book +#****************************************************************************/ + + +LOCAL_PATH := $(call my-dir) + + +include $(CLEAR_VARS) + + + +LOCAL_SRC_FILES += \ + base/coffeecatch.c \ + android/DigitJni.cpp \ + android/MsgcbJni.cpp \ + android/JniHelper.cpp \ + aisdk/jmat.cpp \ + android/kmatarm.cpp \ + aisdk/wavreader.cpp \ + aisdk/wenet.cpp \ + aisdk/aimodel.cpp \ + aisdk/scrfd.cpp \ + aisdk/pfpld.cpp \ + aisdk/munet.cpp \ + aisdk/blendgram.cpp \ + aisdk/face_utils.cpp \ + digit/netwav.cpp \ + digit/looper.cpp \ + digit/netcurl.cpp \ + digit/GRender.cpp \ + digit/GDigit.cpp \ + digit/dispatchqueue.cpp \ + render/EglRenderer.cpp \ + render/RgbVideoRenderer.cpp \ + render/SurfaceVideoRenderer.cpp \ + render/RenderHelper.cpp \ + render/AudioTrack.cpp \ + render/AudioRenderer.cpp \ + render/GlesProgram.cpp \ + base/Log.cpp \ + base/FrameSource.cpp \ + base/MediaData.cpp \ + base/MessageSource.cpp \ + base/MessageHelper.cpp \ + base/LoopThread.cpp \ + base/XThread.cpp \ + base/XTick.c \ + base/cJSON.c \ + base/dh_mem.c \ + digit/grtcfg.c \ + base/LoopThreadHelper.cpp \ + ) + +LOCAL_ARM_NEON := true +LOCAL_MODULE := facedetect +LOCAL_LDLIBS += -llog -ldl -lm -lmediandk +LOCAL_LDLIBS += -lEGL -lGLESv2 -landroid +LOCAL_LDLIBS += -ljnigraphics -fopenmp + +LOCAL_CFLAGS += -fpermissive +LOCAL_CPPFLAGS += -fpermissive +#LOCAL_CFLAGS += -ftree-vectorizer-verbose=2 +LOCAL_CPPFLAGS += -std=c++17 +LOCAL_LDLIBS += -lstdc++ + +LOCAL_C_INCLUDES += $(LOCAL_PATH) +LOCAL_C_INCLUDES += include +LOCAL_C_INCLUDES += base +LOCAL_C_INCLUDES += aisdk +LOCAL_C_INCLUDES += digit +LOCAL_C_INCLUDES += render +LOCAL_C_INCLUDES += android +LOCAL_C_INCLUDES += third/arm/include +LOCAL_C_INCLUDES += third/arm/include/ncnn +LOCAL_C_INCLUDES += third/opencv-mobile-4.6.0-android/sdk/native/jni/include/ +LOCAL_C_INCLUDES += third/ncnn-20221128-android-vulkan-shared/arm64-v8a/include/ncnn + +include $(BUILD_SHARED_LIBRARY) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..199c716d6b0534229b1412368fd6aa63c6ca88ef --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/CMakeLists.txt @@ -0,0 +1,169 @@ +project(scrfdncnn) + +cmake_minimum_required(VERSION 3.10.2) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -funwind-tables") + +set(OpenCV_DIR ${CMAKE_SOURCE_DIR}/third/opencv-mobile-4.6.0-android/sdk/native/jni) +find_package(OpenCV REQUIRED core imgproc highgui) + +#set(ncnn_DIR ${CMAKE_SOURCE_DIR}/third/ncnn-20221128-android-vulkan-shared/${ANDROID_ABI}/lib/cmake/ncnn) +set(ncnn_DIR ${CMAKE_SOURCE_DIR}/third/ncnn-20231027-android-shared/${ANDROID_ABI}/lib/cmake/ncnn) +find_package(ncnn REQUIRED) + + +option(USE_OPENCV "shared library support" TRUE) +option(USE_NCNN "shared library support" TRUE) + +include_directories( + include + base + render + aisdk + aes + digit + android + third/arm/include + third/arm/include/turbojpeg + ) + +add_library(scrfdncnn SHARED + android/DigitJni.cpp + android/MsgcbJni.cpp + android/JniHelper.cpp + aisdk/jmat.cpp + aisdk/wavreader.cpp + aisdk/wenet.cpp + aisdk/aimodel.cpp + aisdk/scrfd.cpp + aisdk/pfpld.cpp + aisdk/munet.cpp + aisdk/malpha.cpp + aisdk/wavcache.cpp + aisdk/blendgram.cpp + aisdk/face_utils.cpp + aisdk/netwav.cpp + digit/looper.cpp + digit/netcurl.cpp + digit/GRender.cpp + digit/GDigit.cpp + digit/dispatchqueue.cpp + render/EglRenderer.cpp + render/RgbVideoRenderer.cpp + render/SurfaceVideoRenderer.cpp + render/RenderHelper.cpp + base/BaseRenderHelper.cpp + base/AudioTrack.cpp + render/AudioRenderer.cpp + render/GlesProgram.cpp + base/Log.cpp + base/FrameSource.cpp + base/MediaData.cpp + base/MessageSource.cpp + base/MessageHelper.cpp + base/LoopThread.cpp + base/XThread.cpp + base/XTick.c + base/cJSON.c + base/dh_mem.c + digit/grtcfg.c + base/LoopThreadHelper.cpp + base/coffeecatch.c + aes/aes_cbc.c aes/aes_core.c aes/aes_ecb.c aes/base64.c aes/cbc128.c aes/gj_aes.c + aes/aesmain.c + ) + + +add_library(turbojpeg STATIC IMPORTED) +set_target_properties(turbojpeg + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libturbojpeg.a) + +add_library(libjpeg STATIC IMPORTED) +set_target_properties(libjpeg + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libjpeg.a) + + #add_library(pplcommon STATIC IMPORTED) +#set_target_properties(pplcommon + # PROPERTIES IMPORTED_LOCATION + # ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libpplcommon_static.a) + + #add_library(pplcv STATIC IMPORTED) +#set_target_properties(pplcv + # PROPERTIES IMPORTED_LOCATION + # ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libpplcv_static.a) + +add_library(curl STATIC IMPORTED) +set_target_properties(curl + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libcurl.a) + +add_library(ssl STATIC IMPORTED) +set_target_properties(ssl + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libssl.a) + +add_library(crypto STATIC IMPORTED) +set_target_properties(crypto + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libcrypto.a) + +add_library(avcodec STATIC IMPORTED) +set_target_properties(avcodec + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/ffmpeg-lite/libavcodec.a) + +add_library(avformat STATIC IMPORTED) +set_target_properties(avformat + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/ffmpeg-lite/libavformat.a) + +add_library(avutil STATIC IMPORTED) +set_target_properties(avutil + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/ffmpeg-lite/libavutil.a) + +add_library(swresample STATIC IMPORTED) +set_target_properties(swresample + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/ffmpeg-lite/libswresample.a) + +add_library(swscale STATIC IMPORTED) +set_target_properties(swscale + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/ffmpeg-lite/libswscale.a) + +find_library(log-lib log) + +add_library(onnx-lib SHARED IMPORTED) +set_target_properties( + onnx-lib + PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/third/arm/${ANDROID_ABI}/libonnxruntime.so) + +target_link_libraries(scrfdncnn + ncnn + ${OpenCV_LIBS} + ${log-lib} + onnx-lib + camera2ndk + mediandk + libjpeg + turbojpeg + avformat + avcodec + avutil + swresample + swscale + curl + ssl + crypto + -landroid + -lmediandk + -lEGL + -lGLESv2 + -lm -lz +) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes.h new file mode 100644 index 0000000000000000000000000000000000000000..854538ee0a1a75aa55ee5d385d9863048053f134 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes.h @@ -0,0 +1,41 @@ + + +#ifndef HEADER_AES_H +# define HEADER_AES_H + +# include + +# define AES_ENCRYPT 1 +# define AES_DECRYPT 0 + +# define AES_MAXNR 14 +# define AES_BLOCK_SIZE 16 + +struct aes_key_st { +# ifdef AES_LONG + unsigned long rd_key[4 * (AES_MAXNR + 1)]; +# else + unsigned int rd_key[4 * (AES_MAXNR + 1)]; +# endif + int rounds; +}; + +typedef struct aes_key_st AES_KEY; + + +int AES_set_encrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key); +int AES_set_decrypt_key(const unsigned char *userKey, const int bits, AES_KEY *key); + +void AES_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); +void AES_decrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key); + +void AES_ecb_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key, + const int enc); + +void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t length, const AES_KEY *key, + unsigned char *ivec, const int enc); + +#endif + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_cbc.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_cbc.c new file mode 100644 index 0000000000000000000000000000000000000000..3925bb1a0a987d7db7dbf59a3959ab74ef715a11 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_cbc.c @@ -0,0 +1,23 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include "aes.h" +#include "modes.h" + +void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const AES_KEY *key, + unsigned char *ivec, const int enc) +{ + + if (enc) + CRYPTO_cbc128_encrypt(in, out, len, key, ivec, + (block128_f) AES_encrypt); + else + CRYPTO_cbc128_decrypt(in, out, len, key, ivec, (block128_f) AES_decrypt); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_core.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_core.c new file mode 100644 index 0000000000000000000000000000000000000000..58013093f0d97ce028156d3b6c41cd27882f94f5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_core.c @@ -0,0 +1,1127 @@ +#include + +#include "aes.h" +#include "aes_locl.h" + + + +/*- +Te0[x] = S [x].[02, 01, 01, 03]; +Te1[x] = S [x].[03, 02, 01, 01]; +Te2[x] = S [x].[01, 03, 02, 01]; +Te3[x] = S [x].[01, 01, 03, 02]; + +Td0[x] = Si[x].[0e, 09, 0d, 0b]; +Td1[x] = Si[x].[0b, 0e, 09, 0d]; +Td2[x] = Si[x].[0d, 0b, 0e, 09]; +Td3[x] = Si[x].[09, 0d, 0b, 0e]; +Td4[x] = Si[x].[01]; +*/ + +static const u32 Te0[256] = { + 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, + 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, + 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, + 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, + 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, + 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, + 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, + 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, + 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, + 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, + 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, + 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, + 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, + 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, + 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, + 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, + 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, + 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, + 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, + 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, + 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, + 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, + 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, + 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, + 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, + 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, + 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, + 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, + 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, + 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, + 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, + 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, + 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, + 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, + 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, + 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, + 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, + 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, + 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, + 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, + 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, + 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, + 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, + 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, + 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, + 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, + 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, + 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, + 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, + 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, + 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, + 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, + 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, + 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, + 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, + 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, + 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, + 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, + 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, + 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, + 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, + 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, + 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, + 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, +}; +static const u32 Te1[256] = { + 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, + 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, + 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, + 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, + 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, + 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, + 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, + 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, + 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, + 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, + 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, + 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, + 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, + 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, + 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, + 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, + 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, + 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, + 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, + 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, + 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, + 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, + 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, + 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, + 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, + 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, + 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, + 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, + 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, + 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, + 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, + 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, + 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, + 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, + 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, + 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, + 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, + 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, + 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, + 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, + 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, + 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, + 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, + 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, + 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, + 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, + 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, + 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, + 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, + 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, + 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, + 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, + 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, + 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, + 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, + 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, + 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, + 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, + 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, + 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, + 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, + 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, + 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, + 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, +}; +static const u32 Te2[256] = { + 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, + 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, + 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, + 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, + 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, + 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, + 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, + 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, + 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, + 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, + 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, + 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, + 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, + 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, + 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, + 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, + 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, + 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, + 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, + 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, + 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, + 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, + 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, + 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, + 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, + 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, + 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, + 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, + 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, + 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, + 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, + 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, + 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, + 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, + 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, + 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, + 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, + 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, + 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, + 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, + 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, + 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, + 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, + 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, + 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, + 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, + 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, + 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, + 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, + 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, + 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, + 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, + 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, + 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, + 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, + 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, + 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, + 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, + 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, + 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, + 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, + 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, + 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, + 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, +}; +static const u32 Te3[256] = { + 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, + 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, + 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, + 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, + 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, + 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, + 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, + 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, + 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, + 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, + 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, + 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, + 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, + 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, + 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, + 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, + 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, + 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, + 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, + 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, + 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, + 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, + 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, + 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, + 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, + 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, + 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, + 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, + 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, + 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, + 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, + 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, + 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, + 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, + 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, + 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, + 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, + 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, + 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, + 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, + 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, + 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, + 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, + 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, + 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, + 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, + 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, + 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, + 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, + 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, + 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, + 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, + 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, + 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, + 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, + 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, + 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, + 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, + 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, + 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, + 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, + 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, + 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, + 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, +}; + +static const u32 Td0[256] = { + 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, + 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, + 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, + 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, + 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, + 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, + 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, + 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, + 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, + 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, + 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, + 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, + 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, + 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, + 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, + 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, + 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, + 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, + 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, + 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, + 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, + 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, + 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, + 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, + 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, + 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, + 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, + 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, + 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, + 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, + 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, + 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, + 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, + 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, + 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, + 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, + 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, + 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, + 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, + 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, + 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, + 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, + 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, + 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, + 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, + 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, + 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, + 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, + 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, + 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, + 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, + 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, + 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, + 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, + 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, + 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, + 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, + 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, + 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, + 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, + 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, + 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, + 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, + 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, +}; +static const u32 Td1[256] = { + 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, + 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, + 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, + 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, + 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, + 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, + 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, + 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, + 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, + 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, + 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, + 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, + 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, + 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, + 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, + 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, + 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, + 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, + 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, + 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, + 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, + 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, + 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, + 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, + 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, + 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, + 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, + 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, + 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, + 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, + 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, + 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, + 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, + 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, + 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, + 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, + 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, + 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, + 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, + 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, + 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, + 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, + 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, + 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, + 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, + 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, + 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, + 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, + 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, + 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, + 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, + 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, + 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, + 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, + 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, + 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, + 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, + 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, + 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, + 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, + 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, + 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, + 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, + 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, +}; +static const u32 Td2[256] = { + 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, + 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, + 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, + 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, + 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, + 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, + 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, + 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, + 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, + 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, + 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, + 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, + 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, + 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, + 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, + 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, + 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, + 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, + 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, + 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, + 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, + 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, + 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, + 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, + 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, + 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, + 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, + 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, + 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, + 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, + 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, + 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, + 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, + 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, + 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, + 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, + 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, + 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, + 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, + 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, + 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, + 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, + 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, + 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, + 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, + 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, + 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, + 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, + 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, + 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, + 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, + 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, + 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, + 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, + 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, + 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, + 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, + 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, + 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, + 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, + 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, + 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, + 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, + 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, +}; +static const u32 Td3[256] = { + 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, + 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, + 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, + 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, + 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, + 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, + 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, + 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, + 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, + 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, + 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, + 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, + 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, + 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, + 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, + 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, + 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, + 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, + 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, + 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, + 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, + 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, + 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, + 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, + 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, + 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, + 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, + 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, + 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, + 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, + 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, + 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, + 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, + 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, + 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, + 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, + 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, + 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, + 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, + 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, + 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, + 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, + 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, + 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, + 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, + 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, + 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, + 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, + 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, + 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, + 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, + 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, + 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, + 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, + 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, + 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, + 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, + 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, + 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, + 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, + 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, + 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, + 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, + 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, +}; +static const u8 Td4[256] = { + 0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U, + 0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU, + 0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U, + 0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU, + 0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU, + 0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU, + 0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U, + 0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U, + 0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U, + 0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U, + 0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU, + 0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U, + 0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU, + 0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U, + 0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U, + 0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU, + 0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU, + 0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U, + 0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U, + 0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU, + 0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U, + 0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU, + 0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U, + 0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U, + 0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U, + 0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU, + 0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU, + 0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU, + 0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U, + 0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U, + 0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U, + 0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU, +}; +static const u32 rcon[] = { + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */ +}; + +/** + * Expand the cipher key into the encryption key schedule. + */ +int AES_set_encrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i = 0; + u32 temp; + + if (!userKey || !key) + return -1; + if (bits != 128 && bits != 192 && bits != 256) + return -2; + + rk = key->rd_key; + + if (bits == 128) + key->rounds = 10; + else if (bits == 192) + key->rounds = 12; + else + key->rounds = 14; + + rk[0] = GETU32(userKey ); + rk[1] = GETU32(userKey + 4); + rk[2] = GETU32(userKey + 8); + rk[3] = GETU32(userKey + 12); + if (bits == 128) { + while (1) { + temp = rk[3]; + rk[4] = rk[0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[5] = rk[1] ^ rk[4]; + rk[6] = rk[2] ^ rk[5]; + rk[7] = rk[3] ^ rk[6]; + if (++i == 10) { + return 0; + } + rk += 4; + } + } + rk[4] = GETU32(userKey + 16); + rk[5] = GETU32(userKey + 20); + if (bits == 192) { + while (1) { + temp = rk[ 5]; + rk[ 6] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 7] = rk[ 1] ^ rk[ 6]; + rk[ 8] = rk[ 2] ^ rk[ 7]; + rk[ 9] = rk[ 3] ^ rk[ 8]; + if (++i == 8) { + return 0; + } + rk[10] = rk[ 4] ^ rk[ 9]; + rk[11] = rk[ 5] ^ rk[10]; + rk += 6; + } + } + rk[6] = GETU32(userKey + 24); + rk[7] = GETU32(userKey + 28); + if (bits == 256) { + while (1) { + temp = rk[ 7]; + rk[ 8] = rk[ 0] ^ + (Te2[(temp >> 16) & 0xff] & 0xff000000) ^ + (Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^ + (Te0[(temp ) & 0xff] & 0x0000ff00) ^ + (Te1[(temp >> 24) ] & 0x000000ff) ^ + rcon[i]; + rk[ 9] = rk[ 1] ^ rk[ 8]; + rk[10] = rk[ 2] ^ rk[ 9]; + rk[11] = rk[ 3] ^ rk[10]; + if (++i == 7) { + return 0; + } + temp = rk[11]; + rk[12] = rk[ 4] ^ + (Te2[(temp >> 24) ] & 0xff000000) ^ + (Te3[(temp >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(temp >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(temp ) & 0xff] & 0x000000ff); + rk[13] = rk[ 5] ^ rk[12]; + rk[14] = rk[ 6] ^ rk[13]; + rk[15] = rk[ 7] ^ rk[14]; + + rk += 8; + } + } + return 0; +} + +/** + * Expand the cipher key into the decryption key schedule. + */ +int AES_set_decrypt_key(const unsigned char *userKey, const int bits, + AES_KEY *key) +{ + + u32 *rk; + int i, j, status; + u32 temp; + + /* first, start with an encryption schedule */ + status = AES_set_encrypt_key(userKey, bits, key); + if (status < 0) + return status; + + rk = key->rd_key; + + /* invert the order of the round keys: */ + for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) { + temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp; + temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp; + temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp; + temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp; + } + /* apply the inverse MixColumn transform to all round keys but the first and the last: */ + for (i = 1; i < (key->rounds); i++) { + rk += 4; + rk[0] = + Td0[Te1[(rk[0] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[0] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[0] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[0] ) & 0xff] & 0xff]; + rk[1] = + Td0[Te1[(rk[1] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[1] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[1] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[1] ) & 0xff] & 0xff]; + rk[2] = + Td0[Te1[(rk[2] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[2] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[2] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[2] ) & 0xff] & 0xff]; + rk[3] = + Td0[Te1[(rk[3] >> 24) ] & 0xff] ^ + Td1[Te1[(rk[3] >> 16) & 0xff] & 0xff] ^ + Td2[Te1[(rk[3] >> 8) & 0xff] & 0xff] ^ + Td3[Te1[(rk[3] ) & 0xff] & 0xff]; + } + return 0; +} + +/* + * Encrypt a single block + * in and out can overlap + */ +void AES_encrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) { + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48]; + s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49]; + s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50]; + s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52]; + t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53]; + t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54]; + t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Te0[(s0 >> 24) ] ^ + Te1[(s1 >> 16) & 0xff] ^ + Te2[(s2 >> 8) & 0xff] ^ + Te3[(s3 ) & 0xff] ^ + rk[4]; + t1 = + Te0[(s1 >> 24) ] ^ + Te1[(s2 >> 16) & 0xff] ^ + Te2[(s3 >> 8) & 0xff] ^ + Te3[(s0 ) & 0xff] ^ + rk[5]; + t2 = + Te0[(s2 >> 24) ] ^ + Te1[(s3 >> 16) & 0xff] ^ + Te2[(s0 >> 8) & 0xff] ^ + Te3[(s1 ) & 0xff] ^ + rk[6]; + t3 = + Te0[(s3 >> 24) ] ^ + Te1[(s0 >> 16) & 0xff] ^ + Te2[(s1 >> 8) & 0xff] ^ + Te3[(s2 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Te0[(t0 >> 24) ] ^ + Te1[(t1 >> 16) & 0xff] ^ + Te2[(t2 >> 8) & 0xff] ^ + Te3[(t3 ) & 0xff] ^ + rk[0]; + s1 = + Te0[(t1 >> 24) ] ^ + Te1[(t2 >> 16) & 0xff] ^ + Te2[(t3 >> 8) & 0xff] ^ + Te3[(t0 ) & 0xff] ^ + rk[1]; + s2 = + Te0[(t2 >> 24) ] ^ + Te1[(t3 >> 16) & 0xff] ^ + Te2[(t0 >> 8) & 0xff] ^ + Te3[(t1 ) & 0xff] ^ + rk[2]; + s3 = + Te0[(t3 >> 24) ] ^ + Te1[(t0 >> 16) & 0xff] ^ + Te2[(t1 >> 8) & 0xff] ^ + Te3[(t2 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + (Te2[(t0 >> 24) ] & 0xff000000) ^ + (Te3[(t1 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t2 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t3 ) & 0xff] & 0x000000ff) ^ + rk[0]; + PUTU32(out , s0); + s1 = + (Te2[(t1 >> 24) ] & 0xff000000) ^ + (Te3[(t2 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t3 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t0 ) & 0xff] & 0x000000ff) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + (Te2[(t2 >> 24) ] & 0xff000000) ^ + (Te3[(t3 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t0 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t1 ) & 0xff] & 0x000000ff) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + (Te2[(t3 >> 24) ] & 0xff000000) ^ + (Te3[(t0 >> 16) & 0xff] & 0x00ff0000) ^ + (Te0[(t1 >> 8) & 0xff] & 0x0000ff00) ^ + (Te1[(t2 ) & 0xff] & 0x000000ff) ^ + rk[3]; + PUTU32(out + 12, s3); +} + +/* + * Decrypt a single block + * in and out can overlap + */ +void AES_decrypt(const unsigned char *in, unsigned char *out, + const AES_KEY *key) +{ + + const u32 *rk; + u32 s0, s1, s2, s3, t0, t1, t2, t3; +#ifndef FULL_UNROLL + int r; +#endif /* ?FULL_UNROLL */ + + assert(in && out && key); + rk = key->rd_key; + + /* + * map byte array block to cipher state + * and add initial round key: + */ + s0 = GETU32(in ) ^ rk[0]; + s1 = GETU32(in + 4) ^ rk[1]; + s2 = GETU32(in + 8) ^ rk[2]; + s3 = GETU32(in + 12) ^ rk[3]; +#ifdef FULL_UNROLL + /* round 1: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7]; + /* round 2: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11]; + /* round 3: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15]; + /* round 4: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19]; + /* round 5: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23]; + /* round 6: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27]; + /* round 7: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31]; + /* round 8: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35]; + /* round 9: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39]; + if (key->rounds > 10) { + /* round 10: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43]; + /* round 11: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47]; + if (key->rounds > 12) { + /* round 12: */ + s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48]; + s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49]; + s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50]; + s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51]; + /* round 13: */ + t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52]; + t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53]; + t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54]; + t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55]; + } + } + rk += key->rounds << 2; +#else /* !FULL_UNROLL */ + /* + * Nr - 1 full rounds: + */ + r = key->rounds >> 1; + for (;;) { + t0 = + Td0[(s0 >> 24) ] ^ + Td1[(s3 >> 16) & 0xff] ^ + Td2[(s2 >> 8) & 0xff] ^ + Td3[(s1 ) & 0xff] ^ + rk[4]; + t1 = + Td0[(s1 >> 24) ] ^ + Td1[(s0 >> 16) & 0xff] ^ + Td2[(s3 >> 8) & 0xff] ^ + Td3[(s2 ) & 0xff] ^ + rk[5]; + t2 = + Td0[(s2 >> 24) ] ^ + Td1[(s1 >> 16) & 0xff] ^ + Td2[(s0 >> 8) & 0xff] ^ + Td3[(s3 ) & 0xff] ^ + rk[6]; + t3 = + Td0[(s3 >> 24) ] ^ + Td1[(s2 >> 16) & 0xff] ^ + Td2[(s1 >> 8) & 0xff] ^ + Td3[(s0 ) & 0xff] ^ + rk[7]; + + rk += 8; + if (--r == 0) { + break; + } + + s0 = + Td0[(t0 >> 24) ] ^ + Td1[(t3 >> 16) & 0xff] ^ + Td2[(t2 >> 8) & 0xff] ^ + Td3[(t1 ) & 0xff] ^ + rk[0]; + s1 = + Td0[(t1 >> 24) ] ^ + Td1[(t0 >> 16) & 0xff] ^ + Td2[(t3 >> 8) & 0xff] ^ + Td3[(t2 ) & 0xff] ^ + rk[1]; + s2 = + Td0[(t2 >> 24) ] ^ + Td1[(t1 >> 16) & 0xff] ^ + Td2[(t0 >> 8) & 0xff] ^ + Td3[(t3 ) & 0xff] ^ + rk[2]; + s3 = + Td0[(t3 >> 24) ] ^ + Td1[(t2 >> 16) & 0xff] ^ + Td2[(t1 >> 8) & 0xff] ^ + Td3[(t0 ) & 0xff] ^ + rk[3]; + } +#endif /* ?FULL_UNROLL */ + /* + * apply last round and + * map cipher state to byte array block: + */ + s0 = + ((u32)Td4[(t0 >> 24) ] << 24) ^ + ((u32)Td4[(t3 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t2 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t1 ) & 0xff]) ^ + rk[0]; + PUTU32(out , s0); + s1 = + ((u32)Td4[(t1 >> 24) ] << 24) ^ + ((u32)Td4[(t0 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t3 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t2 ) & 0xff]) ^ + rk[1]; + PUTU32(out + 4, s1); + s2 = + ((u32)Td4[(t2 >> 24) ] << 24) ^ + ((u32)Td4[(t1 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t0 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t3 ) & 0xff]) ^ + rk[2]; + PUTU32(out + 8, s2); + s3 = + ((u32)Td4[(t3 >> 24) ] << 24) ^ + ((u32)Td4[(t2 >> 16) & 0xff] << 16) ^ + ((u32)Td4[(t1 >> 8) & 0xff] << 8) ^ + ((u32)Td4[(t0 ) & 0xff]) ^ + rk[3]; + PUTU32(out + 12, s3); +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_ecb.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_ecb.c new file mode 100644 index 0000000000000000000000000000000000000000..647680319917cb2d93c29afe7af89b9f22638d0c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_ecb.c @@ -0,0 +1,24 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#include + +#include "aes.h" +#include "aes_locl.h" + +void AES_ecb_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key, const int enc) +{ + assert(in && out && key); + assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc)); + + if (AES_ENCRYPT == enc) + AES_encrypt(in, out, key); + else + AES_decrypt(in, out, key); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_locl.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_locl.h new file mode 100644 index 0000000000000000000000000000000000000000..47d1dfa5a5bfbe383b8e6168667f73c362fec2e1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aes_locl.h @@ -0,0 +1,42 @@ +/* + * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_AES_LOCL_H +# define HEADER_AES_LOCL_H + +//# include +# include +# include +# include + +# if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)) +# define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00) +# define GETU32(p) SWAP(*((u32 *)(p))) +# define PUTU32(ct, st) { *((u32 *)(ct)) = SWAP((st)); } +# else +# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3])) +# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); } +# endif + +# ifdef AES_LONG +typedef unsigned long u32; +# else +typedef unsigned int u32; +# endif +typedef unsigned short u16; +typedef unsigned char u8; + +# define MAXKC (256/32) +# define MAXKB (256/8) +# define MAXNR 14 + +/* This controls loop-unrolling in aes_core.c */ +# undef FULL_UNROLL + +#endif /* !HEADER_AES_LOCL_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.c new file mode 100644 index 0000000000000000000000000000000000000000..547eaf55e069a0950832d639acda43672d88a2fc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.c @@ -0,0 +1,111 @@ +#include +#include +#include +#include +#include "gj_aes.h" +#include "aesmain.h" + +int mainenc(int enc,char* infn,char* outfn){ + char result[255] ; + memset(result,0,255); + char* key = "yymrjzbwyrbjszrk"; + char* aiv = "yymrjzbwyrbjszrk"; + int base64 = 1; + int outlen = 0; + int encrst = 0; + char* fn1 = infn; + char* fn2 = outfn; + FILE* fr = fopen(fn1,"rb"); + FILE* fw = fopen(fn2,"wb"); + while(1){ + if(!fr){ + encrst = -1001; + break; + } + if(!fw){ + encrst = -1002; + break; + } + gj_aesc_t* aesc = NULL; + init_aesc(key,aiv,enc,&aesc); + uint64_t size = 0; + uint64_t realsize = 0; + if(enc){ + fwrite("gjdigits",1,8,fw); + fwrite(&size,1,8,fw); + fwrite(&size,1,8,fw); + fwrite(&size,1,8,fw); + + while(!feof(fr)){ + char data[16]; + memset(data,0,16); + uint64_t rst = fread(data,1,16,fr); + if(rst){ + size +=rst; + do_aesc(aesc,data,16,result,&outlen); + fwrite(result,1,outlen,fw); + } + } + fseek(fw,8,0); + fwrite(&size,1,8,fw); + + }else{ + uint64_t rst = fread(result,1,32,fr); + if(!rst){ + encrst = -1003; + break; + } + if((result[0]!='g')||(result[1]!='j')){ + encrst = -1004; + break; + } + uint64_t *psize = (uint64_t*)(result+8); + realsize = *psize; + if(realsize>1034*1024*1024){ + encrst = -1005; + break; + } + while(!feof(fr)){ + char data[16]; + memset(data,0,16); + uint64_t rst = fread(data,1,16,fr); + if(rst){ + size +=rst; + do_aesc(aesc,data,16,result,&outlen); + if(size>realsize){ + outlen -= (size-realsize); + //printf("===%lu > %lu rst %lu %d outlen \n",size,realsize,rst,outlen); + } + fwrite(result,1,outlen,fw); + } + } + } + break; + } + if(fr) fclose(fr); + if(fw) fclose(fw); + return encrst; +} + + +#ifdef TEST +int main(int argc,char** argv){ + if(argc<4){ + printf("gaes enc|dec filein fileout\n"); + return 0; + } + char k = argv[1][0]; + if(k=='e'){ + int rst = mainenc(1,argv[2],argv[3]); + printf("====enc %s to %s rst %d\n",argv[2],argv[3],rst); + return rst; + }else if(k=='d'){ + int rst = mainenc(0,argv[2],argv[3]); + printf("====dec %s to %s rst %d\n",argv[2],argv[3],rst); + return rst; + }else{ + printf("gaes enc|dec filein fileout\n"); + return 0; + } +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.h new file mode 100644 index 0000000000000000000000000000000000000000..48e53df4c4e8064ee0cbdf9855d2f997a880735b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/aesmain.h @@ -0,0 +1,16 @@ + +#ifndef __AESMAIN_H +#define __AESMAIN_H + +#include "gj_dll.h" +#ifdef __cplusplus +extern "C" { +#endif + +int mainenc(int enc,char* infn,char* outfn); + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.c new file mode 100644 index 0000000000000000000000000000000000000000..a35725db44df58fae410837dc33bb2561c2f68e2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.c @@ -0,0 +1,164 @@ +/* This is a public domain base64 implementation written by WEI Zhicheng. */ + +#include "base64.h" + +#define BASE64_PAD '=' +#define BASE64DE_FIRST '+' +#define BASE64DE_LAST 'z' + +/* BASE 64 encode table */ +static const char base64en[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '+', '/', +}; + +/* ASCII order for BASE 64 decode, 255 in unused character */ +static const unsigned char base64de[] = { + /* nul, soh, stx, etx, eot, enq, ack, bel, */ + 255, 255, 255, 255, 255, 255, 255, 255, + + /* bs, ht, nl, vt, np, cr, so, si, */ + 255, 255, 255, 255, 255, 255, 255, 255, + + /* dle, dc1, dc2, dc3, dc4, nak, syn, etb, */ + 255, 255, 255, 255, 255, 255, 255, 255, + + /* can, em, sub, esc, fs, gs, rs, us, */ + 255, 255, 255, 255, 255, 255, 255, 255, + + /* sp, '!', '"', '#', '$', '%', '&', ''', */ + 255, 255, 255, 255, 255, 255, 255, 255, + + /* '(', ')', '*', '+', ',', '-', '.', '/', */ + 255, 255, 255, 62, 255, 255, 255, 63, + + /* '0', '1', '2', '3', '4', '5', '6', '7', */ + 52, 53, 54, 55, 56, 57, 58, 59, + + /* '8', '9', ':', ';', '<', '=', '>', '?', */ + 60, 61, 255, 255, 255, 255, 255, 255, + + /* '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', */ + 255, 0, 1, 2, 3, 4, 5, 6, + + /* 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', */ + 7, 8, 9, 10, 11, 12, 13, 14, + + /* 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', */ + 15, 16, 17, 18, 19, 20, 21, 22, + + /* 'X', 'Y', 'Z', '[', '\', ']', '^', '_', */ + 23, 24, 25, 255, 255, 255, 255, 255, + + /* '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', */ + 255, 26, 27, 28, 29, 30, 31, 32, + + /* 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', */ + 33, 34, 35, 36, 37, 38, 39, 40, + + /* 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', */ + 41, 42, 43, 44, 45, 46, 47, 48, + + /* 'x', 'y', 'z', '{', '|', '}', '~', del, */ + 49, 50, 51, 255, 255, 255, 255, 255 +}; + +unsigned int +gjbase64_encode(const unsigned char *in, unsigned int inlen, char *out) +{ + int s; + unsigned int i; + unsigned int j; + unsigned char c; + unsigned char l; + + s = 0; + l = 0; + for (i = j = 0; i < inlen; i++) { + c = in[i]; + + switch (s) { + case 0: + s = 1; + out[j++] = base64en[(c >> 2) & 0x3F]; + break; + case 1: + s = 2; + out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xF)]; + break; + case 2: + s = 0; + out[j++] = base64en[((l & 0xF) << 2) | ((c >> 6) & 0x3)]; + out[j++] = base64en[c & 0x3F]; + break; + } + l = c; + } + + switch (s) { + case 1: + out[j++] = base64en[(l & 0x3) << 4]; + out[j++] = BASE64_PAD; + out[j++] = BASE64_PAD; + break; + case 2: + out[j++] = base64en[(l & 0xF) << 2]; + out[j++] = BASE64_PAD; + break; + } + + out[j] = 0; + + return j; +} + +unsigned int +gjbase64_decode(const char *in, unsigned int inlen, unsigned char *out) +{ + unsigned int i; + unsigned int j; + unsigned char c; + + if (inlen & 0x3) { + return 0; + } + + for (i = j = 0; i < inlen; i++) { + if (in[i] == BASE64_PAD) { + break; + } + if (in[i] < BASE64DE_FIRST || in[i] > BASE64DE_LAST) { + return 0; + } + + c = base64de[(unsigned char)in[i]]; + if (c == 255) { + return 0; + } + + switch (i & 0x3) { + case 0: + out[j] = (c << 2) & 0xFF; + break; + case 1: + out[j++] |= (c >> 4) & 0x3; + out[j] = (c & 0xF) << 4; + break; + case 2: + out[j++] |= (c >> 2) & 0xF; + out[j] = (c & 0x3) << 6; + break; + case 3: + out[j++] |= c; + break; + } + } + + return j; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.h new file mode 100644 index 0000000000000000000000000000000000000000..34ad9486bf6beae446796b083fab89b1d66bf794 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/base64.h @@ -0,0 +1,29 @@ +#ifndef BASE64_H +#define BASE64_H + +#define BASE64_ENCODE_OUT_SIZE(s) ((unsigned int)((((s) + 2) / 3) * 4 + 1)) +#define BASE64_DECODE_OUT_SIZE(s) ((unsigned int)(((s) / 4) * 3)) + +#ifdef __cplusplus +extern "C"{ +#endif + +/* + * out is null-terminated encode string. + * return values is out length, exclusive terminating `\0' + */ +unsigned int +gjbase64_encode(const unsigned char *in, unsigned int inlen, char *out); + +/* + * return values is out length + */ +unsigned int +gjbase64_decode(const char *in, unsigned int inlen, unsigned char *out); + +#ifdef __cplusplus +} +#endif + + +#endif /* BASE64_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/cbc128.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/cbc128.c new file mode 100644 index 0000000000000000000000000000000000000000..f10d9cae201a9d16295bd93c1ddc81e529b15ec6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/cbc128.c @@ -0,0 +1,161 @@ +/* + * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +// #include +#include "modes.h" +#include + +#if !defined(STRICT_ALIGNMENT) && !defined(PEDANTIC) +# define STRICT_ALIGNMENT 0 +#endif + +void CRYPTO_cbc128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block) +{ + size_t n; + const unsigned char *iv = ivec; + + if (len == 0) + return; + +#if !defined(OPENSSL_SMALL_FOOTPRINT) + if (STRICT_ALIGNMENT && + ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) { + while (len >= 16) { + for (n = 0; n < 16; ++n) + out[n] = in[n] ^ iv[n]; + (*block) (out, out, key); + iv = out; + len -= 16; + in += 16; + out += 16; + } + } else { + while (len >= 16) { + for (n = 0; n < 16; n += sizeof(size_t)) + *(size_t *)(out + n) = + *(size_t *)(in + n) ^ *(size_t *)(iv + n); + (*block) (out, out, key); + iv = out; + len -= 16; + in += 16; + out += 16; + } + } +#endif + while (len) { + for (n = 0; n < 16 && n < len; ++n) + out[n] = in[n] ^ iv[n]; + for (; n < 16; ++n) + out[n] = iv[n]; + (*block) (out, out, key); + iv = out; + if (len <= 16) + break; + len -= 16; + in += 16; + out += 16; + } + memcpy(ivec, iv, 16); +} + +void CRYPTO_cbc128_decrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block) +{ + size_t n; + union { + size_t t[16 / sizeof(size_t)]; + unsigned char c[16]; + } tmp; + + if (len == 0) + return; + +#if !defined(OPENSSL_SMALL_FOOTPRINT) + if (in != out) { + const unsigned char *iv = ivec; + + if (STRICT_ALIGNMENT && + ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) { + while (len >= 16) { + (*block) (in, out, key); + for (n = 0; n < 16; ++n) + out[n] ^= iv[n]; + iv = in; + len -= 16; + in += 16; + out += 16; + } + } else if (16 % sizeof(size_t) == 0) { /* always true */ + while (len >= 16) { + size_t *out_t = (size_t *)out, *iv_t = (size_t *)iv; + + (*block) (in, out, key); + for (n = 0; n < 16 / sizeof(size_t); n++) + out_t[n] ^= iv_t[n]; + iv = in; + len -= 16; + in += 16; + out += 16; + } + } + memcpy(ivec, iv, 16); + } else { + if (STRICT_ALIGNMENT && + ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) { + unsigned char c; + while (len >= 16) { + (*block) (in, tmp.c, key); + for (n = 0; n < 16; ++n) { + c = in[n]; + out[n] = tmp.c[n] ^ ivec[n]; + ivec[n] = c; + } + len -= 16; + in += 16; + out += 16; + } + } else if (16 % sizeof(size_t) == 0) { /* always true */ + while (len >= 16) { + size_t c, *out_t = (size_t *)out, *ivec_t = (size_t *)ivec; + const size_t *in_t = (const size_t *)in; + + (*block) (in, tmp.c, key); + for (n = 0; n < 16 / sizeof(size_t); n++) { + c = in_t[n]; + out_t[n] = tmp.t[n] ^ ivec_t[n]; + ivec_t[n] = c; + } + len -= 16; + in += 16; + out += 16; + } + } + } +#endif + while (len) { + unsigned char c; + (*block) (in, tmp.c, key); + for (n = 0; n < 16 && n < len; ++n) { + c = in[n]; + out[n] = tmp.c[n] ^ ivec[n]; + ivec[n] = c; + } + if (len <= 16) { + for (; n < 16; ++n) + ivec[n] = in[n]; + break; + } + len -= 16; + in += 16; + out += 16; + } +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.cc b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.cc new file mode 100644 index 0000000000000000000000000000000000000000..b8812cda33071c9be0a2144de80d7ecb81c2dacd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.cc @@ -0,0 +1,213 @@ + +#include "gaes_stream.h" + +#include +#include +#include +#include +#include +#include +#include "gj_aes.h" + + +class GaesIStreamBuf final: public std::streambuf +{ +private: + char *m_inbuf; + size_t m_inbufsize; + bool m_owns_inbuf; + char *m_leftbuf; + + FILE *file; + uint64_t cur_size; + uint64_t file_size; + gj_aesc_t* aesc ; +protected: + virtual std::streambuf* setbuf(char *s, std::streamsize n){ + setg(0, 0, 0); + if (m_owns_inbuf) { + delete [] m_inbuf; + } + m_inbufsize = n; + if (s) { + m_inbuf = s; + m_owns_inbuf = false; + } else { + m_inbuf = new char[m_inbufsize]; + m_leftbuf = new char[m_inbufsize]; + m_owns_inbuf = true; + } + return this; + } + + virtual int sync(){ + int result = 0; + return result; + } + + virtual int underflow() override{ + int __c = traits_type::eof(); + if (!file) return __c; + if(cur_size>=file_size){ + printf("===eof %ld ===%ld\n",cur_size,file_size); + return __c; + } + bool initial = false; + if (eback() == 0) { + setg(m_inbuf, m_inbuf + m_inbufsize, m_inbuf + m_inbufsize); + initial = true; + } + const size_t unget_sz = initial ? 0 : std::min((egptr() - eback()) / 2, 4); + if (gptr() == egptr()) { + memmove(eback(), egptr() - unget_sz, unget_sz); + size_t nmemb = static_cast(egptr() - eback() - unget_sz); + char* pdst = eback() + unget_sz; + int modb = nmemb % 16; + size_t leftb = nmemb - modb; + char* pbuf = m_leftbuf; + size_t leftf = file_size - cur_size; + if(leftb>leftf)leftb=leftf; + memset(pbuf,0,m_inbufsize); + size_t rd = fread(pbuf, 1, leftb, file); + //printf("%d-%ld-%ld----------------%ld--%ld#\n",cur_size,file_size,modb,nmemb,rd); + //ssize_t readed = read(m_fd, eback() + unget_sz, nmemb); + if(rd>0){ + cur_size += rd; + int cnt = leftb /16; + int k; + for(k=0;kaesc); + char head[50]; + memset(head,0,50); + uint64_t rst = fread(head,1,8,file); + rst = fread(&cur_size,1,8,file); + printf("===head %s size %ld\n",head,cur_size); + rst = fread(head,1,16,file); + cur_size = 32; + } + + ~GaesIStreamBuf(){ + close(); + if (m_owns_inbuf) { + delete[] m_inbuf; + } + } + + void close(){ + if(aesc){ + free_aesc(&this->aesc); + } + if (file){ + fclose(file); + file = NULL; + } + } +}; + + + +GaesIStream::GaesIStream(std::string filename): + std::istream(new GaesIStreamBuf(filename)){ +} + +GaesIStream::~GaesIStream() +{ + delete rdbuf(); +} + +#ifdef TEST +int maindec(int argc,char** argv){ + std::string filename(argv[1]);// = "test.enc"; + //std::string filename = "final.mdlenc"; + GaesIStream fin(filename); + //std::string fn2 = "final.mdldec"; + std::string fn2(argv[2]);// = "test.dec"; + std::ofstream fout(fn2,std::ios::binary); + + char buf[1024]; + int rd = 0; + while(!fin.eof()){ + //while((rd = fin.read(buf,16))>0){ + //printf("===rd %ld\n",rd); + fin.read(buf,16); + fout.write(buf,16); + + } + //char ch; + //while (fin.get(ch)) { + //printf("+"); + //fout << ch; + //} + return 0; +} + + + +int mainenc(int argc,char** argv){ + char result[255] ; + memset(result,0,255); + char* key = "yymrjzbwyrbjszrk"; + char* aiv = "yymrjzbwyrbjszrk"; + int base64 = 1; + int outlen = 0; + gj_aesc_t* aesc = NULL; + init_aesc(key,aiv,1,&aesc); + char* fn1 = argv[1]; + char* fn2 = argv[2]; + FILE* fr = fopen(fn1,"rb"); + FILE* fw = fopen(fn2,"wb"); + fwrite("abcdefgh",1,8,fw); + uint64_t size = 0; + fwrite(&size,1,8,fw); + fwrite(&size,1,8,fw); + fwrite(&size,1,8,fw); + while(!feof(fr)){ + char data[16]; + memset(data,0,16); + uint64_t rst = fread(data,1,16,fr); + printf("===rst %d\n",rst); + if(rst){ + size +=rst; + do_aesc(aesc,data,16,result,&outlen); + printf("===out %d\n",outlen); + fwrite(result,1,16,fw); + } + } + fseek(fw,8,0); + fwrite(&size,1,8,fw); + fclose(fr); + fclose(fw); + return 0; +} + +int main(int argc,char** argv){ + if(argc<4){ + return mainenc(argc,argv); + }else{ + return maindec(argc,argv); + } +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.h new file mode 100644 index 0000000000000000000000000000000000000000..d3e2d1d01f7b730238a4d5743ca1163dd20d2e15 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaes_stream.h @@ -0,0 +1,22 @@ +#ifndef COMPRESSED_STREAMS_ZSTD_STREAM_H +#define COMPRESSED_STREAMS_ZSTD_STREAM_H + +#include + + + + + +class GaesIStream: public std::istream +{ +public: + GaesIStream(std::string filename); + + virtual ~GaesIStream(); +}; + + + + + +#endif // COMPRESSED_STREAMS_ZSTD_STREAM_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaesmain b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaesmain new file mode 100644 index 0000000000000000000000000000000000000000..c3cae0fd38f67f6bc71d88d564d9d3af7747fd46 Binary files /dev/null and b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gaesmain differ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.c new file mode 100644 index 0000000000000000000000000000000000000000..3314ef62acd90600ccac1746abc54914f9d3360f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.c @@ -0,0 +1,69 @@ +#include +#include +#include "gj_aes.h" +#include "base64.h" + +#include "aes.h" + + +struct gj_aesc_s{ + char key[16]; + char iv[16]; + int enc; + AES_KEY *aeskey; +}; + +int free_aesc(gj_aesc_t** paesc){ + if(!paesc||!*paesc)return -1; + if((*paesc)->aeskey)free((*paesc)->aeskey); + free(*paesc); + *paesc = NULL; + return 0; +} + + +int init_aesc(char* key,char* iv,int enc,gj_aesc_t** paesc){ + if(strlen(key)!=16) return -1; + if(strlen(iv)!=16) return -2; + gj_aesc_t* aesc = (gj_aesc_t*)malloc(sizeof(gj_aesc_t)); + int k; + for(k=0;k<16;k++){ + aesc->key[k]=key[k]; + aesc->iv[k]=iv[k]; + } + aesc->aeskey = (AES_KEY*)malloc(sizeof(AES_KEY)); + aesc->enc = enc; + if(enc){ + AES_set_encrypt_key((const unsigned char*)aesc->key, 128, aesc->aeskey); + }else{ + AES_set_decrypt_key((const unsigned char*)aesc->key, 128, aesc->aeskey); + } + *paesc = aesc; + return 0; +} + +int do_aesc(gj_aesc_t* aesc,char* in,int inlen,char* out,int* outlen){ + char* psrc = in; + char* pdest = out; + int cnt = 0; + int left=inlen; + while(left>0){ + AES_cbc_encrypt((const unsigned char*)psrc,(unsigned char*)pdest,16,aesc->aeskey,(unsigned char*)aesc->iv,aesc->enc); + psrc += 16; + pdest += 16; + left -= 16; + cnt += 16; + } + *outlen = cnt; + return 0; +} + +int do_base64(int enc,char* in,int inlen,char* out,int* outlen){ + if(enc){ + gjbase64_encode((unsigned char*)in,inlen,out); + *outlen = strlen(out); + }else{ + *outlen = gjbase64_decode(in,inlen,(unsigned char*)out); + } + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.h new file mode 100644 index 0000000000000000000000000000000000000000..a09338f9011cf4287cbec494345b9d76eec3c7f1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_aes.h @@ -0,0 +1,22 @@ +#ifndef __GJ_AES_H__ +#define __GJ_AES_H__ + +#include "gj_dll.h" +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct gj_aesc_s gj_aesc_t; + +GJLIBAPI int free_aesc(gj_aesc_t** paesc); +GJLIBAPI int init_aesc(char* key,char* iv,int enc,gj_aesc_t** paesc); + +GJLIBAPI int do_aesc(gj_aesc_t* aesc,char* in,int inlen,char* out,int* outlen); + +GJLIBAPI int do_base64(int enc,char* in,int inlen,char* out,int* outlen); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_dll.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_dll.h new file mode 100644 index 0000000000000000000000000000000000000000..9d1c9536f027929a430a9be0ca2e46749656b153 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/gj_dll.h @@ -0,0 +1,21 @@ +#ifndef __GJ_DLL_H__ +#define __GJ_DLL_H__ + +#ifdef __cplusplus +extern "C" { +#endif +#define GJLIB_EXPORT 1 +#if defined(GJLIB_EXPORT) + #if defined _WIN32 || defined __CYGWIN__ + #define GJLIBAPI __declspec(dllexport) + #else + #define GJLIBAPI __attribute__((visibility("default"))) + #endif +#else + #define GJLIBAPI +#endif + +#ifdef __cplusplus +} +#endif +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/makefile b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/makefile new file mode 100644 index 0000000000000000000000000000000000000000..dbe0cac9922691c427081872daadd9a808cfb328 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/makefile @@ -0,0 +1,3 @@ +all: + g++ -fPIC -o gjaesmain -g aesmain.c \ + aes_cbc.c aes_core.c aes_ecb.c cbc128.c base64.c gj_aes.c -lm --std=c++11 -I. -DTEST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/modes.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/modes.h new file mode 100644 index 0000000000000000000000000000000000000000..8d2c17e0ca0fddd861e30975b3f7fa7fe9ade88f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aes/modes.h @@ -0,0 +1,22 @@ +#ifndef HEADER_MODES_H +# define HEADER_MODES_H + +# include + +typedef void (*block128_f) (const unsigned char in[16], + unsigned char out[16], const void *key); + +typedef void (*cbc128_f) (const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], int enc); + +void CRYPTO_cbc128_encrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block); +void CRYPTO_cbc128_decrypt(const unsigned char *in, unsigned char *out, + size_t len, const void *key, + unsigned char ivec[16], block128_f block); + + + +#endif \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aicommon.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aicommon.h new file mode 100644 index 0000000000000000000000000000000000000000..ef25518667a537dd5668a31c53fa88159670b929 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aicommon.h @@ -0,0 +1,24 @@ +#pragma once + +//#define MFCC_OFFSET 6436 +#define MFCC_OFFSET 6400 +//##define MFCC_OFFSET 0 +#define MFCC_DEFRMS 0.1f +#define MFCC_FPS 25 +#define MFCC_RATE 16000 +//#define MFCC_WAVCHUNK 960000 +#define MFCC_WAVCHUNK 560000 +//#define MFCC_WAVCHUNK 512 + +//#define MFCC_MELBASE 6001 +#define MFCC_MELBASE 3501 +#define MFCC_MELCHUNK 80 +//#define MFCC_MELCHUNK 20 + +//#define MFCC_BNFBASE 1499 +#define MFCC_BNFBASE 874 +#define MFCC_BNFCHUNK 256 +//input==== NodeArg(name='speech', type='tensor(float)', shape=['B', 'T', 80]) +//input==== NodeArg(name='speech_lengths', type='tensor(int32)', shape=['B']) +//output==== NodeArg(name='encoder_out', type='tensor(float)', shape=['B', 'T_OUT', 'Addencoder_out_dim_2']) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1ccf44987ef03123c9a8798ba42431325aa7f721 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.cpp @@ -0,0 +1,438 @@ +#include "aimodel.h" +#include +#include + +void AiCfg::dump(){ + int incnt = size_inputs.size(); + int outcnt = size_outputs.size(); + std::cout<<"======in onnx:"<=shape_inputs.size())return -1; + if(dim>=shape_inputs[inx].size())return -2; + shape_inputs[inx][dim] = val; + int size = 1; + for(int k=0;k0){ + size_inputs[inx] = size; + } + return 0; +} + +int AiCfg::outShape(int inx,int dim,int val){ + if(inx>=shape_outputs.size())return -1; + if(dim>=shape_outputs[inx].size())return -2; + shape_outputs[inx][dim] = val; + int size = 1; + for(int k=0;k0){ + size_outputs[inx] = size; + } + return 0; +} + +AiCfg AiCfg::clone(){ + AiCfg onecfg; + AiCfg* cfg = &onecfg;//new AiCfg(); + // + cfg->names.assign(names.begin(),names.end()); + cfg->kind_inputs.assign(kind_inputs.begin(),kind_inputs.end()); + cfg->name_inputs.assign(name_inputs.begin(),name_inputs.end()); + cfg->size_inputs.assign(size_inputs.begin(),size_inputs.end()); + //cfg->m_sizeinput = m_sizeinput; + for(int k=0;k shape(shape_inputs[k]); + cfg->shape_inputs.push_back(shape); + } + + cfg->kind_outputs.assign(kind_outputs.begin(),kind_outputs.end()); + cfg->name_outputs.assign(name_outputs.begin(),name_outputs.end()); + cfg->size_outputs.assign(size_outputs.begin(),size_outputs.end()); + //cfg->m_sizeoutput = m_sizeoutput; + for(int k=0;k shape(shape_outputs[k]); + cfg->shape_outputs.push_back(shape); + } + return onecfg;//cfg; +} + +AiModel::AiModel(){ + m_cfg = new AiCfg(); +} + +AiModel::~AiModel(){ + delete m_cfg; +} + +int AiModel::doInitModel(){ + return -1; +} + +AiCfg AiModel::config(){ + return m_cfg->clone(); +} + +void AiModel::dump(){ + m_cfg->dump(); +} + +int AiModel::pushName(const char* name,int input){ + std::string sname(name); + m_cfg->names.push_back(sname); + if(input){ + m_cfg->name_inputs.push_back(m_cfg->names[m_cfg->names.size()-1].c_str()); + }else{ + m_cfg->name_outputs.push_back(m_cfg->names[m_cfg->names.size()-1].c_str()); + } + return 0; +} + +int AiModel::initModel(std::string& modelpath){ + m_modelPath = modelpath; + m_inited = doInitModel(); + printf("===init %d\n",m_inited); + + return m_inited; +} + +int AiModel::initModel(std::string& binfn,std::string& paramfn){ + m_modelbin = binfn; + m_modelparam = paramfn; + m_inited = doInitModel(); + //printf("===init %d\n",m_inited); + + return m_inited; +} + +int AiModel::doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg){ + return 0; +} + + +int AiModel::runModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg){ + if(m_inited){ + //std::cout<<"model not inited:"< availableProviders = Ort::GetAvailableProviders(); + //auto cudaAvailable = std::find(availableProviders.begin(), availableProviders.end(), "CUDAExecutionProvider"); + //OrtCUDAProviderOptions cudaOption; + + //if(cudaAvailable != availableProviders.end()){ + //std::cout << "Inference device: GPU" << std::endl; + //sessionOptions.AppendExecutionProvider_CUDA(cudaOption); + //}else{ + //std::cout << "Inference device: CPU" << std::endl; + //} + + session = Ort::Session(env, m_modelPath.c_str(), sessionOptions); + //Ort::AllocatorWithDefaultOptions allocator; + size_t numInputNodes = session.GetInputCount(); + size_t numOutputNodes = session.GetOutputCount(); + //std::cout << "input NUM: " << numInputNodes << std::endl; + //std::cout << "Output NUM: " << numOutputNodes << std::endl; + for(int k=0;kname_inputs.push_back(session.GetInputName(k));//, allocator)); + Ort::TypeInfo inputTypeInfo = session.GetInputTypeInfo(k); + auto tensorInfo = inputTypeInfo.GetTensorTypeAndShapeInfo(); + auto elemType = tensorInfo.GetElementType(); + m_cfg->kind_inputs.push_back((int)elemType); + std::vector inputTensorShape = tensorInfo.GetShape(); + + if(m_batch&&inputTensorShape.size()){ + if(inputTensorShape[0]==-1)inputTensorShape[0]=m_batch; + } + if(m_batch&&(inputTensorShape.size()==4)){ + if(inputTensorShape[0]==-1)inputTensorShape[0]=m_batch; + if(inputTensorShape[2]==-1)inputTensorShape[2]=m_height; + if(inputTensorShape[3]==-1)inputTensorShape[3]=m_width; + } + int size = 1; + for (auto shape : inputTensorShape){ + size *= shape; + } + m_cfg->shape_inputs.push_back(inputTensorShape); + m_cfg->size_inputs.push_back(size); + } + + for(int k=0;kname_outputs.push_back(session.GetOutputName(k));//, allocator)); + Ort::TypeInfo outputTypeInfo = session.GetOutputTypeInfo(k); + auto tensorInfo = outputTypeInfo.GetTensorTypeAndShapeInfo(); + auto elemType = tensorInfo.GetElementType(); + m_cfg->kind_outputs.push_back((int)elemType); + std::vector outputTensorShape = tensorInfo.GetShape(); + if(m_batch&&outputTensorShape.size()){ + if(outputTensorShape[0]==-1)outputTensorShape[0]=m_batch; + } + if(m_batch&&(outputTensorShape.size()==4)){ + if(outputTensorShape[0]==-1)outputTensorShape[0]=m_batch; + if(outputTensorShape[2]==-1)outputTensorShape[2]=m_height; + if(outputTensorShape[3]==-1)outputTensorShape[3]=m_width; + } + int size = 1; + for (auto shape : outputTensorShape){ + size *= shape; + } + m_cfg->shape_outputs.push_back(outputTensorShape); + m_cfg->size_outputs.push_back(size); + } + + return 0; +} + + +int OnnxModel::doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg){ + AiCfg* cfg = pcfg==nullptr?m_cfg:pcfg; + int incnt = cfg->size_inputs.size(); + int outcnt = cfg->size_outputs.size(); + std::cout<<"run onnx:"< inputTensors; + Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu( OrtAllocatorType::OrtArenaAllocator, OrtMemType::OrtMemTypeDefault); + for(int k=0;ksize_inputs[k]*4 , cfg->shape_inputs[k].data(), cfg->shape_inputs[k].size(), (ONNXTensorElementDataType)cfg->kind_inputs[k] )); + } + std::vector outputTensors; + for(int k=0;ksize_outputs[k]*4 , cfg->shape_outputs[k].data(), cfg->shape_outputs[k].size(),(ONNXTensorElementDataType)cfg->kind_outputs[k] )); + } + this->session.Run(Ort::RunOptions{nullptr}, cfg->names_in, inputTensors.data(), incnt, cfg->names_out, outputTensors.data(),outcnt); + if(1)return 0; + /* + //for(int k=0;k<9;k++)dumpfloat((float*)arrout[k],10);//size_outputs[0]); + std::vector aoutputTensors = this->session.Run(Ort::RunOptions{nullptr}, name_inputs.data(), inputTensors.data(), 1, name_outputs.data(), 9); + //bool* pmsk = (bool*)aoutputTensors[1].GetTensorData(); + for(int k=0;k<9;k++){ + float* pbnf = (float*)aoutputTensors[0].GetTensorData(); + memcpy(arrout[k],pbnf,size_outputs[k]*4); + } + */ + return 0; +} + +NcnnModel::NcnnModel():AiModel(){ +} + +NcnnModel::NcnnModel(int w,int h):AiModel(){ + m_width = w; + m_height = h; +} + +NcnnModel::~NcnnModel(){ + net.clear(); +} + +int NcnnModel::doInitModel(){ + net.clear(); + net.load_param(m_modelparam.c_str()); + net.load_model(m_modelbin.c_str()); + return 0; // +} + +int NcnnModel::doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg){ + ncnn::Extractor ex = net.create_extractor(); + AiCfg* cfg = pcfg==nullptr?m_cfg:pcfg; + int incnt = cfg->size_inputs.size(); + int outcnt = cfg->size_outputs.size(); + ncnn::Mat inmat[incnt]; + for(int k=0;kname_inputs[k]; + JMat* mat = (JMat*)arrin[k]; + ncnn::Mat in_pack =mat->packingmat(); + ex.input(name.c_str(), in_pack); + } + for(int k=0;kname_outputs[k]; + JMat* mat = (JMat*)arrout[k]; + ncnn::Mat output; + ex.extract(name.c_str(), output); + ncnn::Mat in_park; + ncnn::convert_packing(output,in_park,3); + int size = mat->width()*mat->height()*3*sizeof(float); + memcpy((uint8_t*)mat->data(),in_park,size); + } + return 0; +} + +#ifdef _TENSORRT_ +#include "NvInferPlugin.h" +#include "cuda_runtime_api.h" +#include "cuda.h" +#define FPW 4 +using namespace nvinfer1; + +int TrtModel::doInitModel(){ + std::cout<<"deserialize eng !"<deserializeCudaEngine(modelMem,engSize); + runtime->destroy(); + free(modelMem); + if(! m_engine){ + std::cout<<"deserialize eng error!"<createExecutionContext(); + int bindings = m_engine->getNbBindings(); + std::cout<<"bindings!"<getBindingName(k); + std::string sname(name ); + bool input = m_engine->bindingIsInput(k); + std::cout<<"name!"<getBindingDimensions(k); + auto dt = m_engine->getBindingDataType(k); + int tdt = dt==DataType::kFLOAT?ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT:ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; + std::vector tensorShape; + int dsize = 1; + for(int i = 0 ;i < dims.nbDims; i++){ + tensorShape.push_back(dims.d[i]); + dsize *= dims.d[i]; + //cout<<"==dsize!"<kind_inputs.push_back(tdt); + m_cfg->shape_inputs.push_back(tensorShape); + m_cfg->size_inputs.push_back(size); + m_cfg->name_inputs.push_back(name); + }else{ + m_cfg->kind_outputs.push_back(tdt); + m_cfg->size_outputs.push_back(size); + m_cfg->name_outputs.push_back(name); + m_cfg->shape_outputs.push_back(tensorShape); + } + } + //getchar(); + /* + m_sizeinput = 0; + for(int k=0;ksize_inputs.size();k++){ + int size = m_cfg->size_inputs[k]; + void* input ; + //int flag = cudaMalloc(&input,size); + //m_inputs.push_back(input); + //m_bindings[k]=input; + m_sizeinput += size; + //printf("===input %d output %d \n",m_sizeinput,m_sizeoutput); + } + std::cout<<"bbb"<size_inputs.size(); + for(int k=0;ksize_outputs.size();k++){ + int size = m_cfg->size_outputs[k]; + void* output ; + //int flag = cudaMalloc(&output,size); + //m_outputs.push_back(output); + //m_bindings[offset+k]=output; + m_sizeoutput += size; + //printf("===input %d output %d \n",m_sizeinput,m_sizeoutput); + } + std::cout<<"ccc"<size_inputs.size(); + int outcnt = cfg->size_outputs.size(); + std::cout<<"incnt:"< m_bindings(incnt+outcnt,NULL); + for(int k=0;ksize_inputs[k]<size_outputs[k]<enqueue(1,m_bindings.data(),(cudaStream_t)stream,nullptr); + return status?0:-1; +} + +TrtModel::TrtModel(int b,int w,int h):AiModel(){ +} + +TrtModel::TrtModel():AiModel(){ +} + +TrtModel::~TrtModel(){ + if(m_context){ + m_context->destroy(); + m_context = nullptr; + } + if(m_engine){ + m_engine->destroy(); + m_engine = nullptr; + } +} + +#endif +/* + int main(int argc,char** argv){ + OnnxModel *model=new OnnxModel(); + std::string fn = "onnx/mfcc.onnx"; + model->initModel(fn); + delete model; + return 0; + } + */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.h new file mode 100644 index 0000000000000000000000000000000000000000..1665bb68211a6ae8f7487ea2597e863c4d0abbd5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/aimodel.h @@ -0,0 +1,136 @@ +#pragma once + +#include +#include +#include +#include +#include +#include "jmat.h" + +struct AiCfg{ + std::vector kind_inputs; + std::vector size_inputs; + std::vector names; + std::vector name_inputs; + //int m_sizeinput; + std::vector> shape_inputs; + + std::vector kind_outputs; + std::vector size_outputs; + std::vector name_outputs; + //int m_sizeoutput; + std::vector> shape_outputs; + + const char** names_in; + const char** names_out; + void dump(); + int inShape(int inx,int dim,int val); + int outShape(int inx,int dim,int val); + AiCfg clone(); +}; + +class AiModel{ + protected: + int m_inited; + std::string m_modelPath; + std::string m_modelbin; + std::string m_modelparam; + + AiCfg *m_cfg; + + virtual int doInitModel(); + virtual int doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg=nullptr); + public: + void dump(); + AiCfg config(); + int pushName(const char* name,int input); + int initModel(std::string& modelpath); + int initModel(std::string& binfn,std::string& paramfn); + int runModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg = nullptr); + AiModel(); + virtual ~AiModel(); +}; + +#define _ONNX_ +#ifdef _ONNX_ +#include "onnx/onnxruntime_cxx_api.h" +class OnnxModel:public AiModel{ + protected: + int m_batch = 0; + int m_width = 640; + int m_height = 960; + Ort::Env env{nullptr}; + Ort::SessionOptions sessionOptions{nullptr}; + Ort::Session session{nullptr}; + int doInitModel()override; + int doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg=nullptr)override; + public: + OnnxModel(int b,int w,int h); + OnnxModel(); + virtual ~OnnxModel(); +}; +#endif + +#define _NCNN_ +#ifdef _NCNN_ +#include "net.h" +class NcnnModel:public AiModel{ + protected: + int m_width = 160; + int m_height = 160; + ncnn::Net net; + int doInitModel()override; + int doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg=nullptr)override; + public: + NcnnModel(int w,int h); + NcnnModel(); + virtual ~NcnnModel(); +}; + +#endif + +#ifdef _TENSORRT_ +#include "NvInfer.h" +#include "NvInferLegacyDims.h" +#include "NvInferRuntime.h" +class Logger:public nvinfer1::ILogger { + public: + void log(nvinfer1::ILogger::Severity severity, const char *msg) noexcept override { + // suppress info-level messages + if (severity == Severity::kINFO) + return; + switch (severity) { + case Severity::kINTERNAL_ERROR: + std::cerr << "INTERNAL_ERROR: "; + break; + case Severity::kERROR: + std::cerr << "ERROR: "; + break; + case Severity::kWARNING: + std::cerr << "WARNING: "; + break; + case Severity::kINFO: + std::cerr << "INFO: "; + break; + default: + std::cerr << "UNKNOWN: "; + break; + } + std::cerr << msg << std::endl; + } +}; + +class TrtModel:public AiModel{ + protected: + Logger m_logger; + nvinfer1::IExecutionContext *m_context; + nvinfer1::ICudaEngine *m_engine; + + int doInitModel()override; + int doRunModel(void** arrin,void** arrout,void* stream,AiCfg* pcfg=nullptr)override; + public: + TrtModel(int b,int w,int h); + TrtModel(); + virtual ~TrtModel(); +}; +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ffa62916f9c929274e977f8eab58b6c943446bb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.cpp @@ -0,0 +1,437 @@ +#include +#include +#include + +#include "blendgram.h" + + + void exColorBlend_Normal(uint8* T,uint8* A,uint8* B){ ColorBlend_Buffer(T,A,B,Normal); } + void exColorBlend_Lighten(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Lighten);} + void exColorBlend_Darken(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Darken);} + void exColorBlend_Multiply(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Multiply);} + void exColorBlend_Average(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Average);} + void exColorBlend_Add(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Add);} + + void exColorBlend_Subtract(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Subtract);} + void exColorBlend_Difference(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Difference);} + void exColorBlend_Negation(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Negation);} + void exColorBlend_Screen(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Screen);} + void exColorBlend_Exclusion(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Exclusion);} + + void exColorBlend_Overlay(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Overlay);} + void exColorBlend_SoftLight(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,SoftLight);} + void exColorBlend_HardLight(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,HardLight);} + void exColorBlend_ColorDodge(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,ColorDodge);} + void exColorBlend_ColorBurn(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,ColorBurn);} + + void exColorBlend_LinearDodge(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,LinearDodge);} + void exColorBlend_LinearBurn(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,LinearBurn);} + void exColorBlend_LinearLight(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,LinearLight);} + void exColorBlend_VividLight(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,VividLight);} + void exColorBlend_PinLight(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,PinLight);} + + void exColorBlend_HardMix(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,HardMix);} + void exColorBlend_Reflect(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Reflect);} + void exColorBlend_Glow(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Glow);} + void exColorBlend_Phoenix(uint8* T,uint8* A,uint8* B) { ColorBlend_Buffer(T,A,B,Phoenix);} + +typedef void (*BlendFunc) (uint8* T,uint8* A,uint8* B); +static int MAX_FUNC = 25; +static BlendFunc blendfuncs[25]={ + &exColorBlend_Normal, + &exColorBlend_Lighten, + &exColorBlend_Darken, + &exColorBlend_Multiply, + &exColorBlend_Average, + &exColorBlend_Add, + + &exColorBlend_Subtract, + &exColorBlend_Difference, + &exColorBlend_Negation, + &exColorBlend_Screen, + &exColorBlend_Exclusion, + + &exColorBlend_Overlay, + &exColorBlend_SoftLight, + &exColorBlend_HardLight, + &exColorBlend_ColorDodge, + &exColorBlend_ColorBurn, + + &exColorBlend_LinearDodge, + &exColorBlend_LinearBurn, + &exColorBlend_LinearLight, + &exColorBlend_VividLight, + &exColorBlend_PinLight, + + &exColorBlend_HardMix, + &exColorBlend_Reflect, + &exColorBlend_Glow, + &exColorBlend_Phoenix +}; + +void BlendGramSimp(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height, int Mode) +{ + if(Mode<1)return; + if(Mode>=MAX_FUNC)return; + BlendFunc func=blendfuncs[Mode]; + unsigned char *LinePS, *LinePD,*LinePM; + for (int Y = 0; Y < Height; Y += 1) + { + LinePS = Src + Y * Width * 4; + LinePM = Mask + Y * Width * 4; + LinePD = Dest + Y * Width * 4; + for (int X = 0; X < Width; X += 1) + { + func(LinePD,LinePS,LinePM); + LinePS += 4; + LinePM += 4; + LinePD += 4; + } + } +} + +void BlendGramAlpha3(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height) +{ + printf("w %d h %d\n",Width,Height); + unsigned char *LinePS, *LinePD,*LinePM; + for (int Y = 0; Y < Height; Y += 1) + { + LinePS = Src + Y * Width * 3; + LinePM = Mask + Y * Width * 3; + LinePD = Dest + Y * Width * 3; + for (int X = 0; X < Width; X += 1) + { + //func(LinePD,LinePS,LinePM); + //ColorBlend_Alpha(LinePD,LinePD,LinePS,*LinePM); + float alpha = *LinePM/255.0f; + float beta = 1.0f-alpha; + //if(beta<0.5f) printf("==alpha %f beta %f\n",alpha,beta); + //if(beta<0.5f) printf("od %u ps %u\n",LinePD[0],LinePS[0]); + LinePD[0] = CLAMPCOLOR( LinePD[0]*alpha+LinePS[0]*beta); + //if(beta<0.5f) printf("new %u ps%u \n",LinePD[0],LinePS[0]); + //if(beta<0.5f) getchar(); + LinePD[1] = CLAMPCOLOR(LinePD[1]*alpha+LinePS[1]*beta); + LinePD[2] = CLAMPCOLOR( LinePD[2]*alpha+LinePS[2]*beta); + LinePS += 3; + LinePM += 3; + LinePD += 3; + } + } +} + +void BlendGramAlpha(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height) +{ + unsigned char *LinePS, *LinePD,*LinePM; + for (int Y = 0; Y < Height; Y += 1) + { + LinePS = Src + Y * Width * 3; + LinePM = Mask + Y * Width * 1; + LinePD = Dest + Y * Width * 3; + for (int X = 0; X < Width; X += 1) + { + //func(LinePD,LinePS,LinePM); + ColorBlend_Alpha(LinePD,LinePD,LinePS,*LinePM); + /* + float alpha = *LinePM/255.0f; + float beta = 1.0f-alpha; + //printf("==alpha %f beta %f\n",alpha,beta); + LinePD[0] = LinePD[0]*alpha+LinePS[0]*beta; + LinePD[1] = LinePD[1]*alpha+LinePS[1]*beta; + LinePD[2] = LinePD[2]*alpha+LinePS[2]*beta; + */ + LinePS += 3; + LinePM += 1; + LinePD += 3; + } + } +} + +void BlendGramAlphaRev(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height) +{ + unsigned char *LinePS, *LinePD,*LinePM; + for (int Y = 0; Y < Height; Y += 1) + { + LinePS = Src + Y * Width * 3; + LinePM = Mask + Y * Width * 1; + LinePD = Dest + Y * Width * 3; + for (int X = 0; X < Width; X += 1) + { + //func(LinePD,LinePS,LinePM); + ColorBlend_Alpha(LinePD,LinePS,LinePD,*LinePM); + LinePS += 3; + LinePM += 1; + LinePD += 3; + } + } +} + + + + +/* +void BlendGram(CBitmap* image,CBitmap* mask,int mode) +{ + if(mode<1)return; + if(mode>=MAX_FUNC)return; + BlendFunc func=blendfuncs[mode]; + int Stride=image->width*4; + unsigned char *LinePS, *LinePD,*LinePM; + for (int Y = 0; Y < image->height; Y += 1) + { + LinePS = (unsigned char*)image->pixels +image->stride*Y; + LinePM = (unsigned char*)mask->pixels + mask->stride*Y; + LinePD = (unsigned char*)image->pixels +image->stride*Y; + for (int X = 0; X < image->width; X += 1) + { + func(LinePD,LinePS,LinePM); + LinePS += 4; + LinePM += 4; + LinePD += 4; + } + } +} + +void BlendImageAdjustWithMask(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int mode) +{ + unsigned char* bmppixels=(unsigned char*)bmp->pixels; + unsigned char* mskpixels=(unsigned char*)msk->pixels; + unsigned char* dstpixels=(unsigned char*)dst->pixels; + unsigned char* adjpixels=(unsigned char*)adj->pixels; + int stride=bmp->stride; + int width=bmp->width; + int height=bmp->height; + int X,Y; + unsigned char* LinePS , * LinePM , * LinePD , * LinePA ; + #pragma omp parallel for private(LinePS,LinePM,LinePD,LinePA,X,Y) + for (Y = 0; Y < height; Y ++) + { + int offset=stride*Y; + LinePS = bmppixels +offset; + LinePM = mskpixels +offset; + LinePD = dstpixels +offset; + LinePA = adjpixels +offset; + for (X = 0; X < width; X ++) + { + unsigned char M=*LinePM; + if(M==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else if(M==0x00){ + LinePD[0]=LinePA[0]; + LinePD[1]=LinePA[1]; + LinePD[2]=LinePA[2]; + }else{ + ColorBlend_Alpha(LinePD,LinePS,LinePA,M); + } + LinePD[3]=LinePS[3]; + LinePS += 4; LinePM += 4; LinePD += 4; LinePA += 4; + } + } +} + + +void BlendImageAdjustWithMaskEx(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int mode) +{ + unsigned char* bmppixels=(unsigned char*)bmp->pixels; + unsigned char* mskpixels=(unsigned char*)msk->pixels; + unsigned char* dstpixels=(unsigned char*)dst->pixels; + unsigned char* adjpixels=(unsigned char*)adj->pixels; + int stride=bmp->stride; + int width=bmp->width; + int height=bmp->height; + int X,Y; + unsigned char* LinePS , * LinePM , * LinePD , * LinePA ; + #pragma omp parallel for private(LinePS,LinePM,LinePD,LinePA,X,Y) + for (Y = 0; Y < height; Y ++) + { + int offset=stride*Y; + LinePS = bmppixels +offset; + LinePM = mskpixels +offset; + LinePD = dstpixels +offset; + LinePA = adjpixels +offset; + for (X = 0; X < width; X ++) + { + unsigned char M=*LinePM; + if(M==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else if(M==0x00){ + LinePD[0]=LinePA[0]; + LinePD[1]=LinePA[1]; + LinePD[2]=LinePA[2]; + }else{ + //ColorBlend_Alpha(LinePD,LinePS,LinePA,M); + LinePD[0]=LinePS[0]*M>>8; + LinePD[1]=LinePS[1]*M>>8; + LinePD[2]=LinePS[2]*M>>8; + } + LinePD[3]=M; + LinePS += 4; LinePM += 4; LinePD += 4; LinePA += 4; + } + } +} + + + + +void BlendImageAdjustWithAlpha(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,int alpha,int mode){ + unsigned char* bmppixels=(unsigned char*)bmp->pixels; + unsigned char* dstpixels=(unsigned char*)dst->pixels; + unsigned char* adjpixels=(unsigned char*)adj->pixels; + int stride=bmp->stride; + int width=bmp->width; + int height=bmp->height; + int X,Y; + unsigned char M=CLAMPCOLOR(alpha); + unsigned char *LinePS , *LinePD , *LinePA ; + #pragma omp parallel for private(LinePS,LinePD,LinePA,X,Y) + for (Y = 0; Y < height; Y ++) + { + int offset=stride*Y; + LinePS = bmppixels +offset; + LinePD = dstpixels +offset; + LinePA = adjpixels +offset; + for (X = 0; X < width; X ++) + { + if(M==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else if(M==0x00){ + LinePD[0]=LinePA[0]; + LinePD[1]=LinePA[1]; + LinePD[2]=LinePA[2]; + }else{ + ColorBlend_Alpha(LinePD,LinePS,LinePA,M); + } + LinePD[3]=LinePS[3]; + LinePS += 4; LinePD += 4; LinePA += 4; + } + } +} + +void BlendImageAdjustWithAlphaMask(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int alpha,int mode){ + unsigned char* bmppixels=(unsigned char*)bmp->pixels; + unsigned char* mskpixels=(unsigned char*)msk->pixels; + unsigned char* dstpixels=(unsigned char*)dst->pixels; + unsigned char* adjpixels=(unsigned char*)adj->pixels; + int stride=bmp->stride; + int width=bmp->width; + int height=bmp->height; + int X,Y; + unsigned char NM=CLAMPCOLOR(alpha); + unsigned char *LinePS , *LinePM , *LinePD , *LinePA ; + #pragma omp parallel for private(LinePS,LinePM,LinePD,LinePA,X,Y) + for (Y = 0; Y < height; Y ++) + { + int offset=stride*Y; + LinePS = bmppixels +offset; + LinePM = mskpixels +offset; + LinePD = dstpixels +offset; + LinePA = adjpixels +offset; + for (X = 0; X < width; X ++) + { + unsigned char M=*LinePM; + if(M==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else if(M==0x00){ + if(NM==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else { + if(NM==0x00){ + //none + LinePD[0]=LinePA[0]; + LinePD[1]=LinePA[1]; + LinePD[2]=LinePA[2]; + }else{ + ColorBlend_Alpha(LinePD,LinePS,LinePA,NM); + } + } + }else{ + // + if(NM==0xFF){ + LinePD[0]=LinePS[0]; + LinePD[1]=LinePS[1]; + LinePD[2]=LinePS[2]; + }else{ + if(NM==0x00){ + ColorBlend_Alpha(LinePD,LinePS,LinePA,M); + }else{ + ColorBlend_Alpha(LinePA,LinePS,LinePA,NM); + ColorBlend_Alpha(LinePD,LinePS,LinePA,M); + } + } + } + LinePD[3]=LinePS[3]; + LinePS += 4; LinePM += 4; LinePD += 4; LinePA += 4; + } + } +} + +void ReadAlphaBySrc(CBitmap* src,CBitmap* alpha){ + memcpy(alpha,src,sizeof(CBitmap)); + alpha->stride=src->width; + alpha->channel=1; + alpha->pixels=(CPixel*)malloc(alpha->width*alpha->height*sizeof(unsigned char)); + unsigned char* bmppixels=(unsigned char*)src->pixels; + unsigned char* alapixels=(unsigned char*)alpha->pixels; + int stride=src->stride; + int width=src->width; + int height=src->height; + int X,Y; + unsigned char *LinePS , *LinePA; + //#pragma omp parallel for private(LinePS,LinePA) + for (Y = 0; Y < height; Y ++) + { + LinePS = bmppixels +stride*Y; + LinePA = alapixels +width*Y; + for (X = 0; X < width; X ++) + { + LinePA[0]=LinePS[3]; + LinePS += 4; LinePA ++; + } + } +} + + +void CheckAlpha(CBitmap* bmp,CBitmap* alpha) +{ + unsigned char* bmppixels=(unsigned char*)bmp->pixels; + unsigned char* alapixels=(unsigned char*)alpha->pixels; + int stride=bmp->stride; + int width=bmp->width; + int height=bmp->height; + int X,Y; + unsigned char *LinePS , *LinePA; + //#pragma omp parallel for private(LinePS,LinePA) + for (Y = 0; Y < height; Y ++) + { + LinePS = bmppixels +stride*Y; + LinePA = alapixels +width*Y; + for (X = 0; X < width; X ++) + { + //unsigned char M=LinePA[0]; + if(*LinePA==0x00){ + LinePS[0]=0; + LinePS[1]=0; + LinePS[2]=0; + LinePS[3]=0; + //}else if(M<0xff){ + //if(LinePD[0]>M)LinePD[0]=M; + //if(LinePD[1]>M)LinePD[1]=M; + //if(LinePD[2]>M)LinePD[2]=M; + //LinePD[3]=M; + }else{ + } + LinePS += 4; LinePA++; + } + } +} +*/ + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.h new file mode 100644 index 0000000000000000000000000000000000000000..7e8ec8a31470f272be10be28506b920681ba3e4a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/blendgram.h @@ -0,0 +1,287 @@ +#ifndef __BLENDGRAM_H__ +#define __BLENDGRAM_H__ + +#include +#include +#include + +typedef unsigned char uchar; +#define CLAMPCOLOR(x) (uchar)((x)<(0)?(0):((x)>(255)?(255):(x))) + +#define MMAX(A,B) ((A)>(B)?(A):(B)) +#define MMIN(A,B) ((A)<(B)?(A):(B)) + +static int ConstBlend_Buffer = 0; +static int ConstBlend_Normal=ConstBlend_Buffer+1; +static int ConstBlend_Lighten=ConstBlend_Buffer+2; +static int ConstBlend_Darken=ConstBlend_Buffer+3; +static int ConstBlend_Multiply=ConstBlend_Buffer+4; +static int ConstBlend_Average=ConstBlend_Buffer+5; + +static int ConstBlend_Add=ConstBlend_Buffer+6; +static int ConstBlend_Subtract=ConstBlend_Buffer+7; +static int ConstBlend_Difference=ConstBlend_Buffer+8; +static int ConstBlend_Negation=ConstBlend_Buffer+9; +static int ConstBlend_Screen=ConstBlend_Buffer+10; +static int ConstBlend_Exclusion=ConstBlend_Buffer+11; +static int ConstBlend_Overlay=ConstBlend_Buffer+12; +static int ConstBlend_SoftLight=ConstBlend_Buffer+13; +static int ConstBlend_HardLight=ConstBlend_Buffer+14; +static int ConstBlend_ColorDodge=ConstBlend_Buffer+15; +static int ConstBlend_ColorBurn=ConstBlend_Buffer+16; +static int ConstBlend_LinearDodge=ConstBlend_Buffer+17; +static int ConstBlend_LinearBurn=ConstBlend_Buffer+18; +static int ConstBlend_LinearLight=ConstBlend_Buffer+19; +static int ConstBlend_VividLight=ConstBlend_Buffer+20; +static int ConstBlend_PinLight=ConstBlend_Buffer+21; +static int ConstBlend_HardMix=ConstBlend_Buffer+22; +static int ConstBlend_Reflect=ConstBlend_Buffer+23; +static int ConstBlend_Glow=ConstBlend_Buffer+24; +static int ConstBlend_Phoenix=ConstBlend_Buffer+25; + +//void BlendGram(CBitmap* immage,CBitmap* mask,int mode); + +//#typedef unsigned char uint8 +#define uint8 unsigned char +#define float64 double +#define TRUE 1 +#define FALSE 0 + +inline uint8 mmin(uint8 A,uint8 B){ + return AB?A:B; +} + +#define ChannelBlend_Normal(A,B) ((uint8)(A)) +#define ChannelBlend_Lighten(A,B) ((uint8)((B > A) ? B:A)) +#define ChannelBlend_Darken(A,B) ((uint8)((B > A) ? A:B)) +#define ChannelBlend_Multiply(A,B) ((uint8)((A * B) / 255)) +#define ChannelBlend_Average(A,B) ((uint8)((A + B) / 2)) +#define ChannelBlend_Add(A,B) ((uint8)(mmin(255, (A + B)))) +#define ChannelBlend_Subtract(A,B) ((uint8)((A + B < 255) ? 0:(A + B - 255))) +#define ChannelBlend_Difference(A,B) ((uint8)(abs(A - B))) +#define ChannelBlend_Negation(A,B) ((uint8)(255 - abs(255 - A - B))) +#define ChannelBlend_Screen(A,B) ((uint8)(255 - (((255 - A) * (255 - B)) >> 8))) +#define ChannelBlend_Exclusion(A,B) ((uint8)(A + B - 2 * A * B / 255)) +#define ChannelBlend_Overlay(A,B) ((uint8)((B < 128) ? (2 * A * B / 255):(255 - 2 * (255 - A) * (255 - B) / 255))) +#define ChannelBlend_SoftLight(A,B) ((uint8)((B < 128)?(2*((A>>1)+64))*((float)B/255):(255-(2*(255-((A>>1)+64))*(float)(255-B)/255)))) +#define ChannelBlend_HardLight(A,B) (ChannelBlend_Overlay(B,A)) +#define ChannelBlend_ColorDodge(A,B) ((uint8)((B == 255) ? B:mmin(255, ((A << 8 ) / (255 - B))))) +#define ChannelBlend_ColorBurn(A,B) ((uint8)((B == 0) ? B:mmax(0, (255 - ((255 - A) << 8 ) / B)))) +#define ChannelBlend_LinearDodge(A,B)(ChannelBlend_Add(A,B)) +#define ChannelBlend_LinearBurn(A,B) (ChannelBlend_Subtract(A,B)) +#define ChannelBlend_LinearLight(A,B)((uint8)(B < 128)?ChannelBlend_LinearBurn(A,(2 * B)):ChannelBlend_LinearDodge(A,(2 * (B - 128)))) +#define ChannelBlend_VividLight(A,B) ((uint8)(B < 128)?ChannelBlend_ColorBurn(A,(2 * B)):ChannelBlend_ColorDodge(A,(2 * (B - 128)))) +#define ChannelBlend_PinLight(A,B) ((uint8)(B < 128)?ChannelBlend_Darken(A,(2 * B)):ChannelBlend_Lighten(A,(2 * (B - 128)))) +#define ChannelBlend_HardMix(A,B) ((uint8)((ChannelBlend_VividLight(A,B) < 128) ? 0:255)) +#define ChannelBlend_Reflect(A,B) ((uint8)((B == 255) ? B:mmin(255, (A * A / (255 - B))))) +#define ChannelBlend_Glow(A,B) (ChannelBlend_Reflect(B,A)) +#define ChannelBlend_Phoenix(A,B) ((uint8)(mmin(A,B) - mmax(A,B) + 255)) +#define ChannelBlend_SoftEx(A,B) (A*B/255+A*(255-((255-A)*(255-B)/255)-A*B/255)/255) + +#define ChannelBlend_Alpha(A,B,O) ((uint8)(O * A + (1 - O) * B)) +#define ChannelBlend_AlphaEx(A,B,O) ((uint8)((O * A + (255 - O) * B)/255)) +#define ChannelBlend_AlphaF(A,B,F,O) (ChannelBlend_AlphaEx(F(A,B),A,O)) + +#define ColorBlend_Alpha(T,A,B,O) (T)[0] = ChannelBlend_AlphaEx((A)[0], (B)[0],O), (T)[1] = ChannelBlend_AlphaEx((A)[1], (B)[1],O), (T)[2] = ChannelBlend_AlphaEx((A)[2], (B)[2],O) +//, (T)[3] = ChannelBlend_AlphaEx((A)[3], (B)[3],O) +#define ColorBlend_AlphaF(T,A,B,F,O) (T)[0] = ChannelBlend_AlphaF((A)[0], (B)[0],F,O), (T)[1] = ChannelBlend_AlphaF((A)[1], (B)[1],F,O), (T)[2] = ChannelBlend_AlphaF((A)[2], (B )[2],F,O) , (T)[3] = ChannelBlend_AlphaEx((A)[3], (B)[3],O) + + +#define ColorBlend_Buffer(T,A,B,M) (T)[0] = ChannelBlend_##M((A)[0], (B)[0]), (T)[1] = ChannelBlend_##M((A)[1], (B)[1]), (T)[2] = ChannelBlend_##M((A)[2], (B)[2]) + +#define ColorBlend_Normal(T,A,B) (ColorBlend_Buffer(T,A,B,Normal)) +#define ColorBlend_Lighten(T,A,B) (ColorBlend_Buffer(T,A,B,Lighten)) +#define ColorBlend_Darken(T,A,B) (ColorBlend_Buffer(T,A,B,Darken)) +#define ColorBlend_Multiply(T,A,B) (ColorBlend_Buffer(T,A,B,Multiply)) +#define ColorBlend_Average(T,A,B) (ColorBlend_Buffer(T,A,B,Average)) +#define ColorBlend_Add(T,A,B) (ColorBlend_Buffer(T,A,B,Add)) +#define ColorBlend_Subtract(T,A,B) (ColorBlend_Buffer(T,A,B,Subtract)) +#define ColorBlend_Difference(T,A,B) (ColorBlend_Buffer(T,A,B,Difference)) +#define ColorBlend_Negation(T,A,B) (ColorBlend_Buffer(T,A,B,Negation)) +#define ColorBlend_Screen(T,A,B) (ColorBlend_Buffer(T,A,B,Screen)) +#define ColorBlend_Exclusion(T,A,B) (ColorBlend_Buffer(T,A,B,Exclusion)) +#define ColorBlend_Overlay(T,A,B) (ColorBlend_Buffer(T,A,B,Overlay)) +#define ColorBlend_SoftLight(T,A,B) (ColorBlend_Buffer(T,A,B,SoftLight)) +#define ColorBlend_HardLight(T,A,B) (ColorBlend_Buffer(T,A,B,HardLight)) +#define ColorBlend_ColorDodge(T,A,B) (ColorBlend_Buffer(T,A,B,ColorDodge)) +#define ColorBlend_ColorBurn(T,A,B) (ColorBlend_Buffer(T,A,B,ColorBurn)) +#define ColorBlend_LinearDodge(T,A,B) (ColorBlend_Buffer(T,A,B,LinearDodge)) +#define ColorBlend_LinearBurn(T,A,B) (ColorBlend_Buffer(T,A,B,LinearBurn)) +#define ColorBlend_LinearLight(T,A,B) (ColorBlend_Buffer(T,A,B,LinearLight)) +#define ColorBlend_VividLight(T,A,B) (ColorBlend_Buffer(T,A,B,VividLight)) +#define ColorBlend_PinLight(T,A,B) (ColorBlend_Buffer(T,A,B,PinLight)) +#define ColorBlend_HardMix(T,A,B) (ColorBlend_Buffer(T,A,B,HardMix)) +#define ColorBlend_Reflect(T,A,B) (ColorBlend_Buffer(T,A,B,Reflect)) +#define ColorBlend_Glow(T,A,B) (ColorBlend_Buffer(T,A,B,Glow)) +#define ColorBlend_Phoenix(T,A,B) (ColorBlend_Buffer(T,A,B,Phoenix)) + + +#define ColorBlend_Hue(T,B,L) ColorBlend_Hls(T,B,L,HueL,LuminationB,SaturationB) +#define ColorBlend_Saturation(T,B,L) ColorBlend_Hls(T,B,L,HueB,LuminationB,SaturationL) +#define ColorBlend_Color(T,B,L) ColorBlend_Hls(T,B,L,HueL,LuminationB,SaturationL) +#define ColorBlend_Luminosity(T,B,L) ColorBlend_Hls(T,B,L,HueB,LuminationL,SaturationB) + + + +#define ColorBlend_Hls(T,B,L,O1,O2,O3) { \ + float64 HueB, LuminationB, SaturationB; \ + float64 HueL, LuminationL, SaturationL; \ + Color_RgbToHls((B)[2],(B)[1],(B)[0], &HueB, &LuminationB, &SaturationB); \ + Color_RgbToHls((L)[2],(L)[1],(L)[0], &HueL, &LuminationL, &SaturationL); \ + Color_HlsToRgb(O1,O2,O3,&(T)[2],&(T)[1],&(T)[0]); \ + } + + +/*********************************************************************/ + +#define COLOR_OPAQUE (0) +#define COLOR_TRANSPARENT (127) + +#define RGB_SIZE (3) +#define RGB_BPP (24) +#define RGB_MAXRED (255) +#define RGB_MAXGREEN (255) +#define RGB_MAXBLUE (255) + +#define ARGB_SIZE (4) +#define ARGB_BPP (32) +#define ARGB_MAXALPHA (127) +#define ARGB_MAXRED (RGB_MAXRED) +#define ARGB_MAXGREEN (RGB_MAXGREEN) +#define ARGB_MAXBLUE (RGB_MAXBLUE) + +/*********************************************************************/ + +#define Color_GetChannel(c,shift) ((uint8)((c) >> (shift))) +#define Color_Reverse(c,bpp) ((((uint8)(c) << 24) | ((uint8)((c) >> 8 ) << 16) | ((uint8)((c) >> 16) << 8 ) | \ ((uint8)((c) >> 24))) >> (32 - (bpp))) + +#define Rgb_ByteWidth(width) ((width) * RGB_SIZE) +#define Rgb_PixelWidth(width) ((width) / RGB_SIZE) + +#define Rgb_GetRed(rgb) (Color_GetChannel(rgb, 0)) +#define Rgb_GetGreen(rgb) (Color_GetChannel(rgb, 8)) +#define Rgb_GetBlue(rgb) (Color_GetChannel(rgb, 16)) + +#define Rgba_GetRed(rgba) (Color_GetChannel(rgba, 24)) +#define Rgba_GetGreen(rgba) (Color_GetChannel(rgba, 16)) +#define Rgba_GetBlue(rgba) (Color_GetChannel(rgba, 8)) +#define Rgba_GetAlpha(rgba) (Color_GetChannel(rgba, 0)) + +#define Argb_GetAlpha(argb) (Color_GetChannel(argb, 24)) +#define Argb_GetRed(argb) (Color_GetChannel(argb, 16)) +#define Argb_GetGreen(argb) (Color_GetChannel(argb, 8)) +#define Argb_GetBlue(argb) (Color_GetChannel(argb, 0)) + +#define MakeRgb(r,g,b) (((uint32)(uint8)(b) << 16) | ((uint16)(uint8)(g) << 8 ) | (uint8)(r)) +#define MakeRgba(r,g,b,a) (((uint32)(uint8)(r) << 24) | ((uint16)(uint8)(g) << 16) | ((uint16)(uint8)(b) << 8 ) | (uint8)(a)) +#define MakeArgb(a,r,g,b) (((uint32)(uint8)(a) << 24) | ((uint32)(uint8)(r) << 16) | ((uint16)(uint8)(g) << 8 ) | (uint8)(b)) +#define HexToRgb(hex) (MakeRgb(((hex & 0xFF0000) >> 16), ((hex & 0x00FF00) >> 8 ), (hex & 0xFF))) + +inline int Color_HueToRgb(float64 M1, float64 M2, float64 Hue, float64 *Channel) +{ + if (Hue < 0.0) + Hue += 1.0; + else if (Hue > 1.0) + Hue -= 1.0; + + if ((6.0 * Hue) < 1.0) + *Channel = (M1 + (M2 - M1) * Hue * 6.0); + else if ((2.0 * Hue) < 1.0) + *Channel = (M2); + else if ((3.0 * Hue) < 2.0) + *Channel = (M1 + (M2 - M1) * ((2.0F / 3.0F) - Hue) * 6.0); + else + *Channel = (M1); + + return TRUE; +} + +inline void Color_RgbToHls(uint8 Red, uint8 Green, uint8 Blue, float64 *Hue, float64 *Lumination, float64 *Saturation) +{ + float64 Delta; + float64 Max, Min; + float64 Redf, Greenf, Bluef; + + Redf = (float64)Red / 255.0; + Greenf = (float64)Green / 255.0; + Bluef = (float64)Blue / 255.0; + + //Max = fmax(fmax(Redf, Greenf), Bluef); + //Min = fmin(fmin(Redf, Greenf), Bluef); + Max = MMAX(MMAX(Red, Green), Blue)/255.0; + Min = MMIN(MMIN(Red, Green), Blue)/255.0; + + *Hue = 0; + *Lumination = (Max + Min) / 2.0F; + *Saturation = 0; + + if (Max == Min) + return ; + + Delta = (Max - Min); + + if (*Lumination < 0.5) + *Saturation = Delta / (Max + Min); + else + *Saturation = Delta / (2.0 - Max - Min); + + if (Redf == Max) + *Hue = (Greenf - Bluef) / Delta; + else if (Greenf == Max) + *Hue = 2.0 + (Bluef - Redf) / Delta; + else + *Hue = 4.0 + (Redf - Greenf) / Delta; + + *Hue /= 6.0; + + if (*Hue < 0.0) + *Hue += 1.0; + +} + +inline void Color_HlsToRgb(float64 Hue, float64 Lumination, float64 Saturation, uint8 *Red, uint8 *Green, uint8 *Blue) +{ + float64 M1, M2; + float64 Redf, Greenf, Bluef; + + if (Saturation == 0) { + Redf = Lumination; + Greenf = Lumination; + Bluef = Lumination; + } else { + if (Lumination <= 0.5) + M2 = Lumination * (1.0 + Saturation); + else + M2 = Lumination + Saturation - Lumination * Saturation; + + M1 = (2.0 * Lumination - M2); + + Color_HueToRgb(M1, M2, Hue + (1.0F / 3.0F), &Redf); + Color_HueToRgb(M1, M2, Hue, &Greenf); + Color_HueToRgb(M1, M2, Hue - (1.0F / 3.0F), &Bluef); + } + + *Red = (uint8)(Redf * 255); + *Blue = (uint8)(Bluef * 255); + *Green = (uint8)(Greenf * 255); + +} + +void BlendGramSimp(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height, int Mode); +void BlendGramAlpha(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height); +void BlendGramAlpha3(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height); +void BlendGramAlphaRev(unsigned char *Src,unsigned char* Mask, unsigned char *Dest, int Width, int Height); +/* +void BlendImageAdjustWithMask(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int mode); +void BlendImageAdjustWithMaskEx(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int mode); +void BlendImageAdjustWithAlpha(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,int alpha,int mode); +void BlendImageAdjustWithAlphaMask(CBitmap* bmp,CBitmap* adj,CBitmap* dst ,CBitmap* msk,int alpha,int mode); + +void CheckAlpha(CBitmap* bmp,CBitmap* alpha); +void ReadAlphaBySrc(CBitmap* src,CBitmap* alpha); +*/ + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/bt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/bt new file mode 100644 index 0000000000000000000000000000000000000000..50f0612dd82a1beddbbbfcd5c22e8c8e24d8cbbd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/bt @@ -0,0 +1,19 @@ +g++ -g -I. \ + -I/usr/include/opencv4 \ + -I../third/x86/include \ + -I../third/x86/include/ncnn/ \ + -I../third/x86/include/onnx/ \ + -I../third/x86/include/turbojpeg/ \ + wavcache.cpp \ + jmat.cpp \ + wavreader.cpp \ + wenet.cpp \ + aimodel.cpp \ + scrfd.cpp \ + pfpld.cpp \ + munet.cpp \ + blendgram.cpp \ + face_utils.cpp \ + -L../third/x86/lib \ + -lopencv_core -lopencv_dnn -lopencv_imgcodecs -lopencv_imgproc -lopencv_highgui -lopencv_videoio \ + -lonnxruntime -lncnn \ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/face_utils.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/face_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb3c4e8af47664a2090036117f32084df6961f42 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/face_utils.cpp @@ -0,0 +1,114 @@ +#include "face_utils.h" +//#include + + +cv::Mat resize_image(cv::Mat srcimg, int height, int width, int* top, int* left){ + cv::Mat dstimg; + int srch = srcimg.rows, srcw = srcimg.cols; + int neww = width; + int newh = height; + if (srch != srcw) { + float hw_scale = (float)srch / srcw; + if (hw_scale > 1) { + newh = height; + neww = int(width / hw_scale); + cv::resize(srcimg, dstimg, cv::Size(neww, newh), cv::INTER_AREA); + *left = int((width - neww) * 0.5); + cv::copyMakeBorder(dstimg, dstimg, 0, 0, *left, width - neww - *left, cv::BORDER_CONSTANT, 0); + } + else + { + newh = (int)height * hw_scale; + neww = width; + cv::resize(srcimg, dstimg,cv::Size(neww, newh), cv::INTER_AREA); + *top = (int)(height - newh) * 0.5; + cv::copyMakeBorder(dstimg, dstimg, *top, height - newh - *top, 0, 0, cv::BORDER_CONSTANT, 0); + + } + } else { + cv::resize(srcimg, dstimg, cv::Size(neww, newh), cv::INTER_AREA); + } + return dstimg; +} + + +int dumpfile(char* file,char** pbuf){ + std::string fname(file); + std::ifstream cache(fname,std::ios::binary); + cache.seekg(0,std::ios::end); + const int engSize = cache.tellg(); + cache.seekg(0,std::ios::beg); + char *modelMem = (char*)malloc(engSize+8000); + cache.read(modelMem,engSize); + cache.close(); + *pbuf = modelMem; + return engSize; +} + +void dumpchar(char* abuf,int len){ + uint8_t* buf = (uint8_t*)abuf; + printf("\n----------------------chardump------------------------\n"); + int i; + for(i = 0; i < len; i++) { + printf("=%u=", buf[i]); + if( (i+1) % 16 == 0) { + printf("\n"); + } + } + if(i%16 != 0) { + printf("\n"); + } + printf("\n----------------------chardump------------------------\n"); +} + + +void dumpfloat(float* abuf,int len){ + printf("\n----------------------floatdump------------------------\n"); + int i; + for(i = 0; i < len; i++) { + printf("=%f=", abuf[i]); + if( (i+1) % 16 == 0) { + printf("\n"); + } + } + if(i%16 != 0) { + printf("\n"); + } + printf("\n----------------------floatdump------------------------\n"); +} + +void dumphex(char* abuf,int len){ + unsigned char* buf = (unsigned char*)abuf; + int i = 0; + printf("\n----------------------hexdump------------------------\n"); + for(i = 0; i < len; i++) { + printf("=%02x=", buf[i]); + if( (i+1) % 16 == 0) { + printf("\n"); + } + } + if(i%16 != 0) { + printf("\n"); + } + printf("---------------------hexdump-------------------------\n\n"); +} + +int diffbuf(char* abuf,char* bbuf,int size){ + char* pa = abuf; + char* pb = bbuf; + int diff = 0; + for(int k= 0;k +#include +#include +#include +//#include +#include +#include + +cv::Mat resize_image(cv::Mat srcimg, int height, int width, int* top, int* left); + +void dumpchar(char* abuf,int len); +void dumphex(char* abuf,int len); +void dumpfloat(float* abuf,int len); +void dumpdouble(double* abuf,int len); +int dumpfile(char* file,char** pbuf); +int diffbuf(char* abuf,char* bbuf,int size); + +uint64_t timer_msstamp(); + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jlog.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jlog.h new file mode 100644 index 0000000000000000000000000000000000000000..92597882c742acfd24e4699ceb0dd20de80de73d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jlog.h @@ -0,0 +1,31 @@ +#pragma once +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef LIB_JNI +#include +#include + +#define LOG_TAG "tooken" +#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) +#define LOGE(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) +#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) + + +#else + +#define LOGE(...) printf(__VA_ARGS__) +#define LOGI(...) printf(__VA_ARGS__) +#define LOGD(...) printf(__VA_ARGS__) + +#endif + +#ifdef __cplusplus +} +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e44b4bfc0f8fd90d517be16a1a2204ffa71e03de --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.cpp @@ -0,0 +1,411 @@ +#include "jmat.h" + +extern "C"{ +#pragma pack(push) +#pragma pack(4) + + typedef struct _gpg_hdr { + char head[4]; + int box[4]; + int size[4]; + int width[4]; + int height[4]; + uint8_t channel[4]; + uint8_t bit[4]; + }gpg_hdr; +#pragma pack(pop) +} + + +int JBuf::zeros(){ + memset(m_buf,0,m_size); + return m_size; +} + +int JBuf::forceref(int bref){ + if(m_ref!=bref){ + m_ref = bref; + } + return 0; +} + +JBuf::JBuf(uint32_t size,void* buf ){ + if(buf){ + m_ref = true; + m_buf = buf; + m_size = size; + }else{ + m_ref = false; + m_size = size; + m_buf = malloc(size+1024); + } +} + +JBuf::~JBuf(){ + if(!m_ref){ + free(m_buf); + m_buf = nullptr; + } +} + +JBuf::JBuf(){ + m_size = 0; + m_buf = nullptr; +} + +JMat::JMat(){ + init_tagarr(); +} + +void JMat::init_tagarr(){ + memset(m_tagarr,0,512*sizeof(int)); +} + +int* JMat::tagarr(){ + return m_tagarr; +} + +int JMat::savegpg(std::string gpgfile){ + gpg_hdr ghead; + memset(&ghead,0,sizeof(gpg_hdr)); + ghead.head[0]='g'; + ghead.head[1]='p'; + ghead.head[2]='g'; + ghead.head[3]='1'; + ghead.size[0]=m_size; + ghead.width[0]=m_width; + ghead.height[0]=m_height; + ghead.channel[0]=m_channel; + ghead.bit[0]=m_bit; + + FILE *gpgFile = NULL; + const char* fn = gpgfile.c_str(); + if ((gpgFile = fopen(fn, "wb")) == NULL)return -1; + fwrite(&ghead,sizeof(gpg_hdr),1,gpgFile); + fwrite(m_buf, m_size, 1, gpgFile); + fclose(gpgFile); + return 0; +} + +int JMat::load(std::string picfile){ + const char* fn = picfile.c_str(); + int len = strlen(fn); + if(len<4)return -1; + fn+= len-3; + int gpg = (fn[0]=='g')&&(fn[1]=='p')&&(fn[2]=='g'); + if(gpg){ + return loadgpg(picfile); + }else{ + return loadjpg(picfile); + } + +} + +int JMat::loadgpg(std::string gpgfile){ + FILE *gpgFile = NULL; + const char* fn = gpgfile.c_str(); + if ((gpgFile = fopen(fn, "rb")) == NULL)return -1; + int rst = 0; + while(1){ + gpg_hdr ghead; + memset(&ghead,0,sizeof(gpg_hdr)); + fread(&ghead,sizeof(gpg_hdr),1,gpgFile); + char* arr=ghead.head; + if((arr[0]=='g')&& + (arr[1]=='p')&& + (arr[2]=='g')){ + + int imgSize = ghead.size[0]; + if(m_sizem_buf,m_buf,m_size); + memcpy(cm->m_tagarr,m_tagarr,512*sizeof(int)); + return cm; + } +} + +JMat JMat::clone(){ + JMat cm(m_width,m_height,m_channel,m_stride,m_bit); + //printf("==clone %d\n",m_size); + memcpy(cm.m_buf,m_buf,m_size); + memcpy(cm.m_tagarr,m_tagarr,512*sizeof(int)); + return cm; +} + +#ifdef USE_OPENCV +JMat::JMat(std::string picfile,int flag):JBuf(){ + cv::Mat image = cv::imread(picfile); + m_bit = flag?1:sizeof(float); + m_width = image.cols; + m_height = image.rows; + m_channel = 3;//image.channels(); + //printf("===channels %d\n",m_channel); + m_stride = m_width*m_channel; + m_size = m_bit*m_stride*m_height; + m_buf = malloc(m_size+m_bit*m_stride); + m_ref = 0; + if(flag){ + memcpy(m_buf,image.data,m_size); + //printf("===w %d h %d\n",image.cols,image.rows); + //cv::imshow("aaa",image); + //cv::waitKey(0); + //cv::Mat fmat(m_height,m_width,CV_8UC3,m_buf); + //float scale = 1.0f/255.0f; + //image.convertTo(fmat,CV_32F,scale); + }else{ + cv::Mat fmat(m_height,m_width,CV_32FC3,m_buf); + float scale = 1.0f/255.0f; + image.convertTo(fmat,CV_32F,scale); + } + image.release(); + init_tagarr(); +} +#else +JMat::JMat(std::string picfile,int flag):JBuf(){ + +} +#endif + +JMat::~JMat(){ +} + +float* JMat::fdata(){ + return (float*)m_buf; +} + +float* JMat::frow(int row){ + return ((float*)m_buf)+ row*m_stride; +} + +float* JMat::fitem(int row,int col){ + return ((float*)m_buf)+ row*m_stride + col; + +} + + +uint8_t* JMat::udata(){ + return (uint8_t*)m_buf; +} +/* + nc::NdArray JMat::ncarray(){ + bool own = false; + nc::NdArray arr = nc::NdArray((float*)m_buf, m_height, m_width, own); + return arr; + } + */ + + +#ifdef USE_NCNN +ncnn::Mat JMat::packingmat(){ + ncnn::Mat in_pack(m_width,m_height,1,(void*)m_buf,(size_t)4u*3,3); + ncnn::Mat in ; + ncnn::convert_packing(in_pack,in,1); + return in; +} + +ncnn::Mat JMat::ncnnmat(){ + unsigned char* data = (unsigned char*)m_buf; + if(m_channel == 3){ + ncnn::Mat mat = ncnn::Mat::from_pixels(data, ncnn::Mat::PIXEL_BGR, m_width, m_height); + return mat; + }else if(m_channel == 4){ + ncnn::Mat mat = ncnn::Mat::from_pixels(data, ncnn::Mat::PIXEL_BGRA, m_width, m_height); + return mat; + }else if(m_channel == 1){ + ncnn::Mat mat = ncnn::Mat::from_pixels(data, ncnn::Mat::PIXEL_GRAY, m_width, m_height); + return mat; + }else { + ncnn::Mat mat = ncnn::Mat::from_pixels(data, ncnn::Mat::PIXEL_GRAY, m_width*m_channel, m_height); + return mat; + } +} +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.h new file mode 100644 index 0000000000000000000000000000000000000000..8ca5660d02a8dca3e98c9bdac13dc0b013ba66e1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/jmat.h @@ -0,0 +1,92 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +//#include "NumCpp.hpp" +#define USE_OPENCV +#define USE_NCNN +#define USE_TURBOJPG + +#ifdef USE_OPENCV +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/highgui.hpp" +#endif + +#ifdef USE_NCNN +#include "mat.h" +#endif + +#ifdef USE_EIGEN +#include "eigen3/Eigen/Core" +typedef Eigen::Matrix Vectorf; +typedef Eigen::Matrix, 1, Eigen::Dynamic, Eigen::RowMajor> Vectorcf; +typedef Eigen::Matrix Matrixf; +typedef Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Matrixcf; +#endif + +class JBuf{ + protected: + bool m_ref = 0; + uint32_t m_size = 0; + void* m_buf = NULL; + public: + uint32_t size(){return m_size;} ; + void* data(){return m_buf;}; + bool ref(){return m_ref;}; + int zeros(); + int forceref(int bref); + JBuf(); + JBuf(uint32_t size,void* buf = nullptr); + virtual ~JBuf(); +}; + +class JMat:public JBuf{ + protected: + int m_bit = 0; + int m_width = 0; + int m_height = 0; + int m_channel = 0; + int m_stride = 0; + int m_tagarr[512]; + void init_tagarr(); + public: + int height(){return m_height;} + int width(){return m_width;} + int stride(){return m_stride;} + int channel(){return m_channel;} + JMat(int w,int h,float *buf ,int c = 3 ,int d = 0); + JMat(int w,int h,uint8_t *buf ,int c = 3 ,int d = 0); + JMat(int w,int h,int c = 3,int d = 0,int b=0); + JMat(std::string picfile,int flag=0); + JMat(); + int load(std::string picfile); + int loadjpg(std::string picfile,int flag=0); + int savegpg(std::string gpgfile); + int loadgpg(std::string gpgfile); + float* fdata(); + float* frow(int row); + float* fitem(int row,int col); + int tojpg(const char* fn); + int tobin(const char* fn); + int show(const char* title); + JMat clone(); + JMat* refclone(int ref=1); + uint8_t* udata(); + virtual ~JMat(); + int* tagarr(); + //nc::NdArray ncarray(); +#ifdef USE_OPENCV + cv::Mat cvmat(); +#endif +#ifdef USE_NCNN + ncnn::Mat ncnnmat(); + ncnn::Mat packingmat(); +#endif + //Matrixf tomatrix(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e59a87ee93a7140bc52a892c8701a4e9ceb72aee --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.cpp @@ -0,0 +1,229 @@ +#include "malpha.h" +#include "blendgram.h" +#include "face_utils.h" + +MWorkMat::MWorkMat(JMat* pic,JMat* msk,const int* boxs){ + m_boxx = boxs[0]; + m_boxy=boxs[1]; + m_boxwidth=boxs[2]-m_boxx; + m_boxheight=boxs[3]-m_boxy; + //printf("x %d y %d w %d h %d \n",m_boxx,m_boxy,m_boxwidth,m_boxheight); + m_pic = pic; + m_msk = msk; + + pic_real160 = new JMat(160,160,3,0,1); + pic_mask160 = new JMat(160,160,3,0,1); + //pic_crop160 = new JMat(160,160,3,0,1); + + msk_real160 = new JMat(160,160,1,0,1); + + //msk_mask160 = new JMat(160,160,3,0,1); + +} + +MWorkMat::~MWorkMat(){ + matpic_org168.release(); + matpic_roirst.release(); + delete pic_real160; + delete pic_mask160; + delete msk_real160; + if(pic_clone160) delete pic_clone160; +} + +int MWorkMat::munet(JMat** ppic,JMat** pmsk){ + *ppic = pic_real160; + *pmsk = pic_mask160; + return 0; +} + +int MWorkMat::premunet(){ + matpic_roisrc = cv::Mat(m_pic->cvmat(),cv::Rect(m_boxx,m_boxy,m_boxwidth,m_boxheight)); + cv::resize(matpic_roisrc , matpic_org168, cv::Size(168, 168), cv::INTER_AREA); + //vtacc + matpic_roi160 = cv::Mat(matpic_org168,cv::Rect(4,4,160,160)); + cv::Mat cvmask = pic_mask160->cvmat(); + cv::Mat cvreal = pic_real160->cvmat(); + matpic_roi160.copyTo(cvmask); + matpic_roi160.copyTo(cvreal); + //cv::rectangle(cvmask,cv::Rect(5,5,150,150),cv::Scalar(0,0,0),-1);//,cv::LineTypes::FILLED); + cv::rectangle(cvmask,cv::Rect(5,5,150,145),cv::Scalar(0,0,0),-1);//,cv::LineTypes::FILLED); + //cv::rectangle(cvmask,cv::Rect(4,4,152,152),cv::Scalar(0,0,0),-1);//,cv::LineTypes::FILLED); + //cv::imwrite("cvmask.bmp",cvmask); + //cv::waitKey(0); + pic_clone160 = pic_real160->refclone(0); + return 0; +} + +int MWorkMat::finmunet(JMat* fgpic){ + cv::Mat cvreal = pic_real160->cvmat(); + cvreal.copyTo(matpic_roi160); + //cv::imwrite("accpre.bmp",matpic_org168); + if(m_msk) vtacc((uint8_t*)matpic_org168.data,168*168); + //cv::imwrite("accend.bmp",matpic_org168); + cv::resize(matpic_org168, matpic_roirst, cv::Size(m_boxwidth, m_boxheight), cv::INTER_AREA); + if(fgpic){ + matpic_roisrc = cv::Mat(fgpic->cvmat(),cv::Rect(m_boxx,m_boxy,m_boxwidth,m_boxheight)); + matpic_roirst.copyTo(matpic_roisrc); + }else{ + matpic_roirst.copyTo(matpic_roisrc); + } + return 0; +} + +int MWorkMat::alpha(JMat** preal,JMat** pimg,JMat** pmsk){ + *preal = pic_clone160; + *pimg = pic_real160; + *pmsk = msk_real160; + return 0; +} + +int MWorkMat::prealpha(){ + printf("x %d y %d w %d h %d \n",m_boxx,m_boxy,m_boxwidth,m_boxheight); + //m_msk->show("cba"); + //cv::waitKey(0); + matmsk_roisrc = cv::Mat(m_msk->cvmat(),cv::Rect(m_boxx,m_boxy,m_boxwidth,m_boxheight)); + cv::resize(matmsk_roisrc , matmsk_org168, cv::Size(168, 168), cv::INTER_AREA); + + matmsk_roi160 = cv::Mat(matmsk_org168,cv::Rect(4,4,160,160)); + cv::Mat cvmask = msk_real160->cvmat(); + cv::cvtColor(matmsk_roi160,cvmask,cv::COLOR_RGB2GRAY); + + //BlendGramAlphaRev(pic_clone160->udata(),msk_real160->udata(),pic_crop160->udata(),160,160); + //pic_crop160->show("aaa"); + //cv::waitKey(0); + //pic_crop160 + // + return 0; +} + +int MWorkMat::finalpha(){ + cv::Mat cvmask = msk_real160->cvmat(); + cv::cvtColor(cvmask,matmsk_roi160,cv::COLOR_GRAY2RGB); + // + cv::resize(matmsk_org168, matmsk_roirst, cv::Size(m_boxwidth, m_boxheight), cv::INTER_AREA); + matmsk_roirst.copyTo(matmsk_roisrc); + return 0; +} + +int MWorkMat::vtacc(uint8_t* buf,int count){ + /* + int avgr = 0; + int avgb = 0; + int avgg = 0; + if(1){ + uint8_t* pb = m_pic->udata(); + for(int k=0;k<10;k++){ + avgr += *pb++; + avgg += *pb++; + avgb += *pb++; + } + avgr =avgr/10 +10; + avgg =avgg/10 -20; + if(avgg<0)avgg=0; + avgb =avgb/10 + 10; + } + */ + uint8_t* pb = buf; + for(int k=0;k=sum){ + pb[1]=sum; + //pb[0]=0; + //pb[2]=0; + // }else if((pb[0]avgg)&&(pb[2]255.f)?255:mean; + //printf("sum %ld mean %f maxg %d\n",sum,mean,maxg); + //getchar(); + pb = buf +1; + for(int k=0;kmaxg){ + *pb = maxg; + } + pb+=3; + } + */ + return 0; +} + +int MAlpha::doModel(JMat* real,JMat* img,JMat* pha){ + if(1)return 0; + /* + if(1)return 0; + JMat picimg(160,160,3,0,1); + JMat picreal(160,160,3,0,1); + cv::cvtColor(real->cvmat(),picreal.cvmat(),cv::COLOR_RGB2BGR); + cv::cvtColor(img->cvmat(),picimg.cvmat(),cv::COLOR_RGB2BGR); + */ + float mean_vals[3] = {127.5f, 127.5f, 127.5f}; + float norm_vals[3] = {1 / 127.5f, 1 / 127.5f, 1 / 127.5f}; + ncnn::Mat inimg = ncnn::Mat::from_pixels(img->udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inimg.substract_mean_normalize(mean_vals, norm_vals); + ncnn::Mat inreal = ncnn::Mat::from_pixels(real->udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inreal.substract_mean_normalize(mean_vals, norm_vals); + ncnn::Mat inpha = ncnn::Mat::from_pixels(pha->udata(), ncnn::Mat::PIXEL_GRAY, 160, 160); + float gmean_vals[3] = {0.0f, 0.0f, 0.0f}; + float gnorm_vals[3] = {1 / 255.0f, 1 / 255.0f, 1 / 255.0f}; + inpha.substract_mean_normalize(gmean_vals, gnorm_vals); + + ncnn::Mat inpic(160,160,7); + //printf("===in %d %d all %d %d pha %d %d\n",inreal.cstep,inreal.elempack,inpic.cstep,inpic.elempack,inpha.cstep,inpha.elempack); + //JMat picin(160,160,7); + float* buf = (float*)inpic.data; + memcpy(buf,inreal.data,inreal.cstep*inreal.c*sizeof(float)); + buf += inpic.cstep*inreal.c; + memcpy(buf,inimg.data,inimg.cstep*inimg.c*sizeof(float)); + buf += inimg.cstep*inimg.c; + memcpy(buf, inpha.data,inpha.cstep*sizeof(float)); + //ncnn::Mat inpic(160,160,7,pd,4); + //ncnn::Mat inpack(160,160,1,pd,(size_t)4u*7,7); + //ncnn::Mat inpic; + //ncnn::convert_packing(inpack,inpic,1); + ncnn::Mat outpic; + ncnn::Extractor ex = net.create_extractor(); + int rst = ex.input("input", inpic); + //printf("input %d\n",rst); + rst = ex.extract("output", outpic); + //printf("output %d\n",rst); + float outmean_vals[3] = {0.0f, 0.0f, 0.0f}; + float outnorm_vals[3] = { 255.0f, 255.0f, 255.0f}; + outpic.substract_mean_normalize(outmean_vals, outnorm_vals); + outpic.to_pixels(pha->udata(),ncnn::Mat::PIXEL_GRAY); + //pha->show("mmm"); + //cv::waitKey(0); + //dumpfloat((float*)outpic.data+160*159,10); + //ncnn::Mat pakpic; + //ncnn::convert_packing(outpic,pakpic,1); + //dumpfloat((float*)pakpic.data,160*160*1); + //getchar(); + /* + cv::Mat cvadj(160,160,CV_32FC1,outpic.data); + cv::Mat cvout;//(160,160,CV_8UC1); + float scale = 255.0f;//255.0f; + cvadj.convertTo(cvout,CV_8UC1,scale); + cvout.copyTo(pha->cvmat()); + */ + //cv::imshow("pha",cvout); + //pha->show("pha"); + //cv::waitKey(0); + return 0; +} + +MAlpha::MAlpha(const char* fnbin,const char* fnparam):NcnnModel(160,160){ + std::string fb(fnbin); + std::string fp(fnparam); + initModel(fb,fp); +} + +MAlpha::~MAlpha(){ + +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.h new file mode 100644 index 0000000000000000000000000000000000000000..8bb007ef4ec78ad43525ecc28f8cebb67babac18 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/malpha.h @@ -0,0 +1,59 @@ +#pragma once +#include "jmat.h" +#include "net.h" +#include +#include +#include +#include +#include +#include "aimodel.h" + +class MWorkMat{ + private: + int m_boxx; + int m_boxy; + int m_boxwidth; + int m_boxheight; + JMat* m_pic; + JMat* m_msk; + + JMat* pic_real160;//blendimg + JMat* pic_mask160; + + cv::Mat matpic_roisrc;//box area + cv::Mat matpic_org168; + cv::Mat matpic_roi160; + JMat* pic_clone160;//blendimg + cv::Mat matpic_roirst; + + //JMat* pic_crop160; + // + JMat* msk_real160; + //JMat* msk_mask160; + + cv::Mat matmsk_roisrc;//box area + cv::Mat matmsk_org168; + cv::Mat matmsk_roi160; + + cv::Mat matmsk_roirst; + + int vtacc(uint8_t* buf,int count); + public: + MWorkMat(JMat* pic,JMat* msk,const int* boxs); + int premunet(); + int munet(JMat** ppic,JMat** pmsk); + int finmunet(JMat* fgpic=NULL); + int prealpha(); + int alpha(JMat** preal,JMat** pimg,JMat** pmsk); + int finalpha(); + + virtual ~MWorkMat(); +}; + +class MAlpha:public NcnnModel{ + private: + public: + int doModel(JMat* real,JMat* img,JMat* pha); + MAlpha(const char* fnbin,const char* fnparam); + virtual ~MAlpha(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/AudioFFT.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/AudioFFT.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3ccfcae672f67fb92b45a5a3d736404e0c80bed4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/AudioFFT.hpp @@ -0,0 +1,1264 @@ +#pragma once + +#ifndef _AUDIOFFT_H +#define _AUDIOFFT_H + + + +#include +#include +#include +#include +#include + +//#define AUDIOFFT_APPLE_ACCELERATE //AUDIOFFT_INTEL_IPP//AUDIOFFT_FFTW3//AUDIOFFT_APPLE_ACCELERATE + +#if defined(AUDIOFFT_INTEL_IPP) +#define AUDIOFFT_INTEL_IPP_USED + #include +#elif defined(AUDIOFFT_APPLE_ACCELERATE) +#define AUDIOFFT_APPLE_ACCELERATE_USED + #include + #include +#elif defined (AUDIOFFT_FFTW3) +#define AUDIOFFT_FFTW3_USED + #include +#else +#if !defined(AUDIOFFT_OOURA) +#define AUDIOFFT_OOURA +#endif +#define AUDIOFFT_OOURA_USED +#include +#endif + +namespace audiofft +{ + + namespace detail + { + class AudioFFTImpl; + } + + + // ============================================================= + + + /** + * @class AudioFFT + * @brief Performs 1D FFTs + */ + class AudioFFT + { + public: + /** + * @brief Constructor + */ + AudioFFT(); + + AudioFFT(const AudioFFT&) = delete; + AudioFFT& operator=(const AudioFFT&) = delete; + + /** + * @brief Destructor + */ + ~AudioFFT(); + + /** + * @brief Initializes the FFT object + * @param size Size of the real input (must be power 2) + */ + void init(size_t size); + + /** + * @brief Performs the forward FFT + * @param data The real input data (has to be of the length as specified in init()) + * @param re The real part of the complex output (has to be of length as returned by ComplexSize()) + * @param im The imaginary part of the complex output (has to be of length as returned by ComplexSize()) + */ + void fft(const float* data, float* re, float* im); + + /** + * @brief Performs the inverse FFT + * @param data The real output data (has to be of the length as specified in init()) + * @param re The real part of the complex input (has to be of length as returned by ComplexSize()) + * @param im The imaginary part of the complex input (has to be of length as returned by ComplexSize()) + */ + void ifft(float* data, const float* re, const float* im); + + /** + * @brief Calculates the necessary size of the real/imaginary complex arrays + * @param size The size of the real data + * @return The size of the real/imaginary complex arrays + */ + static size_t ComplexSize(size_t size); + + private: + std::unique_ptr _impl; + }; + + + /** + * @deprecated + * @brief Let's keep an AudioFFTBase type around for now because it has been here already in the 1st version in order to avoid breaking existing code. + */ + typedef AudioFFT AudioFFTBase; + +} // End of namespace + + +namespace audiofft +{ + + namespace detail + { + + class AudioFFTImpl + { + public: + AudioFFTImpl() = default; + AudioFFTImpl(const AudioFFTImpl&) = delete; + AudioFFTImpl& operator=(const AudioFFTImpl&) = delete; + virtual ~AudioFFTImpl() = default; + virtual void init(size_t size) = 0; + virtual void fft(const float* data, float* re, float* im) = 0; + virtual void ifft(float* data, const float* re, const float* im) = 0; + }; + + + constexpr bool IsPowerOf2(size_t val) + { + return (val == 1 || (val & (val-1)) == 0); + } + + + template + void ConvertBuffer(TypeDest* dest, const TypeSrc* src, size_t len) + { + for (size_t i=0; i(src[i]); + } + } + + + template + void ScaleBuffer(TypeDest* dest, const TypeSrc* src, const TypeFactor factor, size_t len) + { + for (size_t i=0; i(static_cast(src[i]) * factor); + } + } + + } // End of namespace detail + + + // ================================================================ + + +#ifdef AUDIOFFT_OOURA_USED + + /** + * @internal + * @class OouraFFT + * @brief FFT implementation based on the great radix-4 routines by Takuya Ooura + */ + class OouraFFT : public detail::AudioFFTImpl + { + public: + OouraFFT() : + detail::AudioFFTImpl(), + _size(0), + _ip(), + _w(), + _buffer() + { + } + + OouraFFT(const OouraFFT&) = delete; + OouraFFT& operator=(const OouraFFT&) = delete; + + virtual void init(size_t size) override + { + if (_size != size) + { + _ip.resize(2 + static_cast(std::sqrt(static_cast(size)))); + _w.resize(size / 2); + _buffer.resize(size); + _size = size; + + const int size4 = static_cast(_size) / 4; + makewt(size4, _ip.data(), _w.data()); + makect(size4, _ip.data(), _w.data() + size4); + } + } + + virtual void fft(const float* data, float* re, float* im) override + { + // Convert into the format as required by the Ooura FFT + detail::ConvertBuffer(_buffer.data(), data, _size); + + rdft(static_cast(_size), +1, _buffer.data(), _ip.data(), _w.data()); + + // Convert back to split-complex + { + double* b = _buffer.data(); + double* bEnd = b + _size; + float *r = re; + float *i = im; + while (b != bEnd) + { + *(r++) = static_cast(*(b++)); + *(i++) = static_cast(-(*(b++))); + } + } + const size_t size2 = _size / 2; + re[size2] = -im[0]; + im[0] = 0.0; + im[size2] = 0.0; + } + + virtual void ifft(float* data, const float* re, const float* im) override + { + // Convert into the format as required by the Ooura FFT + { + double* b = _buffer.data(); + double* bEnd = b + _size; + const float *r = re; + const float *i = im; + while (b != bEnd) + { + *(b++) = static_cast(*(r++)); + *(b++) = -static_cast(*(i++)); + } + _buffer[1] = re[_size / 2]; + } + + rdft(static_cast(_size), -1, _buffer.data(), _ip.data(), _w.data()); + + // Convert back to split-complex + detail::ScaleBuffer(data, _buffer.data(), 2.0 / static_cast(_size), _size); + } + + private: + size_t _size; + std::vector _ip; + std::vector _w; + std::vector _buffer; + + void rdft(int n, int isgn, double *a, int *ip, double *w) + { + int nw = ip[0]; + int nc = ip[1]; + + if (isgn >= 0) + { + if (n > 4) + { + bitrv2(n, ip + 2, a); + cftfsub(n, a, w); + rftfsub(n, a, nc, w + nw); + } + else if (n == 4) + { + cftfsub(n, a, w); + } + double xi = a[0] - a[1]; + a[0] += a[1]; + a[1] = xi; + } + else + { + a[1] = 0.5 * (a[0] - a[1]); + a[0] -= a[1]; + if (n > 4) + { + rftbsub(n, a, nc, w + nw); + bitrv2(n, ip + 2, a); + cftbsub(n, a, w); + } + else if (n == 4) + { + cftfsub(n, a, w); + } + } + } + + + /* -------- initializing routines -------- */ + + void makewt(int nw, int *ip, double *w) + { + int j, nwh; + double delta, x, y; + + ip[0] = nw; + ip[1] = 1; + if (nw > 2) { + nwh = nw >> 1; + delta = atan(1.0) / nwh; + w[0] = 1; + w[1] = 0; + w[nwh] = cos(delta * nwh); + w[nwh + 1] = w[nwh]; + if (nwh > 2) { + for (j = 2; j < nwh; j += 2) { + x = cos(delta * j); + y = sin(delta * j); + w[j] = x; + w[j + 1] = y; + w[nw - j] = y; + w[nw - j + 1] = x; + } + bitrv2(nw, ip + 2, w); + } + } + } + + + void makect(int nc, int *ip, double *c) + { + int j, nch; + double delta; + + ip[1] = nc; + if (nc > 1) { + nch = nc >> 1; + delta = atan(1.0) / nch; + c[0] = cos(delta * nch); + c[nch] = 0.5 * c[0]; + for (j = 1; j < nch; j++) { + c[j] = 0.5 * cos(delta * j); + c[nc - j] = 0.5 * sin(delta * j); + } + } + } + + + /* -------- child routines -------- */ + + + void bitrv2(int n, int *ip, double *a) + { + int j, j1, k, k1, l, m, m2; + double xr, xi, yr, yi; + + ip[0] = 0; + l = n; + m = 1; + while ((m << 3) < l) { + l >>= 1; + for (j = 0; j < m; j++) { + ip[m + j] = ip[j] + l; + } + m <<= 1; + } + m2 = 2 * m; + if ((m << 3) == l) { + for (k = 0; k < m; k++) { + for (j = 0; j < k; j++) { + j1 = 2 * j + ip[k]; + k1 = 2 * k + ip[j]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 -= m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += 2 * m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + j1 = 2 * k + m2 + ip[k]; + k1 = j1 + m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + } else { + for (k = 1; k < m; k++) { + for (j = 0; j < k; j++) { + j1 = 2 * j + ip[k]; + k1 = 2 * k + ip[j]; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + j1 += m2; + k1 += m2; + xr = a[j1]; + xi = a[j1 + 1]; + yr = a[k1]; + yi = a[k1 + 1]; + a[j1] = yr; + a[j1 + 1] = yi; + a[k1] = xr; + a[k1 + 1] = xi; + } + } + } + } + + + void cftfsub(int n, double *a, double *w) + { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + l = 2; + if (n > 8) { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) { + cftmdl(n, l, a, w); + l <<= 2; + } + } + if ((l << 2) == n) { + for (j = 0; j < l; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i - x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i + x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i - x3r; + } + } else { + for (j = 0; j < l; j += 2) { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = a[j + 1] - a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] += a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + + void cftbsub(int n, double *a, double *w) + { + int j, j1, j2, j3, l; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + l = 2; + if (n > 8) { + cft1st(n, a, w); + l = 8; + while ((l << 2) < n) { + cftmdl(n, l, a, w); + l <<= 2; + } + } + if ((l << 2) == n) { + for (j = 0; j < l; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = -a[j + 1] - a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = -a[j + 1] + a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i - x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i + x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i - x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i + x3r; + } + } else { + for (j = 0; j < l; j += 2) { + j1 = j + l; + x0r = a[j] - a[j1]; + x0i = -a[j + 1] + a[j1 + 1]; + a[j] += a[j1]; + a[j + 1] = -a[j + 1] - a[j1 + 1]; + a[j1] = x0r; + a[j1 + 1] = x0i; + } + } + } + + + void cft1st(int n, double *a, double *w) + { + int j, k1, k2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + x0r = a[0] + a[2]; + x0i = a[1] + a[3]; + x1r = a[0] - a[2]; + x1i = a[1] - a[3]; + x2r = a[4] + a[6]; + x2i = a[5] + a[7]; + x3r = a[4] - a[6]; + x3i = a[5] - a[7]; + a[0] = x0r + x2r; + a[1] = x0i + x2i; + a[4] = x0r - x2r; + a[5] = x0i - x2i; + a[2] = x1r - x3i; + a[3] = x1i + x3r; + a[6] = x1r + x3i; + a[7] = x1i - x3r; + wk1r = w[2]; + x0r = a[8] + a[10]; + x0i = a[9] + a[11]; + x1r = a[8] - a[10]; + x1i = a[9] - a[11]; + x2r = a[12] + a[14]; + x2i = a[13] + a[15]; + x3r = a[12] - a[14]; + x3i = a[13] - a[15]; + a[8] = x0r + x2r; + a[9] = x0i + x2i; + a[12] = x2i - x0i; + a[13] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[10] = wk1r * (x0r - x0i); + a[11] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[14] = wk1r * (x0i - x0r); + a[15] = wk1r * (x0i + x0r); + k1 = 0; + for (j = 16; j < n; j += 16) { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + x0r = a[j] + a[j + 2]; + x0i = a[j + 1] + a[j + 3]; + x1r = a[j] - a[j + 2]; + x1i = a[j + 1] - a[j + 3]; + x2r = a[j + 4] + a[j + 6]; + x2i = a[j + 5] + a[j + 7]; + x3r = a[j + 4] - a[j + 6]; + x3i = a[j + 5] - a[j + 7]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 4] = wk2r * x0r - wk2i * x0i; + a[j + 5] = wk2r * x0i + wk2i * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 2] = wk1r * x0r - wk1i * x0i; + a[j + 3] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 6] = wk3r * x0r - wk3i * x0i; + a[j + 7] = wk3r * x0i + wk3i * x0r; + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + x0r = a[j + 8] + a[j + 10]; + x0i = a[j + 9] + a[j + 11]; + x1r = a[j + 8] - a[j + 10]; + x1i = a[j + 9] - a[j + 11]; + x2r = a[j + 12] + a[j + 14]; + x2i = a[j + 13] + a[j + 15]; + x3r = a[j + 12] - a[j + 14]; + x3i = a[j + 13] - a[j + 15]; + a[j + 8] = x0r + x2r; + a[j + 9] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j + 12] = -wk2i * x0r - wk2r * x0i; + a[j + 13] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j + 10] = wk1r * x0r - wk1i * x0i; + a[j + 11] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j + 14] = wk3r * x0r - wk3i * x0i; + a[j + 15] = wk3r * x0i + wk3i * x0r; + } + } + + + void cftmdl(int n, int l, double *a, double *w) + { + int j, j1, j2, j3, k, k1, k2, m, m2; + double wk1r, wk1i, wk2r, wk2i, wk3r, wk3i; + double x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i; + + m = l << 2; + for (j = 0; j < l; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x0r - x2r; + a[j2 + 1] = x0i - x2i; + a[j1] = x1r - x3i; + a[j1 + 1] = x1i + x3r; + a[j3] = x1r + x3i; + a[j3 + 1] = x1i - x3r; + } + wk1r = w[2]; + for (j = m; j < l + m; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + a[j2] = x2i - x0i; + a[j2 + 1] = x0r - x2r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * (x0r - x0i); + a[j1 + 1] = wk1r * (x0r + x0i); + x0r = x3i + x1r; + x0i = x3r - x1i; + a[j3] = wk1r * (x0i - x0r); + a[j3 + 1] = wk1r * (x0i + x0r); + } + k1 = 0; + m2 = 2 * m; + for (k = m2; k < n; k += m2) { + k1 += 2; + k2 = 2 * k1; + wk2r = w[k1]; + wk2i = w[k1 + 1]; + wk1r = w[k2]; + wk1i = w[k2 + 1]; + wk3r = wk1r - 2 * wk2i * wk1i; + wk3i = 2 * wk2i * wk1r - wk1i; + for (j = k; j < l + k; j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j2] = wk2r * x0r - wk2i * x0i; + a[j2 + 1] = wk2r * x0i + wk2i * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; + } + wk1r = w[k2 + 2]; + wk1i = w[k2 + 3]; + wk3r = wk1r - 2 * wk2r * wk1i; + wk3i = 2 * wk2r * wk1r - wk1i; + for (j = k + m; j < l + (k + m); j += 2) { + j1 = j + l; + j2 = j1 + l; + j3 = j2 + l; + x0r = a[j] + a[j1]; + x0i = a[j + 1] + a[j1 + 1]; + x1r = a[j] - a[j1]; + x1i = a[j + 1] - a[j1 + 1]; + x2r = a[j2] + a[j3]; + x2i = a[j2 + 1] + a[j3 + 1]; + x3r = a[j2] - a[j3]; + x3i = a[j2 + 1] - a[j3 + 1]; + a[j] = x0r + x2r; + a[j + 1] = x0i + x2i; + x0r -= x2r; + x0i -= x2i; + a[j2] = -wk2i * x0r - wk2r * x0i; + a[j2 + 1] = -wk2i * x0i + wk2r * x0r; + x0r = x1r - x3i; + x0i = x1i + x3r; + a[j1] = wk1r * x0r - wk1i * x0i; + a[j1 + 1] = wk1r * x0i + wk1i * x0r; + x0r = x1r + x3i; + x0i = x1i - x3r; + a[j3] = wk3r * x0r - wk3i * x0i; + a[j3 + 1] = wk3r * x0i + wk3i * x0r; + } + } + } + + + void rftfsub(int n, double *a, int nc, double *c) + { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; + + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) { + k = n - j; + kk += ks; + wkr = 0.5 - c[nc - kk]; + wki = c[kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr - wki * xi; + yi = wkr * xi + wki * xr; + a[j] -= yr; + a[j + 1] -= yi; + a[k] += yr; + a[k + 1] -= yi; + } + } + + + void rftbsub(int n, double *a, int nc, double *c) + { + int j, k, kk, ks, m; + double wkr, wki, xr, xi, yr, yi; + + a[1] = -a[1]; + m = n >> 1; + ks = 2 * nc / m; + kk = 0; + for (j = 2; j < m; j += 2) { + k = n - j; + kk += ks; + wkr = 0.5 - c[nc - kk]; + wki = c[kk]; + xr = a[j] - a[k]; + xi = a[j + 1] + a[k + 1]; + yr = wkr * xr + wki * xi; + yi = wkr * xi - wki * xr; + a[j] -= yr; + a[j + 1] = yi - a[j + 1]; + a[k] += yr; + a[k + 1] = yi - a[k + 1]; + } + a[m + 1] = -a[m + 1]; + } + }; + + + /** + * @internal + * @brief Concrete FFT implementation + */ + typedef OouraFFT AudioFFTImplementation; + + +#endif // AUDIOFFT_OOURA_USED + + + // ================================================================ + + +#ifdef AUDIOFFT_INTEL_IPP_USED + + + /** + * @internal + * @class IntelIppFFT + * @brief FFT implementation using the Intel Integrated Performance Primitives + */ + class IntelIppFFT : public detail::AudioFFTImpl + { + public: + IntelIppFFT() : + detail::AudioFFTImpl(), + _size(0), + _operationalBufferSize(0), + _powerOf2(0), + _fftSpec(nullptr), + _fftSpecBuf(0), + _fftWorkBuf(0), + _operationalBuffer(nullptr) + { + ippInit(); + } + + IntelIppFFT(const IntelIppFFT&) = delete; + IntelIppFFT& operator=(const IntelIppFFT&) = delete; + + virtual ~IntelIppFFT() + { + init(0); + } + + virtual void init(size_t size) override + { + if (_fftSpec) + { + if (_fftWorkBuf) ippFree(_fftWorkBuf); + if (_fftSpecBuf) ippFree(_fftSpecBuf); + ippFree(_operationalBuffer); + + _size = 0; + _operationalBufferSize = 0; + _powerOf2 = 0; + _fftSpec = 0; + } + + if (size > 0) + { + _size = size; + _operationalBufferSize = _size + 2; + _powerOf2 = (int)(log((double)_size)/log(2.0)); + + // Query to get buffer sizes + int sizeFFTSpec, + sizeFFTInitBuf, + sizeFFTWorkBuf; + ippsFFTGetSize_R_32f( + _powerOf2, + IPP_FFT_NODIV_BY_ANY, + ippAlgHintAccurate, + &sizeFFTSpec, + &sizeFFTInitBuf, + &sizeFFTWorkBuf + ); + + Ipp8u* fftInitBuf; + + // init buffers + _fftSpecBuf = ippsMalloc_8u(sizeFFTSpec); + _fftWorkBuf = ippsMalloc_8u(sizeFFTWorkBuf); + fftInitBuf = ippsMalloc_8u(sizeFFTInitBuf); + + // Initialize FFT + ippsFFTInit_R_32f( + &_fftSpec, + _powerOf2, + IPP_FFT_NODIV_BY_ANY, + ippAlgHintAccurate, + _fftSpecBuf, + fftInitBuf + ); + if (fftInitBuf) ippFree(fftInitBuf); + + // init operational buffer + _operationalBuffer = ippsMalloc_32f( + _operationalBufferSize + ); + } + } + + virtual void fft(const float* data, float* re, float* im) override + { + size_t complexNumbersCount = _operationalBufferSize / 2; + ippsFFTFwd_RToCCS_32f( + data, + _operationalBuffer, + _fftSpec, + _fftWorkBuf + ); + + // no need to scale + + size_t complexCounter = 0; + for (int i = 0; i < complexNumbersCount; ++i) + { + re[i] = _operationalBuffer[complexCounter++]; + im[i] = _operationalBuffer[complexCounter++]; + } + } + + virtual void ifft(float* data, const float* re, const float* im) override + { + size_t complexNumbersCount = _operationalBufferSize / 2; + + size_t complexCounter = 0; + for (int i = 0; i < complexNumbersCount; ++i) + { + _operationalBuffer[complexCounter++] = re[i]; + _operationalBuffer[complexCounter++] = im[i]; + } + + ippsFFTInv_CCSToR_32f( + _operationalBuffer, + data, + _fftSpec, + _fftWorkBuf + ); + + // scaling + const float factor = 1.0f / static_cast(_size); + ippsMulC_32f_I(factor, data, _size); + } + + private: + size_t _size; + size_t _operationalBufferSize; + size_t _powerOf2; + IppsFFTSpec_R_32f* _fftSpec; + Ipp8u* _fftSpecBuf; + Ipp8u* _fftWorkBuf; + Ipp32f* _operationalBuffer; + }; + + + /** + * @internal + * @brief Concrete FFT implementation + */ + typedef IntelIppFFT AudioFFTImplementation; + + +#endif // AUDIOFFT_INTEL_IPP_USED + + + // ================================================================ + + +#ifdef AUDIOFFT_APPLE_ACCELERATE_USED + + + /** + * @internal + * @class AppleAccelerateFFT + * @brief FFT implementation using the Apple Accelerate framework internally + */ + class AppleAccelerateFFT : public detail::AudioFFTImpl + { + public: + AppleAccelerateFFT() : + detail::AudioFFTImpl(), + _size(0), + _powerOf2(0), + _fftSetup(0), + _re(), + _im() + { + } + + AppleAccelerateFFT(const AppleAccelerateFFT&) = delete; + AppleAccelerateFFT& operator=(const AppleAccelerateFFT&) = delete; + + virtual ~AppleAccelerateFFT() + { + init(0); + } + + virtual void init(size_t size) override + { + if (_fftSetup) + { + vDSP_destroy_fftsetup(_fftSetup); + _size = 0; + _powerOf2 = 0; + _fftSetup = 0; + _re.clear(); + _im.clear(); + } + + if (size > 0) + { + _size = size; + _powerOf2 = 0; + while ((1 << _powerOf2) < _size) + { + ++_powerOf2; + } + _fftSetup = vDSP_create_fftsetup(_powerOf2, FFT_RADIX2); + _re.resize(_size / 2); + _im.resize(_size / 2); + } + } + + virtual void fft(const float* data, float* re, float* im) override + { + const size_t size2 = _size / 2; + DSPSplitComplex splitComplex; + splitComplex.realp = re; + splitComplex.imagp = im; + vDSP_ctoz(reinterpret_cast(data), 2, &splitComplex, 1, size2); + vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_FORWARD); + const float factor = 0.5f; + vDSP_vsmul(re, 1, &factor, re, 1, size2); + vDSP_vsmul(im, 1, &factor, im, 1, size2); + re[size2] = im[0]; + im[0] = 0.0f; + im[size2] = 0.0f; + } + + virtual void ifft(float* data, const float* re, const float* im) override + { + const size_t size2 = _size / 2; + ::memcpy(_re.data(), re, size2 * sizeof(float)); + ::memcpy(_im.data(), im, size2 * sizeof(float)); + _im[0] = re[size2]; + DSPSplitComplex splitComplex; + splitComplex.realp = _re.data(); + splitComplex.imagp = _im.data(); + vDSP_fft_zrip(_fftSetup, &splitComplex, 1, _powerOf2, FFT_INVERSE); + vDSP_ztoc(&splitComplex, 1, reinterpret_cast(data), 2, size2); + const float factor = 1.0f / static_cast(_size); + vDSP_vsmul(data, 1, &factor, data, 1, _size); + } + + private: + size_t _size; + size_t _powerOf2; + FFTSetup _fftSetup; + std::vector _re; + std::vector _im; + }; + + + /** + * @internal + * @brief Concrete FFT implementation + */ + typedef AppleAccelerateFFT AudioFFTImplementation; + + +#endif // AUDIOFFT_APPLE_ACCELERATE_USED + + + // ================================================================ + + +#ifdef AUDIOFFT_FFTW3_USED + + + /** + * @internal + * @class FFTW3FFT + * @brief FFT implementation using FFTW3 internally (see fftw.org) + */ + class FFTW3FFT : public detail::AudioFFTImpl + { + public: + FFTW3FFT() : + detail::AudioFFTImpl(), + _size(0), + _complexSize(0), + _planForward(0), + _planBackward(0), + _data(0), + _re(0), + _im(0) + { + } + + FFTW3FFT(const FFTW3FFT&) = delete; + FFTW3FFT& operator=(const FFTW3FFT&) = delete; + + virtual ~FFTW3FFT() + { + init(0); + } + + virtual void init(size_t size) override + { + if (_size != size) + { + if (_size > 0) + { + fftwf_destroy_plan(_planForward); + fftwf_destroy_plan(_planBackward); + _planForward = 0; + _planBackward = 0; + _size = 0; + _complexSize = 0; + + if (_data) + { + fftwf_free(_data); + _data = 0; + } + + if (_re) + { + fftwf_free(_re); + _re = 0; + } + + if (_im) + { + fftwf_free(_im); + _im = 0; + } + } + + if (size > 0) + { + _size = size; + _complexSize = AudioFFT::ComplexSize(_size); + const size_t complexSize = AudioFFT::ComplexSize(_size); + _data = reinterpret_cast(fftwf_malloc(_size * sizeof(float))); + _re = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); + _im = reinterpret_cast(fftwf_malloc(complexSize * sizeof(float))); + + fftw_iodim dim; + dim.n = static_cast(size); + dim.is = 1; + dim.os = 1; + _planForward = fftwf_plan_guru_split_dft_r2c(1, &dim, 0, 0, _data, _re, _im, FFTW_MEASURE); + _planBackward = fftwf_plan_guru_split_dft_c2r(1, &dim, 0, 0, _re, _im, _data, FFTW_MEASURE); + } + } + } + + virtual void fft(const float* data, float* re, float* im) override + { + ::memcpy(_data, data, _size * sizeof(float)); + fftwf_execute_split_dft_r2c(_planForward, _data, _re, _im); + ::memcpy(re, _re, _complexSize * sizeof(float)); + ::memcpy(im, _im, _complexSize * sizeof(float)); + } + + virtual void ifft(float* data, const float* re, const float* im) override + { + ::memcpy(_re, re, _complexSize * sizeof(float)); + ::memcpy(_im, im, _complexSize * sizeof(float)); + fftwf_execute_split_dft_c2r(_planBackward, _re, _im, _data); + detail::ScaleBuffer(data, _data, 1.0f / static_cast(_size), _size); + } + + private: + size_t _size; + size_t _complexSize; + fftwf_plan _planForward; + fftwf_plan _planBackward; + float* _data; + float* _re; + float* _im; + }; + + + /** + * @internal + * @brief Concrete FFT implementation + */ + typedef FFTW3FFT AudioFFTImplementation; + + +#endif // AUDIOFFT_FFTW3_USED + + + // ============================================================= + + + AudioFFT::AudioFFT() : + _impl(new AudioFFTImplementation()) + { + } + + + AudioFFT::~AudioFFT() + { + } + + + void AudioFFT::init(size_t size) + { + assert(detail::IsPowerOf2(size)); + _impl->init(size); + } + + + void AudioFFT::fft(const float* data, float* re, float* im) + { + _impl->fft(data, re, im); + } + + + void AudioFFT::ifft(float* data, const float* re, const float* im) + { + _impl->ifft(data, re, im); + } + + + size_t AudioFFT::ComplexSize(size_t size) + { + return (size / 2) + 1; + } + +} // End of namespace + + +#endif // Header guard diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/iir_filter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/iir_filter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3906806350e091d7836b88050316e4036a88a4a9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/iir_filter.hpp @@ -0,0 +1,375 @@ +#pragma once + +#ifndef SERVICESUPERVISOR_IIR_FILTER_H +#define SERVICESUPERVISOR_IIR_FILTER_H + +//E(t,f) is computed using a first-order in-finite impulse response (IIR) filter +#define UES_IIR_I +//#define UES_IIR_II + +#ifdef UES_IIR_I + +class IIR_I +{ +private: + double *m_pNum; + double *m_pDen; + double *m_px; + double *m_py; + int m_num_order; + int m_den_order; +public: + IIR_I(); + ~IIR_I(); + void reset(); + void setPara(double num[], int num_order, double den[], int den_order); + void resp(double data_in[], int m, double data_out[], int n); + void filter(double data_in[], double data_out[], int len); +}; +/** \brief 将滤波器的内部状态清零,滤波器的系数保留 + * \return + */ +void IIR_I::reset() +{ + for(int i = 0; i <= m_num_order; i++) + { + m_pNum[i] = 0.0; + } + for(int i = 0; i <= m_den_order; i++) + { + m_pDen[i] = 0.0; + } +} +IIR_I::IIR_I() +{ + m_pNum = NULL; + m_pDen = NULL; + m_px = NULL; + m_py = NULL; + m_num_order = -1; + m_den_order = -1; +}; +IIR_I::~IIR_I() +{ + delete[] m_pNum; + delete[] m_pDen; + delete[] m_px; + delete[] m_py; + m_pNum = NULL; + m_pDen = NULL; + m_px = NULL; + m_py = NULL; +}; + +/** \brief + * + * \param num 分子多项式的系数,升序排列,num[0] 为常数项 + * \param m 分子多项式的阶数 + * \param den 分母多项式的系数,升序排列,den[0] 为常数项 + * \param m 分母多项式的阶数 + * \return + */ +void IIR_I::setPara(double num[], int num_order, double den[], int den_order) +{ + delete[] m_pNum; + delete[] m_pDen; + delete[] m_px; + delete[] m_py; + m_pNum = new double[num_order + 1]; + m_pDen = new double[den_order + 1]; + m_num_order = num_order; + m_den_order = den_order; + m_px = new double[num_order + 1]; + m_py = new double[den_order + 1]; + for(int i = 0; i < m_num_order; i++) + { + m_pNum[i] = num[i]; + m_px[i] = 0.0; + } + m_pNum[m_num_order] = 0.0; + m_px[m_num_order] = 0.0; + for(int i = 0; i < m_den_order; i++) + { + m_pDen[i] = den[i]; + m_py[i] = 0.0; + } + m_pDen[m_den_order] = 0.0; + m_py[m_den_order] = 0.0; +} + +/** \brief 计算 IIR 滤波器的时域响应,不影响滤波器的内部状态 + * \param data_in 为滤波器的输入,0 时刻之前的输入默认为 0,data_in[M] 及之后的输入默认为data_in[M-1] + * \param data_out 滤波器的输出 + * \param M 输入数据的长度 + * \param N 输出数据的长度 + * \return + */ +void IIR_I::resp(double data_in[], int M, double data_out[], int N) +{ + int i, k, il; + for(k = 0; k < N; k++) + { + data_out[k] = 0.0; + for(i = 0; i <= m_num_order; i++) + { + if( k - i >= 0) + { + il = ((k - i) < M) ? (k - i) : (M - 1); + data_out[k] = data_out[k] + m_pNum[i] * data_in[il]; + } + } + for(i = 1; i <= m_den_order; i++) + { + if( k - i >= 0) + { + data_out[k] = data_out[k] - m_pDen[i] * data_out[k - i]; + } + } + } +} + +/** \brief 滤波函数,采用直接I型结构 + * 注:该函数内部修改过,移植librosa.pcen时参照scipy.signal.lfilter所做的设计。 + * + * \param data_in[] 输入数据 + * \param data_out[] 保存滤波后的数据 + * \param len 数组的长度 + * \return + */ +void IIR_I::filter(double data_in[], double data_out[], int len) +{ + int i, k; + m_py[1] = 1; //修改的地方,因为公式中y[n-k],当为第一个元素时会出现y[-1],pcen中y[-1]会被认为为1。 + for(k = 0; k < len; k++) + { + m_px[0] = data_in[k]; + m_py[0] = 0.0; + for(i = 0; i <= m_num_order; i++) + { + m_py[0] = m_py[0] + m_pNum[i] * m_px[i]; + } + for(i = 1; i <= m_den_order; i++) + { + m_py[0] = m_py[0] - m_pDen[i] * m_py[i]; + } + for(i = m_num_order; i >= 1; i--) + { + m_px[i] = m_px[i-1]; + } + for(i = m_den_order; i >= 1; i--) + { + m_py[i] = m_py[i-1]; + } + data_out[k] = m_py[0]; + } +} + +#endif + +#ifdef UES_IIR_II + +/**< IIR 滤波器直接II型实现 */ +class IIR_II +{ +public: + IIR_II(); + void reset(); + void setPara(double num[], int num_order, double den[], int den_order); + void resp(double data_in[], int m, double data_out[], int n); + double filter(double data); + void filter(double data[], int len); + void filter(double data_in[], double data_out[], int len); +protected: +private: + double *m_pNum; + double *m_pDen; + double *m_pW; + int m_num_order; + int m_den_order; + int m_N; +}; + +class IIR_BODE +{ +private: + double *m_pNum; + double *m_pDen; + int m_num_order; + int m_den_order; + std::complex poly_val(double p[], int order, double omega); +public: + IIR_BODE(); + void setPara(double num[], int num_order, double den[], int den_order); + std::complex bode(double omega); + void bode(double omega[], int n, std::complex resp[]); +}; + +IIR_II::IIR_II() +{ +//ctor +m_pNum = NULL; +m_pDen = NULL; +m_pW = NULL; +m_num_order = -1; +m_den_order = -1; +m_N = 0; +}; + +/** \brief 将滤波器的内部状态清零,滤波器的系数保留 + * \return + */ +void IIR_II::reset() +{ + for(int i = 0; i < m_N; i++) + { + m_pW[i] = 0.0; + } +} +/** \brief + * + * \param num 分子多项式的系数,升序排列,num[0] 为常数项 + * \param m 分子多项式的阶数 + * \param den 分母多项式的系数,升序排列,den[0] 为常数项 + * \param m 分母多项式的阶数 + * \return + */ +void IIR_II::setPara(double num[], int num_order, double den[], int den_order) +{ + delete[] m_pNum; + delete[] m_pDen; + delete[] m_pW; + m_num_order = num_order; + m_den_order = den_order; + m_N = fmax(num_order, den_order) + 1; + m_pNum = new double[m_N]; + m_pDen = new double[m_N]; + m_pW = new double[m_N]; + for(int i = 0; i < m_N; i++) + { + m_pNum[i] = 0.0; + m_pDen[i] = 0.0; + m_pW[i] = 0.0; + } + for(int i = 0; i <= num_order; i++) + { + m_pNum[i] = num[i]; + } + for(int i = 0; i <= den_order; i++) + { + m_pDen[i] = den[i]; + } +} +/** \brief 计算 IIR 滤波器的时域响应,不影响滤波器的内部状态 + * \param data_in 为滤波器的输入,0 时刻之前的输入默认为 0,data_in[M] 及之后的输入默认为data_in[M-1] + * \param data_out 滤波器的输出 + * \param M 输入数据的长度 + * \param N 输出数据的长度 + * \return + */ +void IIR_II::resp(double data_in[], int M, double data_out[], int N) +{ + int i, k, il; + for(k = 0; k < N; k++) + { + data_out[k] = 0.0; + for(i = 0; i <= m_num_order; i++) + { + if( k - i >= 0) + { + il = ((k - i) < M) ? (k - i) : (M - 1); + data_out[k] = data_out[k] + m_pNum[i] * data_in[il]; + } + } + for(i = 1; i <= m_den_order; i++) + { + if( k - i >= 0) + { + data_out[k] = data_out[k] - m_pDen[i] * data_out[k - i]; + } + } + } +} +/** \brief 滤波函数,采用直接II型结构 + * + * \param data 输入数据 + * \return 滤波后的结果 + */ +double IIR_II::filter(double data) +{ + m_pW[0] = data; + for(int i = 1; i <= m_den_order; i++) // 先更新 w[n] 的状态 + { + m_pW[0] = m_pW[0] - m_pDen[i] * m_pW[i]; + } + data = 0.0; + for(int i = 0; i <= m_num_order; i++) + { + data = data + m_pNum[i] * m_pW[i]; + } + for(int i = m_N - 1; i >= 1; i--) + { + m_pW[i] = m_pW[i-1]; + } + return data; +} +/** \brief 滤波函数,采用直接II型结构 + * + * \param data[] 传入输入数据,返回时给出滤波后的结果 + * \param len data[] 数组的长度 + * \return + */ +void IIR_II::filter(double data[], int len) +{ + int i, k; + for(k = 0; k < len; k++) + { + m_pW[0] = data[k]; + for(i = 1; i <= m_den_order; i++) // 先更新 w[n] 的状态 + { + m_pW[0] = m_pW[0] - m_pDen[i] * m_pW[i]; + } + data[k] = 0.0; + for(i = 0; i <= m_num_order; i++) + { + data[k] = data[k] + m_pNum[i] * m_pW[i]; + } + + for(i = m_N - 1; i >= 1; i--) + { + m_pW[i] = m_pW[i-1]; + } + } +} +/** \brief 滤波函数,采用直接II型结构 + * + * \param data_in[] 输入数据 + * \param data_out[] 保存滤波后的数据 + * \param len 数组的长度 + * \return + */ +void IIR_II::filter(double data_in[], double data_out[], int len) +{ + int i, k; + for(k = 0; k < len; k++) + { + m_pW[0] = data_in[k]; + for(i = 1; i <= m_den_order; i++) // 先更新 w[n] 的状态 + { + m_pW[0] = m_pW[0] - m_pDen[i] * m_pW[i]; + } + data_out[k] = 0.0; + for(i = 0; i <= m_num_order; i++) + { + data_out[k] = data_out[k] + m_pNum[i] * m_pW[i]; + } + + for(i = m_N - 1; i >= 1; i--) + { + m_pW[i] = m_pW[i-1]; + } + } +} + +#endif + +#endif //SERVICESUPERVISOR_IIR_FILTER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/mfcc.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/mfcc.hpp new file mode 100644 index 0000000000000000000000000000000000000000..19b561946a3553b9a5398d67bf7ec379f308ba10 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/mfcc.hpp @@ -0,0 +1,441 @@ +#pragma once + +#include "AudioFFT.hpp" +//#include"../third/numcpp/NumCpp.hpp" +#include "opencv2/opencv.hpp" +#include "iir_filter.hpp" +#include "sas_util.h" + +int nSamplesPerSec = 16000; //采样率(每秒样本数) //Sample rate.(keda, thchs30, aishell) +int length_DFT = 1024;//2048; //傅里叶点数 //fft points (samples) +int hop_length = 160;//int(0.05 * nSamplesPerSec); //步长 //下一帧取数据相对于这一帧的右偏移量 +int win_length = 800;// int(0.1 * nSamplesPerSec); //帧长 //假设16000采样率,则取取0.1s时间的数据 +int number_filterbanks = 80; //过滤器数量 //Number of Mel banks to generate +float preemphasis = 0.97; //预加重(高通滤波器比例值) +int max_db = 100; +int ref_db = 20; +int r = 1; //librosa里的r=1,暂未深入分析其作用 +double pi = 3.14159265358979323846; + +cv::Mat_ mel_basis; +cv::Mat_ hannWindow; + +std::shared_ptr filter; + +//"""Convert Hz to Mels""" +double hz_to_mel(double frequencies, bool htk = false) { + if (htk) { + return 2595.0 * log10(1.0 + frequencies / 700.0); + } + // Fill in the linear part + double f_min = 0.0; + double f_sp = 200.0 / 3; + double mels = (frequencies - f_min) / f_sp; + // Fill in the log-scale part + double min_log_hz = 1000.0; // beginning of log region (Hz) + double min_log_mel = (min_log_hz - f_min) / f_sp; // same (Mels) + double logstep = log(6.4) / 27.0; // step size for log region + + // 对照Python平台的librosa库,移植 + //如果是多维数列 +// if (frequencies.ndim) { +// // If we have array data, vectorize +// log_t = (frequencies >= min_log_hz) +// mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep +// } else + if (frequencies >= min_log_hz) { + // If we have scalar data, heck directly + mels = min_log_mel + log(frequencies / min_log_hz) / logstep; + } + return mels; +} + +//"""Convert mel bin numbers to frequencies""" +cv::Mat_ mel_to_hz(cv::Mat_ mels, bool htk = false) { +// if (htk) { +// return //python://700.0 * (10.0**(mels / 2595.0) - 1.0); +// } + // Fill in the linear scale + double f_min = 0.0; + double f_sp = 200.0 / 3; + cv::Mat_ freqs = mels * f_sp + f_min; + // And now the nonlinear scale + double min_log_hz = 1000.0; // beginning of log region (Hz) + double min_log_mel = (min_log_hz - f_min) / f_sp; // same (Mels) + double logstep = log(6.4) / 27.0; // step size for log region + // 对照Python平台的librosa库,移植 + //if (mels.ndim) { + // If we have vector data, vectorize + cv::Mat_ log_t = (mels >= min_log_mel); + for (int i = 0; i < log_t.cols; i++) { + if (log_t(0, i)) { + freqs(0, i) = cv::exp((mels(0, i) - min_log_mel) * logstep) * min_log_hz; + } + } + //} + return freqs; +} + +// 生成等差数列,类似np.linspace +cv::Mat_ cvlinspace(double min_, double max_, int length) { + auto cvmat = cv::Mat_(1, length); + for (int i = 0; i < length; i++) { + cvmat(0, i) = ((max_ - min_) / (length - 1) * i) + min_; + } + return cvmat; +} + +//"""Create a Filterbank matrix to combine FFT bins into Mel-frequency bins""" +cv::Mat_ mel_spectrogram_create(int nps, int n_fft, int n_mels) { + double f_max = nps / 2.0; + double f_min = 0; + int n_fft_2 = 1 + n_fft / 2; + // Initialize the weights + //auto weights = nc::zeros(nc::uint32(n_mels), nc::uint32(n_fft_2)); + auto weights = cv::Mat_(n_mels, n_fft_2, 0.0); + // Center freqs of each FFT bin + //auto fftfreqs_ = nc::linspace(f_min, f_max, nc::uint32(n_fft_2), true); + auto fftfreqs = cvlinspace(f_min, f_max, n_fft_2); + + // 'Center freqs' of mel bands - uniformly spaced between limits + double min_mel = hz_to_mel(f_min, false); + double max_mel = hz_to_mel(f_max, false); + //auto mels_ = nc::linspace(min_mel, max_mel, nc::uint32(n_mels + 2)); + auto mels = cvlinspace(min_mel, max_mel, n_mels + 2); + auto mel_f = mel_to_hz(mels, false); + + //auto fdiff_ = nc::diff(mel_f_); //沿着指定轴计算第N维的离散差值(后一个元素减去前一个元素) + cv::Mat_ d1(1, mel_f.cols * mel_f.rows - 1, (double *) (mel_f.data) + 1); + cv::Mat_ d2(1, mel_f.cols * mel_f.rows - 1, (double *) (mel_f.data)); + cv::Mat_ fdiff = d1 - d2; + + //auto ramps = nc::subtract.outer(mel_f, fftfreqs); //nc没有subtract.outer + //nc::NdArray ramps = nc::zeros(mel_f.cols, fftfreqs.cols); + auto ramps = cv::Mat_(mel_f.cols, fftfreqs.cols); + for (int i = 0; i < mel_f.cols; i++) { + for (int j = 0; j < fftfreqs.cols; j++) { + ramps(i, j) = mel_f(0, i) - fftfreqs(0, j); + } + } + + for (int i = 0; i < n_mels; i++) { + // lower and upper slopes for all bins + //auto ramps_1 = nc::NdArray(1, ramps.cols); + auto ramps_1 = cv::Mat_(1, ramps.cols); + for (int j = 0; j < ramps.cols; j++) { + ramps_1(0, j) = ramps(i, j); + } + //auto ramps_2 = nc::NdArray(1, ramps.cols); + auto ramps_2 = cv::Mat_(1, ramps.cols); + for (int j = 0; j < ramps.cols; j++) { + ramps_2(0, j) = ramps(i + 2, j); + } + cv::Mat_ lower = ramps_1 * -1 / fdiff(0, i); + cv::Mat_ upper = ramps_2 / fdiff(0, i + 1); + // .. then intersect them with each other and zero + //auto weights_1 = nc::maximum(nc::zeros(1, ramps.cols), nc::minimum(lower, upper)); + cv::Mat c1 = lower;//(cv::Mat_(1,5) << 1,2,-3,4,-5); + cv::Mat c2 = upper; + cv::Mat weights_1 = cv::Mat_(1, lower.cols); + cv::min(c1, c2, weights_1); + cv::max(weights_1, 0, weights_1); + for (int j = 0; j < n_fft_2; j++) { + weights(i, j) = weights_1.at(0, j); + } + } + + // Slaney-style mel is scaled to be approx constant energy per channel + auto enorm = cv::Mat_(1, n_mels); + for (int j = 0; j < n_mels; j++) { + enorm(0, j) = 2.0 / (mel_f(0, j + 2) - mel_f(0, j)); + } + for (int j = 0; j < n_mels; j++) { + for (int k = 0; k < n_fft_2; k++) { + weights(j, k) *= enorm(0, j); + } + } + return weights; +} + +//"""Short-time Fourier transform (STFT)""": 默认center=True, window='hann', pad_mode='reflect' +cv::Mat_ MagnitudeSpectrogram(const cv::Mat_ *emphasis_data, int n_fft = 2048, int hop_length = 0, + int win_length = 0) { + if (win_length == 0) { + win_length = n_fft; + } + if (hop_length == 0) { + hop_length = win_length / 4; + } + + // reflect对称填充 + int pad_lenght = n_fft / 2; + // 使用opencv里的copyMakeBorder来完成reflect填充 + cv::Mat_ cv_padbuffer; + cv::copyMakeBorder(*emphasis_data, cv_padbuffer, 0, 0, pad_lenght, pad_lenght, cv::BORDER_REFLECT_101); + + // windowing加窗:将每一帧乘以汉宁窗,以增加帧左端和右端的连续性。 + // 生成一个1600长度的hannWindow,并居中到2048长度的 + if (hannWindow.empty()) { + hannWindow = cv::Mat_(1, n_fft, 0.0f); + int insert_cnt = 0; + if (n_fft > win_length) { + insert_cnt = (n_fft - win_length) / 2; + } else { + //std::cout << "\tn_fft:" << n_fft << " > win_length:" << n_fft << std::endl; + return cv::Mat_(0, 0); + } + for (int k = 1; k <= win_length; k++) { + hannWindow(0, k - 1 + insert_cnt) = float(0.5 * (1 - cos(2 * pi * k / (win_length + 1)))); + } + } + // opencv虽然有Hann窗生成函数,但是必须要求width > 1,height > 1 + //cv::Mat_ cv_hannWindow; + //cv::createHanningWindow(cv_hannWindow, cv::Size(1, win_length), CV_64FC1); + + int size = cv_padbuffer.rows * cv_padbuffer.cols;//padbuffer.size() + int number_feature_vectors = (size - n_fft) / hop_length + 1; + int number_coefficients = n_fft / 2 + 1; + cv::Mat_ feature_vector(number_feature_vectors, number_coefficients, 0.0f); + + audiofft::AudioFFT fft; //将FFT初始化放在循环外,可达到最优速度 + fft.init(size_t(n_fft)); + for (int i = 0; i <= size - n_fft; i += hop_length) { + // 每次取一段数据 + cv::Mat_ framef = cv::Mat_(1, n_fft, (float *) (cv_padbuffer.data) + i).clone(); + // 加hann窗 + framef = framef.mul(hannWindow); + + // 复数:Xrf实数,Xif虚数。 + cv::Mat_ Xrf(1, number_coefficients); + cv::Mat_ Xif(1, number_coefficients); + fft.fft((float *) (framef.data), (float *) (Xrf.data), (float *) (Xif.data)); + + // 求模 + cv::pow(Xrf, 2, Xrf); + cv::pow(Xif, 2, Xif); + cv::Mat_ cv_feature(1, number_coefficients, &(feature_vector[i / hop_length][0])); + cv::sqrt(Xrf + Xif, cv_feature); + } + cv::Mat_ cv_mag; + cv::transpose(feature_vector, cv_mag); + cv::Mat_ mag; + cv_mag.convertTo(mag, CV_64FC1); + + return mag; +} + +/********************************************* + * 名称:log_mel + * 功能:传入音频数据,输出log-mel方式提取的特征数据。 + * 参数:@ifile_data 传入的音频数据 + * @nSamples_per_sec 音频采样率 + * 返回:cv::Mat_ 特征数据 +*********************************************/ +//cv::Mat_ log_mel(std::vector &ifile_data, int nSamples_per_sec) { +int log_mel(float* ifile_data, int ifile_length,int nSamples_per_sec,float* ofile_data) { + if (nSamples_per_sec != nSamplesPerSec) { + //std::cout << R"(the "nSamples_per_sec" is not 16000.)" << std::endl; + return -1;//cv::Mat_(0, 0); + } + //int ifile_length = int(ifile_data.size() / 4); + + // pre-emphasis 预加重 //高通滤波 + //cv::Mat_ d1(1, ifile_length - 1, (float *) (ifile_data.data()) + 1); + //cv::Mat_ d2(1, ifile_length-1 , (float *) (ifile_data.data())); + cv::Mat_ d1(1, ifile_length - 1, (float *) (ifile_data) + 1); + cv::Mat_ d2(1, ifile_length-1 , (float *) (ifile_data)); + + //std::cout< cv_emphasis_data; + + cv::hconcat(cv::Mat_::zeros(1, 1), d1 - d2 * preemphasis, cv_emphasis_data); + //cv::print(cv_emphasis_data); + //std::cout< cvlfilter_zi(cv::Mat_ b, cv::Mat_ a) { + if ((b.rows != 1) || (a.rows != 1)) { + //std::cout << "Numerator b and Denominator a must be 1-D." << std::endl; + } + if (a(0, 0) != 1) { + // Normalize the coefficients so a[0] == 1. + b = b / a(0, 0); + a = a / a(0, 0); + } + int len_a = a.cols * a.rows; + int len_b = b.cols * b.rows; + int n = len_a > len_b ? len_a : len_b; + if (len_a < n) { + cv::hconcat(a, cv::Mat_::zeros(1, n - len_a), a); + } else if (len_b < n) { + cv::hconcat(b, cv::Mat_::zeros(1, n - len_b), b); + } + return cv::Mat_(0, 0); +} +/* +// scipy.signal.lfilter() +// Filter data along one-dimension with an IIR or FIR filter. +cv::Mat_ cvlfilter(cv::Mat_ &b, cv::Mat_ &a, cv::Mat_ &x, + cv::Mat_ &zi, int axis = -1) { + if (a.rows * a.cols == 1) { + // This path only supports types fdgFDGO to mirror _linear_filter below. + // Any of b, a, x, or zi can set the dtype, but there is no default + // casting of other types; instead a NotImplementedError is raised. + // 后续如果需要,则进行补充 + } else { + // return sigtools._linear_filter(b, a, x, axis, zi) + // sigtools._linear_filter() + // (y,Vf) = _linear_filter(b,a,X,Dim=-1,Vi=None) implemented using Direct Form II transposed flow diagram. + // If Vi is not given, Vf is not returned. + ; + } +} +*/ +/********************************************* + * 名称:pcen + * 功能:传入音频数据,输出pcen方式提取的特征数据。 + * 参数:@ifile_data 传入的音频数据 + * @nSamples_per_sec 音频采样率 + * 返回:cv::Mat_ 特征数据 +*********************************************/ +cv::Mat_ pcen(std::vector &ifile_data, int nSamples_per_sec) { + //if (!(&ifile_data) || ifile_data.empty()) { + if (ifile_data.empty()) { + //std::cout << "error: invalid paramter: ifile_data" << std::endl; + return cv::Mat_(0, 0); + } + if (nSamples_per_sec != nSamplesPerSec) { +// std::cout << R"(error: the "nSamples_per_sec" is not 16000.)" << std::endl; + return cv::Mat_(0, 0); + } + int ifile_length = int(ifile_data.size() / 4); + cv::Mat_ cv_emphasis_data(1, ifile_length, (float *) (ifile_data.data())); +// std::cout< mel = mel_basis * mag; + + // 计算pcen特征 +// double time_constant = 0.400; +// int sr = 22050; +// int hop_length = 512; +// double t_frames = time_constant * sr / double(hop_length); +// double b = (sqrt(1 + 4 * t_frames * t_frames) - 1) / (2 * t_frames * t_frames); +// cv::Mat_ zi = (cv::Mat_(1, 1) << 0.94361056); +// +// cv::Mat_ in_b = (cv::Mat_(1, 1) << b); +// cv::Mat_ in_a = (cv::Mat_(1, 2) << 1, b - 1); +// cv::Mat_ zi = cvlfilter_zi(in_b, in_a); + // 第二个公式计算 +// cv::Mat_ S_smooth = cvlfilter(in_b, in_a, mel, zi); + +#if 1 // IIR滤波器 + if (!filter) { + filter = std::make_shared(); + double iir_b[1] = {0.05638943879134889}; + double iir_a[2] = {1.0, -0.9436105612086512}; + //filter.reset(); + filter->setPara(iir_b, 1, iir_a, 2); + } + cv::Mat_ S_smooth = cv::Mat_(mel.rows, mel.cols); + for (int i = 0; i < mel.rows; i++) { + filter->filter(mel[i], S_smooth[i], mel.cols); + } + +#endif + + // 第一个公式计算 + double gain = 0.98; + double bias = 2.0; + double power = 0.5; + double eps = 1e-6; + //python: smooth = np.exp(-gain * (np.log(eps) + np.log1p(S_smooth / eps))) + cv::Mat_ S_smooth_log1p; + cv::log(S_smooth / eps + 1, S_smooth_log1p); + cv::Mat_ smooth; + cv::exp((S_smooth_log1p + cv::log(eps)) * (-gain), smooth); + //python: S_out = (bias ** power) * np.expm1(power * np.log1p(ref * smooth / bias)) + cv::Mat_ smooth_log1p; + cv::Mat_ smooth_log1p_exp; + cv::log(mel.mul(smooth) / bias + 1, smooth_log1p); + cv::exp(power * smooth_log1p, smooth_log1p_exp); + cv::Mat_ S_out = (smooth_log1p_exp - 1) * pow(bias, power); + // transpose + cv::Mat_ pcen; + cv::transpose(S_out, pcen); + + return pcen; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/sas_util.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/sas_util.h new file mode 100644 index 0000000000000000000000000000000000000000..4fa5692813ac0861b0cd3804ee4fff1c72bcf9e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/mfcc/sas_util.h @@ -0,0 +1,123 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include "opencv2/opencv.hpp" + +using namespace std; +using namespace std::chrono; + +class parambase +{ +public: + string name; + string help; + string strval; + parambase(){} + virtual ~parambase(){} + virtual bool set(const char* value) {return true;}; +}; + +/** + * + */ +class EnginePar +{ +public: + static int cs_timeout; //кŷɵijʱʱ(ĬһνкŴһ,Ĭֵ5) + static int cs_detecthandsup_time; //кźֵʱ(Ĭ10s) + static int cs_detecthandsup_interval ; //кźֵʱ(Ĭ11) + static int cs_detectsmile_interval; //кź΢Цʱ(Ĭ11) + static int cs_detectspeech_interval;//кźʱ(Ĭ20) + static int cs_detectpose_interval; //кź̬ʱ(Ĭ51) + static int detectpose_interval; //ǽкڼ̬ʱ(Ĭ51) + static int detectsmile_interval; //ǽкڼ΢Цʱ(Ĭ11) + static int detectappearance_interval; //װ + static float action_turnpen_thrd; //תֵ + static float action_turnchair_thrd; //תֵ + static float action_record_time; //¼ʱ + static float sit_supporthead_thrd; //ͷֵ + static float sit_layondesk_thrd; //ſֵ + static float sit_relyingonchair_thrd;//ֵ + static string log_path; + static string log_level; + static string temp_path; + static bool set(const char* key, const char* val); + static bool haskey(const char* key); + static const char* getvalue(const char* key); +}; +/** + * ͷ + */ +enum VideoScene +{ + SCENE_counter, // ̨ + SCENE_financial, // + SCENE_lobby, // + SCENE_hall // +}; +/** + * ͷ + */ +class VideoPar +{ +private: + vector> params; +public: + VideoScene scene; //: 1̨, 2, 3, 4(װ) + bool audio_enable ; //Ƶ 1,0 + int audio_channels ; //Ƶͨ 0,1,2,4,6 + int audio_sample_rate ; // 44100, 48000, 96000, 192000 + bool video_enable ; // Ƶ 1,0 + //int video_analyse_rate ; //Ƶ: >0,ÿ֡ + bool video_sample_keyframe; //ֻؼ֡ + bool video_record; //¼Ƶ 1,0 + int video_record_duration; //Ƶ¼ʱ,Ĭ10s + int video_record_reviewtime; //Ƶ¼ƻʱ,Ĭ5s + int face_minsize; //СС + VideoPar(); + //~VideoPar(); + bool set(const char* key, const char* val); + static bool haskey(const char* key); +}; + +template +inline int64_t NowTime() +{ + return std::chrono::time_point_cast(std::chrono::system_clock::now()).time_since_epoch().count(); +} + +/**--------------------------------- modelsģõķ ---------------------------------**/ + +inline bool detectFileExist(char *file_path) { + std::ifstream _ifstream; + _ifstream.open(file_path, std::ios::in); + if (!_ifstream) { + return false; + } + _ifstream.close(); + return true; +} + +// 任xyת +inline cv::Mat_ rotate_point(cv::Mat_ xy, double angle) { + cv::Mat rotate_matrix = (cv::Mat_(2, 2) << cos(angle), -sin(angle), sin(angle), cos(angle)); + cv::transpose(rotate_matrix, rotate_matrix); + auto rotate_xy = xy * rotate_matrix; + return rotate_xy; +} + +// Ƿڿ +inline bool check_point_in_rect(cv::Point point, cv::Rect rect) { + if ((rect.x < point.x && point.x < rect.x + rect.width) && + (rect.y < point.y && point.y < rect.y + rect.height)) { + return true;//rectڲ + } else { + return false;//rectϻⲿ + } +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0ef97dc46bddb11a089d45646ab259896e33928 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.cpp @@ -0,0 +1,332 @@ +#include "munet.h" +#include "cpu.h" +#include "face_utils.h" +#include "blendgram.h" + +Mobunet::Mobunet(const char* fnbin,const char* fnparam,const char* fnmsk){ + initModel(fnbin,fnparam,fnmsk); +} + +Mobunet::Mobunet(const char* modeldir,const char* modelid){ + char fnbin[1024]; + char fnparam[1024]; + char fnmsk[1024]; + sprintf(fnbin,"%s/%s.bin",modeldir,modelid); + sprintf(fnparam,"%s/%s.param",modeldir,modelid); + sprintf(fnmsk,"%s/weight_168u.bin",modeldir); + initModel(fnbin,fnparam,fnmsk); +} + +int Mobunet::initModel(const char* binfn,const char* paramfn,const char* mskfn){ + unet.clear(); + //ncnn::set_cpu_powersave(2); + //ncnn::set_omp_num_threads(ncnn::get_big_cpu_count()); + //unet.opt = ncnn::Option(); + //unet.opt.use_vulkan_compute = true; + unet.opt.num_threads = ncnn::get_big_cpu_count(); + //unet.load_param("model/mobileunet_v5_wenet_sim.param"); + //unet.load_model("model/mobileunet_v5_wenet_sim.bin"); + unet.load_param(paramfn); + unet.load_model(binfn); + char* wbuf = NULL; + dumpfile((char*)mskfn,&wbuf); + mat_weights = new JMat(160,160,(uint8_t*)wbuf,1); + mat_weights->forceref(0); + //mat_weights->show("weight"); + //cv::waitKey(0); + return 0; +} + +Mobunet::~Mobunet(){ + unet.clear(); + if(mat_weights){ + delete mat_weights; + mat_weights = nullptr; + } +} + +int Mobunet::domodelold(JMat* pic,JMat* msk,JMat* feat){ + JMat picall(160*160,2,3,0,1); + uint8_t* buf = picall.udata(); + int width = pic->width(); + int height = pic->height(); + cv::Mat c1(height,width,CV_8UC3,buf); + cv::Mat c2(height,width,CV_8UC3,buf+width*height*3); + cv::cvtColor(pic->cvmat(),c1,cv::COLOR_RGB2BGR); + cv::cvtColor(msk->cvmat(),c2,cv::COLOR_RGB2BGR); + ncnn::Mat inall = ncnn::Mat::from_pixels(buf, ncnn::Mat::PIXEL_BGR, 160*160, 2); + inall.substract_mean_normalize(mean_vals, norm_vals); + //inall.reshape(160,160,6); + ncnn::Mat inwenet(256,20,1,feat->data()); + ncnn::Mat outpic; + ncnn::Extractor ex = unet.create_extractor(); + ex.input("face", inall); + ex.input("audio", inwenet); + ex.extract("output", outpic); + float outmean_vals[3] = {-1.0f, -1.0f, -1.0f}; + float outnorm_vals[3] = { 0.5f, 0.5f, 0.5f}; + outpic.substract_mean_normalize(outmean_vals, outnorm_vals); + ncnn::Mat pakpic; + ncnn::convert_packing(outpic,pakpic,3); + cv::Mat cvadj(160,160,CV_32FC3,pakpic.data); + //dumpfloat((float*)cvadj.data,160*160*3); + cv::Mat cvreal; + float scale = 255.0f; + cvadj.convertTo(cvreal,CV_8UC3,scale); + cv::Mat cvmask; + cv::cvtColor(cvreal,cvmask,cv::COLOR_RGB2BGR); + cv::imshow("cvreal",cvreal); + cv::imshow("cvmask",cvmask); + //cv::waitKey(0); + //getchar(); + BlendGramAlpha((uchar*)cvmask.data,(uchar*)mat_weights->data(),(uchar*)pic->data(),160,160); + return 0; +} + +int Mobunet::domodel(JMat* pic,JMat* msk,JMat* feat){ + //convert to bgr + //pic->tojpg("eee.bmp"); + + //JMat picmask(160,160,3,0,1); + //JMat picreal(160,160,3,0,1); + //cv::cvtColor(pic->cvmat(),picreal.cvmat(),cv::COLOR_RGB2BGR); + //cv::cvtColor(msk->cvmat(),picmask.cvmat(),cv::COLOR_RGB2BGR); + ncnn::Mat inmask = ncnn::Mat::from_pixels(msk->udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inmask.substract_mean_normalize(mean_vals, norm_vals); + ncnn::Mat inreal = ncnn::Mat::from_pixels(pic->udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inreal.substract_mean_normalize(mean_vals, norm_vals); + // + //JMat picin(160*160,6); + //char* pd = (char*)picin.data(); + //memcpy(pd,inreal.data,160*160*3*4); + //memcpy(pd+ 160*160*3*4,inmask.data,160*160*3*4); + // + //ncnn::Mat inpack(160,160,1,pd,(size_t)4u*6,6); + //ncnn::Mat inpic; + //ncnn::convert_packing(inpack,inpic,1); + ncnn::Mat inpic(160,160,6); + //printf("===in %d %d all %d %d\n",inreal.cstep,inreal.elempack,inpic.cstep,inpic.elempack); + float* buf = (float*)inpic.data; + float* pr = (float*)inreal.data; + //printf("==%d==%f\n",pic->udata()[2],*pr); + memcpy(buf,pr,inreal.cstep*sizeof(float)*inreal.c); + /* + for(int k=0;k<3;k++){ + memcpy(buf,pr,inreal.cstep*sizeof(float)); + buf += inpic.cstep; + pr += inreal.cstep; + } + */ + buf+= inpic.cstep*inreal.c; + float* pm = (float*)inmask.data; + //printf("=%d===%f\n",msk->udata()[2],*pm); + memcpy(buf,pm,inmask.cstep*sizeof(float)*inmask.c); + /* + for(int k=0;k<3;k++){ + memcpy(buf,pm,inreal.cstep*sizeof(float)); + buf += inpic.cstep; + pm += inmask.cstep; + } + */ + + ncnn::Mat inwenet(256,20,1,feat->data()); + //ncnn::Mat inwenet(20,256,1,feat->data()); + ncnn::Mat outpic; + ncnn::Extractor ex = unet.create_extractor(); + ex.input("face", inpic); + ex.input("audio", inwenet); + ex.extract("output", outpic); + float outmean_vals[3] = {-1.0f, -1.0f, -1.0f}; + float outnorm_vals[3] = { 127.5f, 127.5f, 127.5f}; + outpic.substract_mean_normalize(outmean_vals, outnorm_vals); + cv::Mat cvout(160,160,CV_8UC3); + outpic.to_pixels(cvout.data,ncnn::Mat::PIXEL_RGB2BGR); + BlendGramAlpha((uchar*)cvout.data,(uchar*)mat_weights->data(),(uchar*)pic->data(),160,160); + //pic->tojpg("fff.bmp"); + //getchar(); + /* + ncnn::Mat pakpic; + ncnn::convert_packing(outpic,pakpic,3); + cv::Mat cvadj(160,160,CV_32FC3,pakpic.data); + //dumpfloat((float*)cvadj.data,160*160*3); + float scale = 255.0f; + cvadj.convertTo(picreal.cvmat(),CV_8UC3,scale); + cv::cvtColor(picreal.cvmat(),picmask.cvmat(),cv::COLOR_RGB2BGR); + */ + //getchar(); + //getchar(); + //cv::Mat cout; + //cv::cvtColor(picreal.cvmat(),cout,cv::COLOR_RGB2BGR); + //BlendGramAlpha((uchar*)cout.data,(uchar*)mat_weights->data(),(uchar*)pic->data(),160,160); + + /* + float outmean_vals[3] = {-1.0f, -1.0f, -1.0f}; +// float outnorm_vals[3] = { 2.0f, 2.0f, 2.0f}; + float outnorm_vals[3] = { 127.5f, 127.5f, 127.5f}; + outpic.substract_mean_normalize(outmean_vals, outnorm_vals); + + ncnn::Mat pakpic; + ncnn::convert_packing(outpic,pakpic,3); + // + cv::Mat cvadj(160,160,CV_32FC3,pakpic.data); + // + float scale = 1.0f; + cvadj.convertTo(picreal.cvmat(),CV_8UC3,scale); + cv::Mat cout; + cv::cvtColor(picreal.cvmat(),cout,cv::COLOR_RGB2BGR); + BlendGramAlpha((uchar*)cout.data,(uchar*)mat_weights->data(),(uchar*)pic->data(),160,160); + //BlendGramAlpha((uchar*)picreal.udata(),(uchar*)mat_weights->data(),(uchar*)pic->data(),160,160); + //cv::cvtColor(picreal.cvmat(),pic->cvmat(),cv::COLOR_RGB2BGR); + */ + return 0; +} + + +int Mobunet::preprocess(JMat* pic,JMat* feat){ + //pic 168 + cv::Mat roipic(pic->cvmat(),cv::Rect(4,4,160,160)); + JMat picmask(160,160,3,0,1); + JMat picreal(160,160,3,0,1); + cv::Mat cvmask = picmask.cvmat(); + cv::Mat cvreal = picreal.cvmat(); + roipic.copyTo(cvmask); + roipic.copyTo(cvreal); + cv::rectangle(cvmask,cv::Rect(5,5,150,145),cv::Scalar(0,0,0),-1);//,cv::LineTypes::FILLED); + domodel(&picreal,&picmask,feat); + cvreal.copyTo(roipic); + return 0; +} + +int Mobunet::fgprocess(JMat* pic,const int* boxs,JMat* feat,JMat* fg){ + int boxx, boxy ,boxwidth, boxheight ; + boxx = boxs[0];boxy=boxs[1];boxwidth=boxs[2]-boxx;boxheight=boxs[3]-boxy; + int stride = pic->stride(); + cv::Mat roisrc(pic->cvmat(),cv::Rect(boxx,boxy,boxwidth,boxheight)); + cv::Mat cvorig; + cv::resize(roisrc , cvorig, cv::Size(168, 168), cv::INTER_AREA); + JMat pic168(168,168,(uint8_t*)cvorig.data); + preprocess(&pic168,feat); + cv::Mat cvrst;; + cv::resize(cvorig , cvrst, cv::Size(boxwidth, boxheight), cv::INTER_AREA); + cv::Mat roidst(fg->cvmat(),cv::Rect(boxx,boxy,boxwidth,boxheight)); + cvrst.copyTo(roidst); + return 0; +} + +int Mobunet::process(JMat* pic,const int* boxs,JMat* feat){ + int boxx, boxy ,boxwidth, boxheight ; + boxx = boxs[0];boxy=boxs[1];boxwidth=boxs[2]-boxx;boxheight=boxs[3]-boxy; + int stride = pic->stride(); + cv::Mat roisrc(pic->cvmat(),cv::Rect(boxx,boxy,boxwidth,boxheight)); + cv::Mat cvorig; + cv::resize(roisrc , cvorig, cv::Size(168, 168), cv::INTER_AREA); + JMat pic168(168,168,(uint8_t*)cvorig.data); + preprocess(&pic168,feat); + cv::Mat cvrst;; + cv::resize(cvorig , cvrst, cv::Size(boxwidth, boxheight), cv::INTER_AREA); + cvrst.copyTo(roisrc); + return 0; +} + +int Mobunet::process2(JMat* pic,const int* boxs,JMat* feat){ + int boxx, boxy ,boxwidth, boxheight ; + boxx = boxs[0];boxy=boxs[1];boxwidth=boxs[2]-boxx;boxheight=boxs[3]-boxy; + int stride = pic->stride(); + + cv::Mat cvsrc = pic->cvmat(); + printf("cvsrc %d %d \n",cvsrc.cols,cvsrc.rows); + cv::Mat roisrc(cvsrc,cv::Rect(boxx,boxy,boxwidth,boxheight)); + cv::Mat cvorig; + cv::resize(roisrc , cvorig, cv::Size(168, 168), cv::INTER_AREA); + /* + uint8_t* data =(uint8_t*)pic->data() + boxy*stride + boxx*pic->channel(); + int scale_w = 168; + int scale_h = 168; + ncnn::Mat prepic = ncnn::Mat::from_pixels_resize(data, ncnn::Mat::PIXEL_BGR, boxwidth, boxheight, stride,scale_w, scale_h); + //pic 168 + cv::Mat cvorig(168,168,CV_8UC3,prepic.data); + */ + + cv::Mat roimask(cvorig,cv::Rect(4,4,160,160)); + JMat picmask(160,160,3,0,1); + JMat picreal(160,160,3,0,1); + cv::Mat cvmask = picmask.cvmat(); + cv::Mat cvreal = picreal.cvmat(); + roimask.copyTo(cvmask); + roimask.copyTo(cvreal); + + cv::rectangle(cvmask,cv::Rect(5,5,150,150),cv::Scalar(0,0,0),-1);//,cv::LineTypes::FILLED); +// cv::imshow("000",cvorig); +// cv::imshow("aaa",cvmask); +// cv::imshow("bbb",cvreal); +// cv::waitKey(0); + + ncnn::Mat inmask = ncnn::Mat::from_pixels(picmask.udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inmask.substract_mean_normalize(mean_vals, norm_vals); + ncnn::Mat inreal = ncnn::Mat::from_pixels(picreal.udata(), ncnn::Mat::PIXEL_BGR2RGB, 160, 160); + inreal.substract_mean_normalize(mean_vals, norm_vals); + + JMat picin(160*160,2,3); + char* pd = (char*)picin.data(); + memcpy(pd,inreal.data,160*160*3*4); + memcpy(pd+ 160*160*3*4,inmask.data,160*160*3*4); + +// char* pinpic = NULL; +// dumpfile("pic.bin",&pinpic); +// dumpfloat((float*)pd,10); +// dumpfloat((float*)pinpic,10); + //ncnn::Mat inpic(160,160,6,pd,4); + ncnn::Mat inpack(160,160,1,pd,(size_t)4u*6,6); + ncnn::Mat inpic; + ncnn::convert_packing(inpack,inpic,1); + +// char* pwenet = NULL; +// dumpfile("wenet.bin",&pwenet); + ncnn::Mat inwenet(256,20,1,feat->data(),4); + ncnn::Mat outpic; + ncnn::Extractor ex = unet.create_extractor(); + ex.input("face", inpic); + ex.input("audio", inwenet); + ex.extract("output", outpic); + + float outmean_vals[3] = {-1.0f, -1.0f, -1.0f}; +// float outnorm_vals[3] = { 2.0f, 2.0f, 2.0f}; + float outnorm_vals[3] = { 127.5f, 127.5f, 127.5f}; + outpic.substract_mean_normalize(outmean_vals, outnorm_vals); + + ncnn::Mat pakpic; + ncnn::convert_packing(outpic,pakpic,3); + + cv::Mat cvadj(160,160,CV_32FC3,pakpic.data); + cv::Mat cvout(160,160,CV_8UC3); + float scale = 1.0f; + cvadj.convertTo(cvout,CV_8UC3,scale); + //cv::imwrite("cvout.jpg",cvout); + cv::cvtColor(cvout,roimask,cv::COLOR_RGB2BGR); +// cvout.copyTo(roimask); + + //cv::imwrite("roimask.jpg",roimask); + //cv::imwrite("cvorig.jpg",cvorig); + //cv::waitKey(0); + cv::resize(cvorig , roisrc, cv::Size(boxwidth, boxheight), cv::INTER_AREA); + //cv::imwrite("roisrc.jpg",roisrc); + //cv::imshow("cvsrc",cvsrc); +// cv::imshow("roisrc",roisrc); +// cv::imshow("cvorig",cvorig); +// cv::waitKey(20); + /* + { + uint8_t *pr = (uint8_t *) cvoutc.data; + printf("==%u %u %u\n", pr[0], pr[1], pr[2]); + } + // + float* p = (float*)cvadj.data; + printf("==%f %f %f\n",p[0],p[1],p[2]); + p+=160*160; + printf("==%f %f %f\n",p[0],p[1],p[2]); + p+=160*160; + printf("==%f %f %f\n",p[0],p[1],p[2]); + */ + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.h new file mode 100644 index 0000000000000000000000000000000000000000..4f35d76063eb248495a325303e4c4e8e18c7e2b6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/munet.h @@ -0,0 +1,28 @@ +#pragma once +#include "jmat.h" +#include "net.h" +#include +#include +#include +#include +#include + + +class Mobunet{ + private: + ncnn::Net unet; + float mean_vals[3] = {127.5f, 127.5f, 127.5f}; + float norm_vals[3] = {1 / 127.5f, 1 / 127.5f, 1 / 127.5f}; + JMat* mat_weights = nullptr; + int initModel(const char* binfn,const char* paramfn,const char* mskfn); + public: + int domodel(JMat* pic,JMat* msk,JMat* feat); + int domodelold(JMat* pic,JMat* msk,JMat* feat); + int preprocess(JMat* pic,JMat* feat); + int process(JMat* pic,const int* boxs,JMat* feat); + int fgprocess(JMat* pic,const int* boxs,JMat* feat,JMat* fg); + int process2(JMat* pic,const int* boxs,JMat* feat); + Mobunet(const char* modeldir,const char* modelid); + Mobunet(const char* fnbin,const char* fnparam,const char* fnmsk); + ~Mobunet(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3613aad8ec7e2dbfda8a8f79fc6546aaf8f17943 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.cpp @@ -0,0 +1,272 @@ +#include "netwav.h" +#include "face_utils.h" +#include "jlog.h" +#include "wavreader.h" + + + +int KWav::initbuf(int pcmsample){ + m_pcmsample = pcmsample; + m_wavsample = pcmsample + 2*MFCC_OFFSET; + + m_seca = m_wavsample / MFCC_WAVCHUNK; + m_secb = m_wavsample % MFCC_WAVCHUNK; + + m_mellast = m_secb?(m_secb /160 +1):0; + m_bnflast = m_secb?((m_mellast*0.25f)-0.75f):0; + + m_wavsize = m_seca*MFCC_WAVCHUNK + m_secb; + + m_melsize = m_seca*MFCC_MELBASE+m_mellast; + m_bnfsize = m_seca*MFCC_BNFBASE+m_bnflast; + + //m_calcsize = m_seca+m_secb?1:0; + m_calcsize = m_seca+(m_secb?1:0); + + m_wavmat = new JMat(MFCC_WAVCHUNK,m_calcsize,1); + m_wavmat->zeros(); + m_melmat = new JMat(MFCC_MELCHUNK*MFCC_MELBASE,m_calcsize,1); + m_melmat->zeros(); + //m_bnfmat = new JMat(MFCC_BNFCHUNK*MFCC_BNFBASE,m_calcsize,1); + //m_bnfmat->zeros(); + m_bnfblock = m_duration*MFCC_FPS; + if(m_bnfblock>(m_bnfsize-10))m_bnfblock = m_bnfsize-10; + LOGD("==seca %d secb %d\n",m_seca,m_secb); + LOGD("==melsize %d bnfsize %d\n",m_melsize,m_bnfsize); + + return 0; +} + +int KWav::initinx(){ + m_curwav = m_wavmat->fdata() + MFCC_OFFSET; + m_leftsample = m_pcmsample; + m_waitsample = MFCC_OFFSET; + + /* + int* arr = m_bnfmat->tagarr(); + arr[0] = m_pcmsample*2; + arr[1] = m_pcmsample; + arr[2] = m_seca; + arr[3] = m_secb; + arr[4] = m_melsize; + arr[5] = m_bnfsize; + */ + float secs = m_pcmsample*1.0f/ MFCC_RATE; + int bnfblock = secs*MFCC_FPS; + if(bnfblock>(m_bnfsize-10))bnfblock = m_bnfsize-10; + //arr[6] = bnfblock;//m_bnfblock; + // + //LOGD("my==bnfblock %d arr6 %d",bnfblock,arr[6]); + //LOGD("myarr %d %d %d %d %d %d %d",arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6]); + return 0; +} + +int KWav::incsample(int sample){ + if(sample<1)return 0; + m_leftsample -= sample; + m_waitsample += sample; + //LOGD("===incsample %d left %d wait %d\n",sample,m_leftsample,m_waitsample); + while(m_waitsample>MFCC_WAVCHUNK){ + m_waitsample -= MFCC_WAVCHUNK; + m_waitcnt += 1; + LOGD("===tooken calc %d waitcnt %d calc %d\n",m_calcsize,m_waitcnt,m_calccnt); + LOGD("===tooken m_ldftsample %d\n",m_leftsample); + } + if(m_leftsample<=0){ + m_waitcnt = m_calcsize; + LOGD("===tooken m_ldftsample %d\n",m_leftsample); + LOGD("===tooken calc %d waitcnt %d\n",m_calcsize,m_waitcnt); + } + return 0; +} + +int KWav::pushpcm(uint8_t* pcm,int size){ + uint8_t* pstart = pcm; + int psize = size; + if(m_alonecnt){ + pstart++; + psize--; + m_alonearr[1]=*pcm; + float* ps = (float*)m_alonearr; + *m_curwav++ = (float)(*ps++/32767.f); + incsample(1); + m_alonecnt = 0; + } + int sample = psize / 2; + //LOGD("push pcm %d left_sample %d\n",sample,m_leftsample); + int left = psize % 2; + if(sample>m_leftsample){ + sample = m_leftsample; + left = 0; + } + + short* ps = (short*)pstart; + float* pf = m_curwav; + for(int k=0;kdata(),data_length); + // + short* ps = (short*)pcmbuf->data(); + float* pd = (float*)m_wavmat->data(); + float* pf = pd+MFCC_OFFSET; + for(int k=0;ktagarr(); + + float secs = index*MFCC_WAVCHUNK *1.0f/ MFCC_RATE; + if(m_resultcnt==m_calccnt){ + secs = m_pcmsample*1.0f/ MFCC_RATE; + }else{ + secs = index*MFCC_WAVCHUNK *1.0f/ MFCC_RATE; + } + int bnfblock = secs*MFCC_FPS; + if(bnfblock>(m_bnfsize-10))bnfblock = m_bnfsize-10; + //arr[7] = bnfblock; + + return 0; +} + +int KWav::isfinish(){ + if((m_waitcnt == m_calcsize)&&(m_calcsize== m_calccnt)){ + return m_resultcnt==m_calccnt; + }else{ + return 0; + } +} + +int KWav::readyall(){ + m_waitcnt=m_calcsize; + return 0; +} + +int KWav::isready(){ + if(m_waitcnt>m_calccnt){ + return ++m_calccnt; + }else{ + return 0; + } +} + + +int KWav::calcbuf(int calcinx,float** ppwav,float** ppmfcc,float** ppbnf,int* pmel,int* pbnf){ + if(calcinx>m_calcsize)return -1; + if(calcinx<1)return -2; + int index = calcinx -1; + //LOGD("===tooken calcbuf %d\n",index); + *ppwav = m_wavmat->frow(index); + *ppmfcc = m_melmat->frow(index); + //*ppbnf = m_bnfmat->frow(index); + *ppbnf = m_bnfcache->secBuf(index)->fdata(); + if(calcinx==m_calcsize){ + *pmel = m_mellast; + *pbnf = m_bnflast; + }else{ + *pmel = MFCC_MELBASE; + *pbnf = MFCC_BNFBASE; + } + return calcinx; +} + +float KWav::duration(){ + return m_duration; +} + +int KWav::resultcnt(){ + return m_resultcnt; +} + +int KWav::debug(){ + //dumpfloat(m_bnfmat->fdata(),10); + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.h new file mode 100644 index 0000000000000000000000000000000000000000..8b895df35198c0775830714b695913434b6b3e73 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/netwav.h @@ -0,0 +1,56 @@ +#pragma once +#include "jmat.h" +#include "aicommon.h" +#include "wavcache.h" + + +class KWav{ + private: + float m_duration = 0; + int m_pcmsample = 0;; + int m_wavsample = 0;; + int m_seca = 0; + int m_secb = 0; + int m_mellast = 0; + int m_bnflast = 0; + int m_wavsize = 0; + int m_melsize = 0; + int m_bnfsize = 0; + int m_calcsize = 0; + int m_bnfblock = 0; + uint8_t m_alonearr[2] ; + int m_alonecnt = 0; + int m_leftsample = 0; + float *m_curwav = nullptr; + int m_waitsample = 0; + + int m_waitcnt = 0; + int m_calccnt = 0; + int m_resultcnt = 0; + + int incsample(int sample); + + JMat *m_wavmat = nullptr; + JMat *m_melmat = nullptr; + //JMat *m_bnfmat = nullptr; + MBnfCache *m_bnfcache = nullptr; + int initbuf(int pcmsample); + int initinx(); + public: + KWav(float duration,MBnfCache* bnfcache); + KWav(const char* filename,MBnfCache* bnfcache); + //KWav(const char* wavfn); + ~KWav(); + int pushpcm(uint8_t* pcm,int size); + int isready(); + int readyall(); + int isfinish(); + int finishone(int index); + int bnfblocks(); + float duration(); + int resultcnt(); + //JMat* bnfmat(); + int calcbuf(int calcinx,float** ppwav,float** ppmfcc,float** ppbnf,int* pmel,int* pbnf); + int debug(); +}; + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6f8fbe740fad9592dbe3416c409fc8d73a4b914 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.cpp @@ -0,0 +1,200 @@ +#include "pfpld.h" +#include "cpu.h" + + +static int pts68_pfpld(float* arr_pts98,float* arr_pts68){ + float* arr = arr_pts98; + float* dst = arr_pts68; + for(int j=0;j<17;j++){ + *dst++ = arr[j*4]; + *dst++ = arr[j*4 + 1]; + } + for(int j=33;j<38;j++){ + *dst++ = arr[j*2]; + *dst++ = arr[j*2 + 1]; + } + for(int j=42;j<47;j++){ + *dst++ = arr[j*2]; + *dst++ = arr[j*2 + 1]; + } + for(int j=51;j<61;j++){ + *dst++ = arr[j*2]; + *dst++ = arr[j*2 + 1]; + } + float* points = arr; + float point_38_x = (float(points[60 * 2 + 0]) + float(points[62 * 2 + 0])) / 2.0; + float point_38_y = (float(points[60 * 2 + 1]) + float(points[62 * 2 + 1])) / 2.0; + float point_39_x = (float(points[62 * 2 + 0]) + float(points[64 * 2 + 0])) / 2.0; + float point_39_y = (float(points[62 * 2 + 1]) + float(points[64 * 2 + 1])) / 2.0; + float point_41_x = (float(points[64 * 2 + 0]) + float(points[66 * 2 + 0])) / 2.0; + float point_41_y = (float(points[64 * 2 + 1]) + float(points[66 * 2 + 1])) / 2.0; + float point_42_x = (float(points[60 * 2 + 0]) + float(points[66 * 2 + 0])) / 2.0; + float point_42_y = (float(points[60 * 2 + 1]) + float(points[66 * 2 + 1])) / 2.0; + float point_44_x = (float(points[68 * 2 + 0]) + float(points[70 * 2 + 0])) / 2.0; + float point_44_y = (float(points[68 * 2 + 1]) + float(points[70 * 2 + 1])) / 2.0; + float point_45_x = (float(points[70 * 2 + 0]) + float(points[72 * 2 + 0])) / 2.0; + float point_45_y = (float(points[70 * 2 + 1]) + float(points[72 * 2 + 1])) / 2.0; + float point_47_x = (float(points[72 * 2 + 0]) + float(points[74 * 2 + 0])) / 2.0; + float point_47_y = (float(points[72 * 2 + 1]) + float(points[74 * 2 + 1])) / 2.0; + float point_48_x = (float(points[68 * 2 + 0]) + float(points[74 * 2 + 0])) / 2.0; + float point_48_y = (float(points[68 * 2 + 1]) + float(points[74 * 2 + 1])) / 2.0; + + *dst++ = point_38_x; + *dst++ = point_38_y; + *dst++ = point_39_x; + *dst++ = point_39_y; + *dst++ = points[64 * 2 + 0]; + *dst++ = points[64 * 2 + 1]; + *dst++ = point_41_x; + *dst++ = point_41_y; + *dst++ = point_42_x; + *dst++ = point_42_y; + *dst++ = points[68 * 2 + 0]; + *dst++ = points[68 * 2 + 1]; + *dst++ = point_44_x; + *dst++ = point_44_y; + *dst++ = point_45_x; + *dst++ = point_45_y; + *dst++ = points[72 * 2 + 0]; + *dst++ = points[72 * 2 + 1]; + *dst++ = point_47_x; + *dst++ = point_47_y; + *dst++ = point_48_x; + *dst++ = point_48_y; + for(int j = 76; j<96;j++){ + *dst++ = points[j * 2 + 0]; + *dst++ = points[j * 2 + 1]; + } + int len = dst-arr_pts68; + printf("====%d\n",len); + return len; +} + + +int Pfpld::detect(JMat* pic,int* arrboxs,int* arrlands){ + int w = arrboxs[0]; + int h = arrboxs[1]; + + int boxx, boxy ,boxwidth, boxheight ; + int* boxs = arrboxs+6; + boxx = boxs[0];boxy=boxs[1];boxwidth=boxs[2]-boxx;boxheight=boxs[3]-boxy; + + printf("===pfpld %d %d %d %d\n",boxx,boxy,boxwidth,boxheight); + //boxx=192; boxy =245 ; boxwidth=908 -boxx;boxheight=1203 - boxy; + int stride = pic->stride(); + uint8_t* data =(uint8_t*)pic->data() + boxy*stride + boxx*pic->channel(); + ncnn::Mat in = ncnn::Mat::from_pixels_resize(data, ncnn::Mat::PIXEL_BGR2RGB, boxwidth, boxheight, stride,scale_w, scale_h); + in.substract_mean_normalize(mean_vals, norm_vals); + ncnn::Extractor ex = pfpld.create_extractor(); + ex.input("input", in); + ncnn::Mat pose_blob, landms_blob; + ex.extract("pose", pose_blob); + ex.extract("landms", landms_blob); + float* arr = (float*)landms_blob.data; + float tmpdst[512]; + float* dst = tmpdst; + pts68_pfpld(arr,dst); + + int len = 68*2; + int* apts = arrlands; + int axmin = 10000,aymin = 10000,axmax = 0,aymax = 0; + for(int j=0;jx) axmin = x; + if(axmaxy) aymin = y; + if(aymax1.0f)m_wh = 1.0f; + printf("====wh %f\n",m_wh); + float wh = m_wh;//0.8878923766816144; + int xmin = 10000,ymin = 10000,xmax = 0,ymax = 0; + apts = arrlands+2; + for(int j=1;j<16;j++){ + int x = *apts++; + int y = *apts++; + if(xmin>x) xmin = x; + if(xmaxy) ymin = y; + if(ymaxx) xmin = x; + if(xmaxy) ymin = y; + if(ymax=m_width)x2=m_width-1; + if(y2>=m_height)y2=m_height-1; + boxs = arrboxs+10; + *boxs++ = x1; + *boxs++ = y1; + *boxs++ = x2; + *boxs++ = y2; + return 0; +} + +void Pfpld::recal(int w,int h){ + m_width = w; + m_height = h; +} + +Pfpld::Pfpld(const char* modeldir,const char* modelid,int w,int h){ + pfpld.clear(); + ncnn::set_cpu_powersave(2); + ncnn::set_omp_num_threads(ncnn::get_big_cpu_count()); + pfpld.opt = ncnn::Option(); + //pfpld.opt.use_vulkan_compute = true; + pfpld.opt.num_threads = ncnn::get_big_cpu_count(); + //pfpld.load_param("model/pfpld.param"); + //pfpld.load_model("model/pfpld.bin"); + char filepath[1024]; + sprintf(filepath,"%s/%s.param",modeldir,modelid); + pfpld.load_param(filepath); + sprintf(filepath,"%s/%s.bin",modeldir,modelid); + pfpld.load_model(filepath); + recal(w,h); +} + +Pfpld::~Pfpld(){ +} + +#ifdef _PFPLD_MAIN_ +int main(int argc,char** argv){ + Pfpld* pfpld = new Pfpld(1080,1920); + std::string picfile("1.jpg"); + JMat* pic = new JMat(picfile,1); + int* arr = pic->tagarr(); + pfpld->detect(pic,arr+6,arr+64); + printf("precess to exit\n"); + getchar(); + return 0; +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.h new file mode 100644 index 0000000000000000000000000000000000000000..2b7db6d3c1b7733c43caeff776340c1dce0d9866 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/pfpld.h @@ -0,0 +1,27 @@ +#pragma once +#include "jmat.h" +#include "net.h" +#include +#include +#include +#include +#include + +class Pfpld{ + private: + ncnn::Net pfpld; + JMat* m_mat112; + int scale_w = 112; + int scale_h = 112; + float mean_vals[3] = {0.f, 0.f, 0.f}; + float norm_vals[3] = {1 / 255.f, 1 / 255.f, 1 / 255.f}; + int m_width; + int m_height; + float m_wh; + int m_cnt; + void recal(int w,int h); + public: + int detect(JMat* pic,int* arrboxs,int* arrlands); + Pfpld(const char* modeldir,const char* modelid,int w,int h); + ~Pfpld(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4db5cb9f8a2fe52402e0b739738e27bd3de0bc36 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.cpp @@ -0,0 +1,487 @@ +#include "scrfd.h" +#include "cpu.h" + +static int drawface(cv::Mat& rgb, const std::vector& faceobjects) +{ + int has_kps = 1; + for (size_t i = 0; i < faceobjects.size(); i++) + { + const FaceObject& obj = faceobjects[i]; + +// fprintf(stderr, "%.5f at %.2f %.2f %.2f x %.2f\n", obj.prob, +// obj.rect.x, obj.rect.y, obj.rect.width, obj.rect.height); + + cv::rectangle(rgb, obj.rect, cv::Scalar(0, 255, 0)); + + if (has_kps) + { + cv::circle(rgb, obj.landmark[0], 2, cv::Scalar(255, 255, 0), -1); + cv::circle(rgb, obj.landmark[1], 2, cv::Scalar(255, 255, 0), -1); + cv::circle(rgb, obj.landmark[2], 2, cv::Scalar(255, 255, 0), -1); + cv::circle(rgb, obj.landmark[3], 2, cv::Scalar(255, 255, 0), -1); + cv::circle(rgb, obj.landmark[4], 2, cv::Scalar(255, 255, 0), -1); + } + + char text[256]; + sprintf(text, "%.1f%%", obj.prob * 100); + + int baseLine = 0; + cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); + + int x = obj.rect.x; + int y = obj.rect.y - label_size.height - baseLine; + if (y < 0) + y = 0; + if (x + label_size.width > rgb.cols) + x = rgb.cols - label_size.width; + + cv::rectangle(rgb, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), cv::Scalar(255, 255, 255), -1); + + cv::putText(rgb, text, cv::Point(x, y + label_size.height), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0), 1); + } + + return 0; +} + +static inline float intersection_area(const FaceObject& a, const FaceObject& b) +{ + cv::Rect_ inter = a.rect & b.rect; + return inter.area(); +} + +static void qsort_descent_inplace(std::vector& faceobjects, int left, int right) +{ + int i = left; + int j = right; + float p = faceobjects[(left + right) / 2].prob; + + while (i <= j) + { + while (faceobjects[i].prob > p) + i++; + + while (faceobjects[j].prob < p) + j--; + + if (i <= j) + { + // swap + std::swap(faceobjects[i], faceobjects[j]); + + i++; + j--; + } + } + +// #pragma omp parallel sections + { +// #pragma omp section + { + if (left < j) qsort_descent_inplace(faceobjects, left, j); + } +// #pragma omp section + { + if (i < right) qsort_descent_inplace(faceobjects, i, right); + } + } +} + +static void qsort_descent_inplace(std::vector& faceobjects) +{ + if (faceobjects.empty()) + return; + + qsort_descent_inplace(faceobjects, 0, faceobjects.size() - 1); +} + +static void nms_sorted_bboxes(const std::vector& faceobjects, std::vector& picked, float nms_threshold) +{ + picked.clear(); + + const int n = faceobjects.size(); + + std::vector areas(n); + for (int i = 0; i < n; i++) + { + areas[i] = faceobjects[i].rect.area(); + } + + for (int i = 0; i < n; i++) + { + const FaceObject& a = faceobjects[i]; + + int keep = 1; + for (int j = 0; j < (int)picked.size(); j++) + { + const FaceObject& b = faceobjects[picked[j]]; + + // intersection over union + float inter_area = intersection_area(a, b); + float union_area = areas[i] + areas[picked[j]] - inter_area; + // float IoU = inter_area / union_area + if (inter_area / union_area > nms_threshold) + keep = 0; + } + + if (keep) + picked.push_back(i); + } +} + +// insightface/detection/scrfd/mmdet/core/anchor/anchor_generator.py gen_single_level_base_anchors() +static ncnn::Mat generate_anchors(int base_size, const ncnn::Mat& ratios, const ncnn::Mat& scales) +{ + int num_ratio = ratios.w; + int num_scale = scales.w; + + ncnn::Mat anchors; + anchors.create(4, num_ratio * num_scale); + + const float cx = 0; + const float cy = 0; + + for (int i = 0; i < num_ratio; i++) + { + float ar = ratios[i]; + + int r_w = round(base_size / sqrt(ar)); + int r_h = round(r_w * ar); //round(base_size * sqrt(ar)); + + for (int j = 0; j < num_scale; j++) + { + float scale = scales[j]; + + float rs_w = r_w * scale; + float rs_h = r_h * scale; + + float* anchor = anchors.row(i * num_scale + j); + + anchor[0] = cx - rs_w * 0.5f; + anchor[1] = cy - rs_h * 0.5f; + anchor[2] = cx + rs_w * 0.5f; + anchor[3] = cy + rs_h * 0.5f; + } + } + + return anchors; +} + +static void generate_proposals(const ncnn::Mat& anchors, int feat_stride, const ncnn::Mat& score_blob, const ncnn::Mat& bbox_blob, const ncnn::Mat& kps_blob, float prob_threshold, std::vector& faceobjects) +{ + int w = score_blob.w; + int h = score_blob.h; + + // generate face proposal from bbox deltas and shifted anchors + const int num_anchors = anchors.h; + + for (int q = 0; q < num_anchors; q++) + { + const float* anchor = anchors.row(q); + + const ncnn::Mat score = score_blob.channel(q); + const ncnn::Mat bbox = bbox_blob.channel_range(q * 4, 4); + + // shifted anchor + float anchor_y = anchor[1]; + + float anchor_w = anchor[2] - anchor[0]; + float anchor_h = anchor[3] - anchor[1]; + + for (int i = 0; i < h; i++) + { + float anchor_x = anchor[0]; + + for (int j = 0; j < w; j++) + { + int index = i * w + j; + + float prob = score[index]; + + if (prob >= prob_threshold) + { + // insightface/detection/scrfd/mmdet/models/dense_heads/scrfd_head.py _get_bboxes_single() + float dx = bbox.channel(0)[index] * feat_stride; + float dy = bbox.channel(1)[index] * feat_stride; + float dw = bbox.channel(2)[index] * feat_stride; + float dh = bbox.channel(3)[index] * feat_stride; + + // insightface/detection/scrfd/mmdet/core/bbox/transforms.py distance2bbox() + float cx = anchor_x + anchor_w * 0.5f; + float cy = anchor_y + anchor_h * 0.5f; + + float x0 = cx - dx; + float y0 = cy - dy; + float x1 = cx + dw; + float y1 = cy + dh; + + FaceObject obj; + obj.rect.x = x0; + obj.rect.y = y0; + obj.rect.width = x1 - x0 + 1; + obj.rect.height = y1 - y0 + 1; + obj.prob = prob; + + if (!kps_blob.empty()) + { + const ncnn::Mat kps = kps_blob.channel_range(q * 10, 10); + + obj.landmark[0].x = cx + kps.channel(0)[index] * feat_stride; + obj.landmark[0].y = cy + kps.channel(1)[index] * feat_stride; + obj.landmark[1].x = cx + kps.channel(2)[index] * feat_stride; + obj.landmark[1].y = cy + kps.channel(3)[index] * feat_stride; + obj.landmark[2].x = cx + kps.channel(4)[index] * feat_stride; + obj.landmark[2].y = cy + kps.channel(5)[index] * feat_stride; + obj.landmark[3].x = cx + kps.channel(6)[index] * feat_stride; + obj.landmark[3].y = cy + kps.channel(7)[index] * feat_stride; + obj.landmark[4].x = cx + kps.channel(8)[index] * feat_stride; + obj.landmark[4].y = cy + kps.channel(9)[index] * feat_stride; + } + + faceobjects.push_back(obj); + } + + anchor_x += feat_stride; + } + + anchor_y += feat_stride; + } + } +} + +int Scrfd::detect(JMat* pic,int* boxs){ + recal(pic->width(),pic->height()); + ncnn::Mat in = ncnn::Mat::from_pixels_resize(pic->udata(), ncnn::Mat::PIXEL_BGR2RGB, m_width, m_height, scale_w, scale_h); + ncnn::Mat in_pad; + ncnn::copy_make_border(in, in_pad, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, ncnn::BORDER_CONSTANT, 0.f); + in_pad.substract_mean_normalize(mean_vals, norm_vals); + int has_kps = 1; + + ncnn::Extractor ex = scrfd.create_extractor(); + ex.input("input.1", in_pad); + + std::vector faceobjects; + std::vector faceproposals; + //std::vector& faceobjects, float prob_threshold, float nms_threshold) + // stride 8 + { + ncnn::Mat score_blob, bbox_blob, kps_blob; + ex.extract("score_8", score_blob); + ex.extract("bbox_8", bbox_blob); + if (has_kps) + ex.extract("kps_8", kps_blob); + + const int base_size = 16; + const int feat_stride = 8; + ncnn::Mat ratios(1); + ratios[0] = 1.f; + ncnn::Mat scales(2); + scales[0] = 1.f; + scales[1] = 2.f; + ncnn::Mat anchors = generate_anchors(base_size, ratios, scales); + + std::vector faceobjects32; + generate_proposals(anchors, feat_stride, score_blob, bbox_blob, kps_blob, prob_threshold, faceobjects32); + + faceproposals.insert(faceproposals.end(), faceobjects32.begin(), faceobjects32.end()); + } + + // stride 16 + { + ncnn::Mat score_blob, bbox_blob, kps_blob; + ex.extract("score_16", score_blob); + ex.extract("bbox_16", bbox_blob); + if (has_kps) + ex.extract("kps_16", kps_blob); + + const int base_size = 64; + const int feat_stride = 16; + ncnn::Mat ratios(1); + ratios[0] = 1.f; + ncnn::Mat scales(2); + scales[0] = 1.f; + scales[1] = 2.f; + ncnn::Mat anchors = generate_anchors(base_size, ratios, scales); + + std::vector faceobjects16; + generate_proposals(anchors, feat_stride, score_blob, bbox_blob, kps_blob, prob_threshold, faceobjects16); + + faceproposals.insert(faceproposals.end(), faceobjects16.begin(), faceobjects16.end()); + } + + // stride 32 + { + ncnn::Mat score_blob, bbox_blob, kps_blob; + ex.extract("score_32", score_blob); + ex.extract("bbox_32", bbox_blob); + if (has_kps) + ex.extract("kps_32", kps_blob); + + const int base_size = 256; + const int feat_stride = 32; + ncnn::Mat ratios(1); + ratios[0] = 1.f; + ncnn::Mat scales(2); + scales[0] = 1.f; + scales[1] = 2.f; + ncnn::Mat anchors = generate_anchors(base_size, ratios, scales); + + std::vector faceobjects8; + generate_proposals(anchors, feat_stride, score_blob, bbox_blob, kps_blob, prob_threshold, faceobjects8); + + faceproposals.insert(faceproposals.end(), faceobjects8.begin(), faceobjects8.end()); + } + + // sort all proposals by score from highest to lowest + qsort_descent_inplace(faceproposals); + + // apply nms with nms_threshold + std::vector picked; + nms_sorted_bboxes(faceproposals, picked, nms_threshold); + + int face_count = picked.size(); + printf("====face_count %d\n",face_count); + faceobjects.resize(face_count); + for (int i = 0; i < face_count; i++) + { + faceobjects[i] = faceproposals[picked[i]]; + + // adjust offset to original unpadded + float x0 = (faceobjects[i].rect.x - (wpad / 2)) / scale; + float y0 = (faceobjects[i].rect.y - (hpad / 2)) / scale; + float x1 = (faceobjects[i].rect.x + faceobjects[i].rect.width - (wpad / 2)) / scale; + float y1 = (faceobjects[i].rect.y + faceobjects[i].rect.height - (hpad / 2)) / scale; + + x0 = std::max(std::min(x0, (float)m_width - 1), 0.f); + y0 = std::max(std::min(y0, (float)m_height - 1), 0.f); + x1 = std::max(std::min(x1, (float)m_width - 1), 0.f); + y1 = std::max(std::min(y1, (float)m_height - 1), 0.f); + + faceobjects[i].rect.x = x0; + faceobjects[i].rect.y = y0; + faceobjects[i].rect.width = x1 - x0; + faceobjects[i].rect.height = y1 - y0; + + if (has_kps) + { + float x0 = (faceobjects[i].landmark[0].x - (wpad / 2)) / scale; + float y0 = (faceobjects[i].landmark[0].y - (hpad / 2)) / scale; + float x1 = (faceobjects[i].landmark[1].x - (wpad / 2)) / scale; + float y1 = (faceobjects[i].landmark[1].y - (hpad / 2)) / scale; + float x2 = (faceobjects[i].landmark[2].x - (wpad / 2)) / scale; + float y2 = (faceobjects[i].landmark[2].y - (hpad / 2)) / scale; + float x3 = (faceobjects[i].landmark[3].x - (wpad / 2)) / scale; + float y3 = (faceobjects[i].landmark[3].y - (hpad / 2)) / scale; + float x4 = (faceobjects[i].landmark[4].x - (wpad / 2)) / scale; + float y4 = (faceobjects[i].landmark[4].y - (hpad / 2)) / scale; + + faceobjects[i].landmark[0].x = std::max(std::min(x0, (float)m_width - 1), 0.f); + faceobjects[i].landmark[0].y = std::max(std::min(y0, (float)m_height - 1), 0.f); + faceobjects[i].landmark[1].x = std::max(std::min(x1, (float)m_width - 1), 0.f); + faceobjects[i].landmark[1].y = std::max(std::min(y1, (float)m_height - 1), 0.f); + faceobjects[i].landmark[2].x = std::max(std::min(x2, (float)m_width - 1), 0.f); + faceobjects[i].landmark[2].y = std::max(std::min(y2, (float)m_height - 1), 0.f); + faceobjects[i].landmark[3].x = std::max(std::min(x3, (float)m_width - 1), 0.f); + faceobjects[i].landmark[3].y = std::max(std::min(y3, (float)m_height - 1), 0.f); + faceobjects[i].landmark[4].x = std::max(std::min(x4, (float)m_width - 1), 0.f); + faceobjects[i].landmark[4].y = std::max(std::min(y4, (float)m_height - 1), 0.f); + } + break; + } + if(faceobjects.size()>0){ + FaceObject fo = faceobjects[0]; + cv::Rect_ rect = fo.rect; + //std::cout<tagarr(); + int inx = 0; + tag[inx++] = w; + tag[inx++] = h; + tag[inx++] = x1; + tag[inx++] = y1; + tag[inx++] = x2; + tag[inx++] = y2; + float adj = w*0.1f; + x1 = x1 - adj; + if(x1<0)x1=0; + if(y1<0)y1=0; + adj = (x2-x1)*0.1f; + x2 = x2 + adj; + if(x2>=m_width)x2=m_width-1; + adj = (y2-y1)*0.1f; + y2 = y2 + adj; + if(y2>=m_height)y2=m_height-1; + tag[inx++] = x1; + tag[inx++] = y1; + tag[inx++] = x2; + tag[inx++] = y2; + printf("adj x1 %d y1 %d x2 %d y2 %d\n",x1,y1,x2,y2); + } + //cv::Mat drawmat(m_height,m_width,CV_8UC3,pic->udata()); + //drawface(drawmat,faceobjects); + //cv::imshow("aaa",drawmat); + //cv::waitKey(0); + return 0; +} + +void Scrfd::recal(int nw ,int nh){ + if((nw==m_width)&&(nh==m_height))return; + m_width = nw; + m_height = nh; + int w = m_width; + int h = m_height; + scale = 1.f; + if (w > h) { + scale = (float)target_size / w; + w = target_size; + h = h * scale; + } else { + scale = (float)target_size / h; + h = target_size; + w = w * scale; + } + scale_h = h; + scale_w = w; + wpad = (w + 31) / 32 * 32 - w; + hpad = (h + 31) / 32 * 32 - h; +} + +Scrfd::Scrfd(const char* modeldir,const char* modelid,int cols,int rows){ + scrfd.clear(); + ncnn::set_cpu_powersave(2); + ncnn::set_omp_num_threads(ncnn::get_big_cpu_count()); + scrfd.opt = ncnn::Option(); + //scrfd.opt.use_vulkan_compute = true; + scrfd.opt.num_threads = ncnn::get_big_cpu_count(); + char filepath[1024]; + sprintf(filepath,"%s/%s.param",modeldir,modelid); + scrfd.load_param(filepath); + sprintf(filepath,"%s/%s.bin",modeldir,modelid); + scrfd.load_model(filepath); + //scrfd.load_param("model/scrfd_500m_kps-opt2.param"); + //scrfd.load_model("model/scrfd_500m_kps-opt2.bin"); + //scrfd.load_param("model/scrfd.param"); + //scrfd.load_model("model/scrfd.bin"); + recal(cols,rows); +} + +Scrfd::~Scrfd(){ + +} + +#ifdef _SCRFD_MAIN_ +int main(int argc,char** argv){ + Scrfd* scrfd = new Scrfd(1080,1920); + std::string picfile("1.jpg"); + JMat* pic = new JMat(picfile,1); + scrfd->detect(pic,pic->tagarr()); + printf("precess to exit\n"); + getchar(); + return 0; +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.h new file mode 100644 index 0000000000000000000000000000000000000000..769c7f7d9299dd51be8b926a3467cf8c62da84ff --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/scrfd.h @@ -0,0 +1,38 @@ +#pragma once +#include "jmat.h" +#include "net.h" +#include +#include +#include +#include +#include + +struct FaceObject +{ + cv::Rect_ rect; + cv::Point2f landmark[5]; + float prob; +}; + +class Scrfd{ + private: + ncnn::Net scrfd; + + int target_size = 640; + float prob_threshold = 0.3f; + float nms_threshold = 0.45f; + float mean_vals[3] = {127.5f, 127.5f, 127.5f}; + float norm_vals[3] = {1 / 128.f, 1 / 128.f, 1 / 128.f}; + float scale; + int scale_w; + int scale_h; + int wpad; + int hpad; + int m_width; + int m_height; + void recal(int nw ,int nh); + public: + int detect(JMat* pic,int* boxs); + Scrfd(const char* modeldir,const char* modelid,int cols,int rows); + ~Scrfd(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b488dfd0cc768bb362522fc3cbb089cab3e708d7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.cpp @@ -0,0 +1,97 @@ +#include "wavcache.h" +#include "aicommon.h" + + +JMat* MBufCache::secBuf(int sec){ + JMat* mat = NULL; + m_lock->lock(); + if(secunlock(); + return mat; +} +void MBufCache::debug(){ + +} + +JMat* MBufCache::inxBuf(int inx){ + int seca = inx/m_sech; + int secb = inx%m_sech; + JMat* mat = NULL; + if(secb>=m_lineh){ + mat= new JMat(m_secw,m_blockh,1); + JMat* sa = secBuf(seca); + int la = m_sech-secb; + int parta = la*m_secw; + float* pa = mat->fdata(); + memcpy(pa,sa->frow(secb),parta*sizeof(float)); + JMat* sb = secBuf(seca+1); + int lb = m_blockh - la; + float* pb = pa+parta; + int partb = lb*m_secw; + memcpy(pb,sa->frow(0),partb*sizeof(float)); + }else{ + JMat* src = secBuf(seca); + float* buf = src->frow(secb); + //printf("==dist %d\n",(buf-src->fdata())*4); + mat = new JMat(m_secw,m_blockh,buf,1); + //printf("==size %d %d = %d\n",m_secw,m_blockh,m_secw*m_blockh*4); + } + return mat; +} + +int* MBufCache::tagarr(){ + return m_tagarr; +} + +MBufCache::MBufCache(int initsec,int secw,int sech,int blockh){ + m_lock = new std::mutex(); + m_secw = secw; + m_sech = sech; + m_blockh = blockh; + m_lineh = sech-blockh; + for(int k=0;klock(); + for(int k=0;kunlock(); + delete m_lock; +} + +#include "aicommon.h" + +MBnfCache::MBnfCache():MBufCache(3,MFCC_BNFCHUNK,MFCC_BNFBASE,20){ +} + +MBnfCache::~MBnfCache(){ +} + +#ifdef _WAVTEST_ +int main(int argc,char** argv){ + MBnfCache cache; + for(int k=0;k<100;k++){ + JMat* mat = cache.secBuf(k); + } + for(int k=816;k<817;k++){ + printf("#%d# \n",k); + JMat* mat = cache.inxBuf(k); + JMat cm = mat->clone(); + delete mat; + } + return 0; +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.h new file mode 100644 index 0000000000000000000000000000000000000000..4969441d767df77fd3f00eb926c1e391f37e9e26 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavcache.h @@ -0,0 +1,28 @@ +#pragma once +#include "jmat.h" +#include +#include + +class MBufCache{ + protected: + int m_lineh; + int m_secw; + int m_sech; + int m_blockh; + std::mutex *m_lock; + std::vector vec_buf ; + int m_tagarr[512]; + public: + JMat* secBuf(int sec); + JMat* inxBuf(int inx); + int* tagarr(); + MBufCache(int initsec,int secw,int sech,int blockh); + virtual ~MBufCache(); + void debug(); +}; + +class MBnfCache:public MBufCache{ + public: + MBnfCache(); + virtual ~MBnfCache(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d678ffd065f2d6b76c8715ad9fd05c4368a8189 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.cpp @@ -0,0 +1,210 @@ + +#include "wavreader.h" +#include +#include +#include +#include + +#define TAG(a, b, c, d) (((a) << 24) | ((b) << 16) | ((c) << 8) | (d)) + +struct wav_reader { + FILE *wav; + long data_pos; + uint32_t data_length; + uint32_t data_left; + + int format; + int sample_rate; + int bits_per_sample; + int channels; + int byte_rate; + int block_align; + + int streamed; +}; + +static uint32_t read_tag(struct wav_reader* wr) { + uint32_t tag = 0; + char c1 = fgetc(wr->wav); + char c2 = fgetc(wr->wav); + char c3 = fgetc(wr->wav); + char c4 = fgetc(wr->wav); + tag = (tag << 8) | c1; + tag = (tag << 8) | c2; + tag = (tag << 8) | c3; + tag = (tag << 8) | c4; + printf("===tag %c %c %c %c\n",c1,c2,c3,c4); + return tag; +} + +static uint32_t read_int32(struct wav_reader* wr) { + uint32_t value = 0; + value |= fgetc(wr->wav) << 0; + value |= fgetc(wr->wav) << 8; + value |= fgetc(wr->wav) << 16; + value |= fgetc(wr->wav) << 24; + return value; +} + +static uint16_t read_int16(struct wav_reader* wr) { + uint16_t value = 0; + value |= fgetc(wr->wav) << 0; + value |= fgetc(wr->wav) << 8; + return value; +} + +static void skip(FILE *f, int n) { + int i; + for (i = 0; i < n; i++) + fgetc(f); +} + +void* wav_read_open(const char *filename) { + struct wav_reader* wr = (struct wav_reader*) malloc(sizeof(*wr)); + memset(wr, 0, sizeof(*wr)); + + if (!strcmp(filename, "-")) + wr->wav = stdin; + else + wr->wav = fopen(filename, "rb"); + if (wr->wav == NULL) { + free(wr); + return NULL; + } + + while (1) { + uint32_t tag, tag2, length; + tag = read_tag(wr); + if (feof(wr->wav)) + break; + length = read_int32(wr); + if (!length || length >= 0x7fff0000) { + wr->streamed = 1; + length = ~0; + } + if (tag != TAG('R', 'I', 'F', 'F') || length < 4) { + fseek(wr->wav, length, SEEK_CUR); + continue; + } + tag2 = read_tag(wr); + length -= 4; + if (tag2 != TAG('W', 'A', 'V', 'E')) { + fseek(wr->wav, length, SEEK_CUR); + continue; + } + // RIFF chunk found, iterate through it + while (length >= 8) { + uint32_t subtag, sublength; + subtag = read_tag(wr); + //char* fff = (char*)&subtag; + if (feof(wr->wav)) + break; + sublength = read_int32(wr); + printf("==== subleng %d\n",sublength ); + length -= 8; + if (length < sublength) + break; + if (subtag == TAG('f', 'm', 't', ' ')) { + if (sublength < 16) { + // Insufficient data for 'fmt ' + break; + } + wr->format = read_int16(wr); + wr->channels = read_int16(wr); + wr->sample_rate = read_int32(wr); + wr->byte_rate = read_int32(wr); + wr->block_align = read_int16(wr); + wr->bits_per_sample = read_int16(wr); + if (wr->format == 0xfffe) { + if (sublength < 28) { + // Insufficient data for waveformatex + break; + } + skip(wr->wav, 8); + wr->format = read_int32(wr); + skip(wr->wav, sublength - 28); + } + else { + skip(wr->wav, sublength - 16); + } + } + else if (subtag == TAG('d', 'a', 't', 'a')) { + wr->data_pos = ftell(wr->wav); + wr->data_length = sublength; + printf("==== data subleng %d\n",sublength ); + wr->data_left = wr->data_length; + if (!wr->data_length || wr->streamed) { + wr->streamed = 1; + return wr; + } + fseek(wr->wav, sublength, SEEK_CUR); + } + else { + skip(wr->wav, sublength); + } + length -= sublength; + } + if (length > 0) { + // Bad chunk? + fseek(wr->wav, length, SEEK_CUR); + } + } + fseek(wr->wav, wr->data_pos, SEEK_SET); + return wr; +} + +void wav_read_close(void* obj) { + struct wav_reader* wr = (struct wav_reader*) obj; + if (wr->wav != stdin) + fclose(wr->wav); + free(wr); +} + +int wav_get_header(void* obj, int* format, int* channels, int* sample_rate, int* bits_per_sample, unsigned int* data_length) { + struct wav_reader* wr = (struct wav_reader*) obj; + if (format) + *format = wr->format; + if (channels) + *channels = wr->channels; + if (sample_rate) + *sample_rate = wr->sample_rate; + if (bits_per_sample) + *bits_per_sample = wr->bits_per_sample; + printf("==== data left %d byterate %d\n",wr->data_left ,wr->byte_rate); + if (data_length) + *data_length = wr->data_length; + return wr->format && wr->sample_rate; +} + +int wav_read_data(void* obj, unsigned char* data, unsigned int length) { + struct wav_reader* wr = (struct wav_reader*) obj; + int n; + if (wr->wav == NULL) + return -1; + if (length > wr->data_left && !wr->streamed) { + int loop = 1; + if (loop) { + fseek(wr->wav, wr->data_pos, SEEK_SET); + wr->data_left = wr->data_length; + } + length = wr->data_left; + } + n = fread(data, 1, length, wr->wav); + wr->data_left -= length; + return n; +} +#ifdef WAVTEST +int main(int argc,char** argv){ + printf("====file %s\n",argv[1]); + void* hnd = wav_read_open(argv[1]); + int format; + int channels; + int sample_rate; + int bits_per_sample; + unsigned int data_length; + int rst = wav_get_header(hnd, &format, &channels, &sample_rate, &bits_per_sample, &data_length); + printf("===format %d channels %d sample_rate %d,bit %d,len %lu\n",format, channels, sample_rate, bits_per_sample, data_length); + return 0; + +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.h new file mode 100644 index 0000000000000000000000000000000000000000..603660eaf5457f3a448b53de3f635b8d9c547e61 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wavreader.h @@ -0,0 +1,37 @@ +/* ------------------------------------------------------------------ +* Copyright (C) 2009 Martin Storsjo +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. +* See the License for the specific language governing permissions +* and limitations under the License. +* ------------------------------------------------------------------- +*/ + +#ifndef WAVREADER_H_ +#define WAVREADER_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +void* wav_read_open(const char *filename); +void wav_read_close(void* obj); + +int wav_get_header(void* obj, int* format, int* channels, int* sample_rate, int* bits_per_sample, unsigned int* data_length); +int wav_read_data(void* obj, unsigned char* data, unsigned int length); + +#ifdef __cplusplus +} +#endif + +#endif \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..728ccbd2aedc9a895748a479fca22bda9745cd59 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.cpp @@ -0,0 +1,196 @@ +#include "wenet.h" +#include +#include +#include +#include "wavreader.h" +#include "face_utils.h" +#include "mfcc/mfcc.hpp" +#include "jlog.h" +#include "aicommon.h" + +void Wenet::initModel(const char* modelfn){ + m_model = new OnnxModel(); + string modelpath(modelfn); + m_model->initModel(modelpath); + //m_model->pushName("speech",1); + //m_model->pushName("speech_lengths",1); + //m_model->pushName("encoder_out",0); +} + +int Wenet::calcbnf(float* melbin,int melnum,float* bnfbin,int bnfnum){ + int rst = 0; + int chkmfcc = melnum; + int chkbnf = bnfnum; + auto onecfg = m_model->config(); + auto cfg = &onecfg; + //cfg->dump(); + cfg->shape_inputs[0][0] = 1; + cfg->shape_inputs[0][1] = chkmfcc; + cfg->size_inputs[0] = chkmfcc*MFCC_MELCHUNK; + cfg->shape_inputs[1][0] = 1; + cfg->size_inputs[1] = 1; + + cfg->shape_outputs[0][0] = 1; + cfg->shape_outputs[0][1] = chkbnf; + cfg->shape_outputs[0][2] = MFCC_BNFCHUNK; + cfg->size_outputs[0] = chkbnf*MFCC_BNFCHUNK; + cfg->dump(); + void* arrin[] = { melbin,&chkmfcc,NULL }; + void* arrout[] = { bnfbin,NULL }; + const char* namein[] = {"speech","speech_lengths",NULL}; + const char* nameout[] = {"encoder_out",NULL}; + cfg->names_in = namein; + cfg->names_out = nameout; + rst = m_model->runModel(arrin,arrout,NULL,cfg); + return rst; +} + +Wenet::Wenet(const char* modeldir,const char* modelid){ + char path[1024]; + sprintf(path,"%s/%s.onnx",modeldir,modelid); + initModel((const char*)path); +} + +Wenet::Wenet(const char* modelfn){ + initModel(modelfn); +} + +Wenet::~Wenet(){ + delete m_model; +} + +//int Wenet::nextwav(const char* wavfile,JMat** pmat){ +int Wenet::nextwav(const char* wavfile,MBnfCache* bnfcache){ + + int m_pcmsample = 0; + JBuf *m_pcmbuf = nullptr; + JMat *m_wavmat = nullptr; + JMat *m_melmat = nullptr; + //JMat *m_bnfmat = nullptr; + + int format, channels, sr, bits_per_sample; + unsigned int data_length; + void* fhnd = wav_read_open(wavfile); + if(!fhnd)return -1; + int res = wav_get_header(fhnd, &format, &channels, &sr, &bits_per_sample, &data_length); + if(data_length<1) { + wav_read_close(fhnd); + return -2; + } + LOGE("data len %d\n",data_length); + m_pcmbuf = new JBuf(data_length); + int rst = wav_read_data(fhnd,(unsigned char*)m_pcmbuf->data(),data_length); + wav_read_close(fhnd); + int wavsample = data_length/2; + m_pcmsample = wavsample + 2*MFCC_OFFSET; + int seca = m_pcmsample / MFCC_WAVCHUNK; + int secb = m_pcmsample % MFCC_WAVCHUNK; + if(secb>0){ + //m_pcmsample = wavsample + 2*MFCC_OFFSET + MFCC_WAVCHUNK - secb; + //seca++; + } + int mellast = secb?(secb /160 +1):0; + int bnflast = secb?((mellast*0.25f)-0.75f):0; + + int wavsize = seca*MFCC_WAVCHUNK + secb; + int melsize = seca*MFCC_MELBASE+mellast; + int bnfsize = seca*MFCC_BNFBASE+bnflast; + + int calcsize = seca+1; + + m_wavmat = new JMat(MFCC_WAVCHUNK,calcsize,1); + m_wavmat->zeros(); + short* ps = (short*)m_pcmbuf->data(); + float* pd = (float*)m_wavmat->data(); + float* pf = pd+MFCC_OFFSET; + for(int k=0;kzeros(); + //m_bnfmat = new JMat(MFCC_BNFCHUNK,MFCC_BNFBASE*calcsize,1); + //m_bnfmat->zeros(); + // + //printf("===seca %d secb %d mellast %d\n",seca,secb,mellast); + //m_bnfmat = new JMat( + calcmfcc(m_wavmat,m_melmat); + float* mel = m_melmat->fdata(); + for(int k=0;ksecBuf(k)->fdata(); + calcbnf(mel,MFCC_MELBASE,bnf,MFCC_BNFBASE); + //dumpfloat(bnf,10); + mel+=MFCC_MELBASE*MFCC_MELCHUNK; + //bnf+=MFCC_BNFBASE*MFCC_BNFCHUNK; + } + if(mellast){ + //fix last + int inxsec = seca ;//seca?(seca+1):0; + printf("===indexsec %d\n",inxsec); + float* bnf = bnfcache->secBuf(inxsec)->fdata(); + calcbnf(mel,mellast,bnf,bnflast); + //dumpfloat(bnf,10); + //calcbnf(mel,MFCC_MELBASE,bnf,MFCC_BNFBASE); + } + int* arr = bnfcache->tagarr(); + // + arr[0] = wavsize; + arr[1] = m_pcmsample; + arr[2] = seca; + arr[3] = secb; + float secs = wavsample *1.0f/ MFCC_RATE; + int bnfblock = secs*MFCC_FPS; + if(bnfblock>(bnfsize-10))bnfblock = bnfsize-10; + arr[4] = melsize; + arr[5] = bnfsize; + arr[6] = bnfblock; + /* + for(int k=0;k<10;k++){ + float* bnf = m_bnfmat->frow(k); + printf("==%d =bnf %f\n",k,*bnf); + } + */ + //*pmat = m_bnfmat; + delete m_pcmbuf; + delete m_wavmat; + delete m_melmat ; + return bnfblock; +} + +float* Wenet::nextbnf(JMat* bnfmat,int index){ + int* arr = bnfmat->tagarr(); + int bnfsize = arr[5] ; + int bnfblock = arr[6] ; + LOGD("===index %d bnfsize %d bnfblock %d\n",index,bnfsize,bnfblock); + if(bnfblock>bnfsize)return NULL; + if(index>=bnfblock)return NULL; + float* buf = bnfmat->fdata(); + buf += index*MFCC_BNFCHUNK+MFCC_BNFCHUNK; + return buf; +} + +int Wenet::calcmfcc(float* fwav,float* mel2){ + int rst = 0; + int melcnt = MFCC_WAVCHUNK/160+1; + rst = log_mel(fwav,MFCC_WAVCHUNK, 16000,mel2); + return rst; +} + +int Wenet::calcmfcc(JMat* mwav,JMat* mmel){ + int rst = 0; + int melcnt = MFCC_WAVCHUNK/160+1; + for(size_t k=0;kheight();k++){ + float* fwav = mwav->frow(k); + float* mel2 = mmel->frow(k); + rst = log_mel(fwav,MFCC_WAVCHUNK, 16000,mel2); + } + return rst; +} + +#ifdef WENET_MAIN + +int main(int argc,char** argv){ + Wenet net("../model","wenet"); + net->nextwav("../mybin/a.wav"); + return 0; +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.h new file mode 100644 index 0000000000000000000000000000000000000000..0e845c09375843f059d2c3fd7da2a939ae499379 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/aisdk/wenet.h @@ -0,0 +1,22 @@ +#pragma once +#include "jmat.h" +#include "aimodel.h" +#include +#include "wavcache.h" + +//#include +class Wenet{ + private: + OnnxModel *m_model = nullptr; + void initModel(const char* modelfn); + public: + int calcmfcc(JMat* mwav,JMat* mmel); + int calcmfcc(float* fwav,float* mel2); + int calcbnf(float* melbin,int melnum,float* bnfbin,int bnfnum); + //int nextwav(const char* wavfile,JMat** pmat); + int nextwav(const char* wavfile,MBnfCache* bnfcache); + float* nextbnf(JMat* bnfmat,int index); + Wenet(const char* modeldir,const char* modelid); + Wenet(const char* modelfn); + ~Wenet(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc4519f3d027de0a1f3f2e8cb6c5b1e1a16618e1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.cpp @@ -0,0 +1,53 @@ +#include +#include "AudioTrackJni.h" +#include "JniHelper.h" + +#define TAG "AudioTrackJni" + +AudioTrackJni::AudioTrackJni(void* obj):AudioTrack(obj) { + JNIEnv *env = JniHelper::getJNIEnv(); + audioTrackObj = env->NewGlobalRef(obj); + audioTrackClass = env->GetObjectClass(obj); + audioTrackStart = env->GetMethodID(audioTrackClass, "open", "(IIII)V"); + audioTrackWrite = env->GetMethodID(audioTrackClass, "write", "(Ljava/nio/ByteBuffer;I)I"); + audioTrackStop = env->GetMethodID(audioTrackClass, "close", "()V"); +} + +AudioTrackJni::~AudioTrackJni() = default; + +void AudioTrackJni::start(int sampleRate, int sampleFormat, int channels, int bytesPerSample) { + LOGI(TAG, "start %d %d %d %d", sampleRate, sampleFormat, channels, bytesPerSample); + bool attach = JniHelper::attachCurrentThread(); + if (audioTrackObj != nullptr && audioTrackStart != nullptr) { + JniHelper::callVoidMethod(audioTrackObj, audioTrackStart, sampleRate, sampleFormat, + channels, bytesPerSample); + } + if (attach) { + JniHelper::detachCurrentThread(); + } +} + +int AudioTrackJni::write(uint8_t *buffer, int size) { + bool attach = JniHelper::attachCurrentThread(); + if (audioTrackObj != nullptr && audioTrackWrite != nullptr) { + JNIEnv *env = JniHelper::getJNIEnv(); + jobject byteBuffer = JniHelper::createByteBuffer(env, buffer, size); + int result = JniHelper::callIntMethod(audioTrackObj, audioTrackWrite, byteBuffer, size); + env->DeleteLocalRef(byteBuffer); + return result; + } + if (attach) { + JniHelper::detachCurrentThread(); + } + return -1; +} + +void AudioTrackJni::stop() { + bool attach = JniHelper::attachCurrentThread(); + if (audioTrackObj != nullptr && audioTrackStop != nullptr) { + JniHelper::callVoidMethod(audioTrackObj, audioTrackStop); + } + if (attach) { + JniHelper::detachCurrentThread(); + } +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.h new file mode 100644 index 0000000000000000000000000000000000000000..80206e1033683dd31ccc8953477cb48593354502 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/AudioTrackJni.h @@ -0,0 +1,32 @@ +#ifndef GPLAYER_AUDIOTRACKJNI_H +#define GPLAYER_AUDIOTRACKJNI_H + + +#include +#include "FrameSource.h" +#include "AudioTrack.h" + +class AudioTrackJni:public AudioTrack { +public: + AudioTrackJni(jobject obj); + + ~AudioTrackJni(); + + virtual void start(int sampleRate, int sampleFormat, int channels, int bytesPerSample); + + virtual int write(uint8_t *buffer, int size); + + virtual void stop(); + +private: + jclass audioTrackClass; + jmethodID audioTrackStart; + jmethodID audioTrackWrite; + jmethodID audioTrackStop; + +private: + jobject audioTrackObj; +}; + + +#endif //GPLAYER_AUDIOTRACKJNI_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/DigitJni.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/DigitJni.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e144d1f17c54edd34b973f1fbe52e54dae31cdc5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/DigitJni.cpp @@ -0,0 +1,273 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "GDigit.h" +#include "Log.h" +#include "MsgcbJni.h" +#include "JniHelper.h" +#include "aesmain.h" + +#if __ARM_NEON +#include +#endif // __ARM_NEON + // + // +static GDigit* g_digit = 0; +static JMat* g_gpgmat = NULL; +static MessageCb* g_msgcb = new MessageCb(); +static int g_width = 540; +static int g_height = 960; +static int g_taskid = -1; +#define TAG "tooken" +extern "C" { + + JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { + LOGD(TAG, "JNI_OnLoad"); + g_digit = new GDigit(g_width,g_height,g_msgcb); + JniHelper::sJavaVM = vm; + return JNI_VERSION_1_4; + } + + JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) { + LOGI(TAG, "unload"); + if(g_digit){ + delete g_digit; + g_digit = nullptr; + } + if(g_msgcb){ + delete g_msgcb; + g_msgcb = nullptr; + } + } + + static std::string getStringUTF(JNIEnv *env, jstring obj) { + char *c_str = (char *) env->GetStringUTFChars(obj, nullptr); + std::string tmpString = std::string(c_str); + env->ReleaseStringUTFChars(obj, c_str); + return tmpString; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_initModel(JNIEnv *env, jobject thiz, jstring cfgtxt){ + return -1; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_createdigit(JNIEnv *env, jobject thiz, jint taskid,jobject msgcbobj){ + LOGI(TAG, "create"); + g_taskid = taskid; + return 0; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_releasedigit(JNIEnv *env, jobject thiz,jint taskid){ + if(g_taskid==taskid){ + g_digit->stop(); + g_digit->recyle(); + } + return 0; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_config(JNIEnv *env, jobject thiz, jstring cfgtxt){ + std::string str = getStringUTF(env,cfgtxt); + LOGI(TAG,"cfgstr %s",str.c_str()); + g_digit->config(str.c_str()); + LOGI(TAG,"cfgstr %s",str.c_str()); + g_digit->prepare(); + return 0; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_start(JNIEnv *env, jobject thiz){ + g_digit->start(); + return 0; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_stop(JNIEnv *env, jobject thiz){ + g_digit->stop(); + return 0; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_netwav(JNIEnv *env, jobject thiz, jstring wavurl,jfloat duration){ + std::string s_wav = getStringUTF(env,wavurl); + return g_digit->netwav(s_wav.c_str(),duration); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_bgpic(JNIEnv *env, jobject thiz, jstring picfn){ + std::string s_pic = getStringUTF(env,picfn); + return g_digit->bgpic(s_pic.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_drawmskpic(JNIEnv *env, jobject thiz, jstring picfn,jstring mskfn){ + std::string s_pic = getStringUTF(env,picfn); + std::string s_dump = getStringUTF(env,mskfn); + return g_digit->drawmskpic(s_pic.c_str(),s_dump.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_drawmskbuf(JNIEnv *env, jobject thiz, jstring picfn,jstring mskfn,jbyteArray arrbuf,jbyteArray mskbuf,jint bufsize){ + std::string s_pic = getStringUTF(env,picfn); + std::string s_dump = getStringUTF(env,mskfn); + jbyte *pixels = (jbyte *) env->GetPrimitiveArrayCritical(arrbuf, 0); + jbyte *pmsk = (jbyte *) env->GetPrimitiveArrayCritical(mskbuf, 0); + int size = bufsize; + int rst = g_digit->drawmskbuf(s_pic.c_str(),s_dump.c_str(),(char*)pixels,(char*)pmsk,size); + env->ReleasePrimitiveArrayCritical(arrbuf, pixels, 0); + env->ReleasePrimitiveArrayCritical(mskbuf, pmsk, 0); + return rst; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_mskrstpic(JNIEnv* env, jobject thiz,jstring picfile, jstring mskfile,jintArray arrbox, jint index,jstring fgfile){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_msk = getStringUTF(env,mskfile); + std::string s_fg = getStringUTF(env,fgfile); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + int rst = g_digit->mskrstpic(index,s_pic.c_str(),(int*)boxData,s_msk.c_str(),s_fg.c_str()); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_drawonebuf(JNIEnv *env, jobject thiz, jstring picfn,jbyteArray arrbuf,jint bufsize){ + std::string s_pic = getStringUTF(env,picfn); + jbyte *pixels = (jbyte *) env->GetPrimitiveArrayCritical(arrbuf, 0); + int size = bufsize; + int rst = g_digit->drawonebuf(s_pic.c_str(),(char*)pixels,size); + env->ReleasePrimitiveArrayCritical(arrbuf, pixels, 0); + return rst; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_onerstbuf(JNIEnv* env, jobject thiz,jstring picfile, jintArray arrbox, jint index,jbyteArray arrbuf,jint bufsize){ + std::string s_pic = getStringUTF(env,picfile); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + jbyte *pixels = (jbyte *) env->GetPrimitiveArrayCritical(arrbuf, 0); + int size = bufsize; + int rst = g_digit->onerstbuf(index,s_pic.c_str(),(int*)boxData,(char*) pixels,size); + env->ReleasePrimitiveArrayCritical(arrbuf, pixels, 0); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_mskrstbuf(JNIEnv* env, jobject thiz,jstring picfile, jstring mskfile,jintArray arrbox, jint index,jstring fgfile,jbyteArray arrbuf,jbyteArray mskbuf,jint bufsize){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_msk = getStringUTF(env,mskfile); + std::string s_fg = getStringUTF(env,fgfile); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + jbyte *pixels = (jbyte *) env->GetPrimitiveArrayCritical(arrbuf, 0); + jbyte *pmsk = (jbyte *) env->GetPrimitiveArrayCritical(mskbuf, 0); + int size = bufsize; + int rst = g_digit->mskrstbuf(index,s_pic.c_str(),(int*)boxData,s_msk.c_str(),s_fg.c_str(),(char*) pixels,(char*)pmsk,size); + env->ReleasePrimitiveArrayCritical(arrbuf, pixels, 0); + env->ReleasePrimitiveArrayCritical(mskbuf, pmsk, 0); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_onewav(JNIEnv *env, jobject thiz, jstring wavfn,jstring dumpfn){ + std::string s_wav = getStringUTF(env,wavfn); + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newwav(s_wav.c_str(),s_dump.c_str()); + } + + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_onepic(JNIEnv *env, jobject thiz, jstring picfn,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfn); + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newpic(s_pic.c_str(),s_dump.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_drawpic(JNIEnv *env, jobject thiz, jstring picfn){ + std::string s_pic = getStringUTF(env,picfn); + return g_digit->drawpic(s_pic.c_str()); + } + // public native boolean openCamera(int facing); + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_onerst(JNIEnv* env, jobject thiz, jint index,jstring dumpfn) { + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newrst(index,s_dump.c_str()); + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_netrst(JNIEnv* env, jobject thiz, jint index,jstring dumpfn) { + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->netrst(index,s_dump.c_str()); + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_picrst(JNIEnv* env, jobject thiz,jstring picfile, jintArray arrbox, jint index,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_dump = getStringUTF(env,dumpfn); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + int rst = g_digit->picrst(s_pic.c_str(),(int*)boxData,index,s_dump.c_str()); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "picrst %d",rst); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_netrstpic(JNIEnv* env, jobject thiz,jstring picfile, jintArray arrbox, jint index,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_dump = getStringUTF(env,dumpfn); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + int rst = g_digit->netrstpic(s_pic.c_str(),(int*)boxData,index,s_dump.c_str()); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "picrst %d",rst); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_reset(JNIEnv* env, jobject thiz){ + //g_digit->reset_fps(); + //g_digit->reset_inx(); + g_digit->setSurface(NULL); + return 0; + } + + // public native boolean setOutputWindow(Surface surface); + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_setOutputWindow(JNIEnv* env, jobject thiz, jobject surface) + { + ANativeWindow* win = ANativeWindow_fromSurface(env, surface); + + __android_log_print(ANDROID_LOG_DEBUG, "ncnn", "setOutputWindow %p", win); + g_digit->setSurface(win); + //g_digit->start(); + + return 0; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_startgpg(JNIEnv *env, jobject thiz, jstring picfn,jstring gpgfn){ + std::string s_pic = getStringUTF(env,picfn); + std::string s_gpg = getStringUTF(env,gpgfn); + if(!g_gpgmat)g_gpgmat = new JMat(); + int rst = g_gpgmat->loadjpg(s_pic); + if(rst)return rst; + rst = g_gpgmat->savegpg(s_gpg); + return rst; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_processmd5(JNIEnv *env, jobject thiz, jint kind,jstring infn,jstring outfn){ + std::string s_in = getStringUTF(env,infn); + std::string s_out = getStringUTF(env,outfn); + int rst = mainenc(kind,(char*)s_in.c_str(),(char*)s_out.c_str()); + return rst; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_stopgpg(JNIEnv *env, jobject thiz){ + if(g_gpgmat){ + delete g_gpgmat; + g_gpgmat = NULL; + } + return 0; + } +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa6f3fc9ba88e9ac8f68108817cda9ca54c6b23c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.cpp @@ -0,0 +1,384 @@ +#include +#include "JniHelper.h" +#include "Log.h" + +#define TAG "JniHelper" + +using namespace std; + +JavaVM *JniHelper::sJavaVM = nullptr; + +JNIEnv *JniHelper::getJNIEnv() { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return nullptr; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } + + return env; +} + +bool JniHelper::attachCurrentThread() { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return false; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } else { + attached = true; + } + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + return attached; +} + +void JniHelper::detachCurrentThread() { + sJavaVM->DetachCurrentThread(); +} + +void JniHelper::throwException(JNIEnv *env, const char *className, const char *msg) { + jclass exception = env->FindClass(className); + env->ThrowNew(exception, msg); +} + +jstring JniHelper::newStringUTF(JNIEnv *env, const char *data) { + if (!data) return nullptr; + jstring str = nullptr; + int size = strlen(data); + jbyteArray array = env->NewByteArray(size); + if (!array) { // OutOfMemoryError exception has already been thrown. + LOGE(TAG, "convertString: OutOfMemoryError is thrown."); + } else { + env->SetByteArrayRegion(array, 0, size, (jbyte *) data); + jclass string_Clazz = env->FindClass("java/lang/String"); + jmethodID string_initMethodID = env->GetMethodID(string_Clazz, "", + "([BLjava/lang/String;)V"); + jstring utf = env->NewStringUTF("UTF-8"); + str = (jstring) env->NewObject(string_Clazz, string_initMethodID, array, utf); + env->DeleteLocalRef(utf); + env->DeleteLocalRef(array); + } + return str; +}; + +jobject JniHelper::createByteBuffer(JNIEnv *env, unsigned char *buffer, int size) { + if (env == nullptr || buffer == nullptr) { + return nullptr; + } + + jobject byteBuffer = env->NewDirectByteBuffer(buffer, size); + //byteBuffer = env->NewGlobalRef(byteBuffer); + + return byteBuffer; +} + +jobject JniHelper::createByteBuffer(JNIEnv *env, int size) { + if (env == nullptr) { + return nullptr; + } + + auto buffer = static_cast(malloc(static_cast(size))); + jobject byteBuffer = env->NewDirectByteBuffer(buffer, size); + free(buffer); + return byteBuffer; +} + +void JniHelper::deleteLocalRef(jobject jobj) { + JNIEnv *env = JniHelper::getJNIEnv(); + if (env == nullptr || jobj == nullptr) { + return; + } + + env->DeleteLocalRef(jobj); +} + +string JniHelper::getStringUTF(JNIEnv *env, jstring obj) { + char *c_str = (char *) env->GetStringUTFChars(obj, nullptr); + string tmpString = std::string(c_str); + env->ReleaseStringUTFChars(obj, c_str); + return tmpString; +} + +char *JniHelper::getCharArrayUTF(JNIEnv *env, jstring obj) { + char *c_str = (char *) env->GetStringUTFChars(obj, nullptr); + env->ReleaseStringUTFChars(obj, c_str); + return c_str; +} + +void JniHelper::callVoidMethod(jobject obj, jmethodID methodId) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + if (env != nullptr) { + env->CallVoidMethod(obj, methodId); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } +} + +void JniHelper::callVoidMethod(jobject obj, jmethodID methodId, jint arg1, jint arg2, jint arg3, jint arg4) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + if (env != nullptr) { + env->CallVoidMethod(obj, methodId, arg1, arg2, arg3, arg4); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } +} + +void +JniHelper::callVoidMethod(jobject obj, jmethodID methodId, jint arg1, jint arg2, jint arg3, + jstring arg4, jstring arg5, jobject arg6) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + if (env != nullptr) { + env->CallVoidMethod(obj, methodId, arg1, arg2, arg3, arg4, arg5, arg6); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } +} + +int JniHelper::callIntMethod(jobject obj, jmethodID methodId, jobject arg1, jint arg2) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return -1; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + int ret = -1; + if (env != nullptr) { + ret = env->CallIntMethod(obj, methodId, arg1, arg2); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } + + return ret; +} + + +void JniHelper::callStaticVoidMethod(jclass cls, jmethodID methodId, jint arg1) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + if (env != nullptr) { + env->CallStaticVoidMethod(cls, methodId, arg1); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } +} + +jobject JniHelper::callObjectMethod(jobject obj, jmethodID methodId) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return nullptr; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + jobject ret = nullptr; + if (env != nullptr) { + ret = env->CallObjectMethod(obj, methodId); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } + + return ret; +} + +jboolean JniHelper::callBooleanMethod(jobject obj, jmethodID methodId) { + if (sJavaVM == nullptr) { + LOGE(TAG, "sJavaVM is nullptr"); + return false; + } + + JNIEnv *env = nullptr; + bool attached = false; + switch (sJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4)) { + case JNI_OK: + break; + case JNI_EDETACHED: + if (sJavaVM->AttachCurrentThread(&env, nullptr) != 0) { + LOGE(TAG, "Could not attach current thread"); + } + attached = true; + break; + case JNI_EVERSION: + LOGE(TAG, "Invalid java version"); + break; + default: + break; + } + + jboolean ret; + if (env != nullptr) { + ret = env->CallBooleanMethod(obj, methodId); + } + + if (attached) { + sJavaVM->DetachCurrentThread(); + } + + return ret; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..aae30f4c682d9fe53f6713d092612ffafe8bdf77 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/JniHelper.h @@ -0,0 +1,50 @@ +#ifndef GPLAYER_JNIHELPER_H +#define GPLAYER_JNIHELPER_H + +#include +#include + +using namespace std; + +class JniHelper { +public: + static JNIEnv *getJNIEnv(); + + static bool attachCurrentThread(); + + static void detachCurrentThread(); + + static void throwException(JNIEnv *env, const char *className, const char *msg); + + static jstring newStringUTF(JNIEnv *env, const char *data); + + static string getStringUTF(JNIEnv *env, jstring obj); + + static char *getCharArrayUTF(JNIEnv *env, jstring obj); + + static jobject createByteBuffer(JNIEnv *env, unsigned char *buffer, int size); + + static jobject createByteBuffer(JNIEnv *env, int size); + + static void deleteLocalRef(jobject jobj); + + static void callVoidMethod(jobject obj, jmethodID methodId); + + static void callVoidMethod(jobject obj, jmethodID methodId, jint arg1, jint arg2, jint arg3, jint arg4); + + static void callVoidMethod(jobject obj, jmethodID methodId, jint arg1, jint arg2, + jint arg3, jstring arg4, jstring arg5, jobject arg6); + + static int callIntMethod(jobject obj, jmethodID methodId, jobject arg1, jint arg2); + + static void callStaticVoidMethod(jclass cls, jmethodID methodId, jint arg1); + + static jobject callObjectMethod(jobject obj, jmethodID methodId); + + static jboolean callBooleanMethod(jobject obj, jmethodID methodId); + +public: + static JavaVM *sJavaVM; +}; + +#endif //GPLAYER_JNIHELPER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b98af6f54bfb6094aa2e336183a163929915cc0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.cpp @@ -0,0 +1,56 @@ + +#include +#include +#include "MsgcbJni.h" + +#define TAG "MediaSourceJni" + +MsgcbJni::MsgcbJni(jobject obj) { + LOGI(TAG, "create MsgcbJni"); + JNIEnv *env = JniHelper::getJNIEnv(); + msgcbJObj = env->NewGlobalRef(obj); + jclass sourceClass = env->GetObjectClass(obj); + onMessageCallbackMethod = env->GetMethodID(sourceClass, "onMessageCallback", + "(IIJLjava/lang/String;Ljava/lang/String;Ljava/lang/Object;)V"); +} + +MsgcbJni::~MsgcbJni() { + bool attach = JniHelper::attachCurrentThread(); + JNIEnv *env = JniHelper::getJNIEnv(); + if (msgcbJObj != nullptr && env) { + env->DeleteGlobalRef(msgcbJObj); + msgcbJObj = nullptr; + onMessageCallbackMethod = nullptr; + } + if (attach) { + JniHelper::detachCurrentThread(); + } + LOGE(TAG, "MsgcbJni destroyed"); +} + +void +MsgcbJni::onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2) { + onMessageCallback(msgId, arg1, arg2, msg1, msg2, (jobject)nullptr); +} + +void +MsgcbJni::onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2, jobject obj) { + if (msgcbJObj != nullptr && onMessageCallbackMethod != nullptr) { + bool attach = JniHelper::attachCurrentThread(); + + JNIEnv *env = JniHelper::getJNIEnv(); + jstring jMsg1 = msg1 ? JniHelper::newStringUTF(env, msg1) : nullptr; + jstring jMsg2 = msg2 ? JniHelper::newStringUTF(env, msg2) : nullptr; + JniHelper::callVoidMethod(msgcbJObj, onMessageCallbackMethod, msgId, arg1, arg2, jMsg1, + jMsg2, obj); + if (jMsg1) { + env->DeleteLocalRef(jMsg1); + } + if (jMsg2) { + env->DeleteLocalRef(jMsg2); + } + if (attach) { + JniHelper::detachCurrentThread(); + } + } +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.h new file mode 100644 index 0000000000000000000000000000000000000000..06c27e0117fd424ec7f87022e6b5b7e0d1f25d8d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/MsgcbJni.h @@ -0,0 +1,25 @@ +#ifndef GPLAYER_MSGCBERJNI_H +#define GPLAYER_MSGCBERJNI_H + +#include +#include +#include "CommObj.h" + + +class MsgcbJni:public MessageCb { +public: + MsgcbJni(jobject obj); + + virtual ~MsgcbJni(); + + virtual void onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2); + + virtual void onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2, jobject obj); + +private: + jobject msgcbJObj; + jmethodID onMessageCallbackMethod; +}; + + +#endif //GPLAYER_GPLAYERJNI_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/kmatarm.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/kmatarm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5cca097d66b221704aee37d2eadd80e5a61b814 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/kmatarm.cpp @@ -0,0 +1,454 @@ +#include "kmat.h" +#define __GARM__ +#ifdef __GARM__ + +#include "ppl/cv/arm/resize.h" +#include "ppl/cv/arm/convertto.h" +#include "ppl/cv/arm/split.h" +#include "ppl/cv/arm/merge.h" +#include "ppl/cv/arm/convertto.h" + +int KMat::vtacc(KMat* mat){ + float* pt0 = (float*)m_buf; + const int stride = 532*532; + uint8_t pct[stride]; + float* p0 = pt0; + float* p1 = p0+stride; + float* p2 = p1+stride; + float* psum = mat->fdata(); + float* pd = psum; + for(int k=0;k*pt++; + } + memcpy(psum,pt0,stride*sizeof(float)); + memcpy(psum+2*stride,pt0+2*stride,stride*sizeof(float)); + //float* ped = pt0+stride; + pc = pct; + p1 = pt0+stride; + pt = pmean; + //pd = ped; + for(int k=0;km_dev)return -1; + ppl::cv::arm::ResizeLinear(m_height,m_width,m_stride,(float*)m_buf, mat->m_height, mat->m_width, mat->m_stride, (float*)mat->m_buf); + return 0; +} + +int KMat::img2hwc(KMat* mat){ + if(m_dev!=mat->m_dev)return -1; + if(m_channel!=3)return -2; + float* gpu_split = (float*)mat->m_buf; + float* gpu_s0 = gpu_split ; + int line = mat->m_stride*mat->m_height; + float* gpu_s1 = gpu_split + line; + float* gpu_s2 = gpu_split + line*2; + ppl::cv::arm::Split3Channels(m_height, m_width,m_stride, (float*)m_buf, mat->m_width,gpu_s2,gpu_s1,gpu_s0); + return 0; +} + +int KMat::hwc2img(KMat* mat){ + if(m_dev!=mat->m_dev)return -1; + if(m_channel!=3)return -2; + return 0; +} + +int KMat::downzero(KMat* mat){ + if(m_dev!=mat->m_dev)return -1; + if((m_height!=mat->m_height)||(m_width!=mat->m_width))return -2; + if(!mat){ + float* dst = (float*)m_buf; + for(int k=0;k< m_height;k++){ + float* line = dst; + for(int m=0;mm_buf; + for(int k=0;k< m_height;k++){ + float* ls = src; + float* ld = dst; + for(int m=0;mm_stride; + } + } + return 0; +} + +int KMat::upzero(KMat* mat ){ + if(m_dev!=mat->m_dev)return -1; + if((m_height!=mat->m_height)||(m_width!=mat->m_width))return -2; + if(!mat){ + float* dst = (float*)m_buf; + for(int k=0;k< m_height;k++){ + float* line = dst; + for(int m=0;mm_buf; + for(int k=0;k< m_height;k++){ + float* ls = src; + float* ld = dst; + for(int m=0;mm_stride; + } + } + return 0; +} + +int KMat::filtermask(KMat* msk, KMat* mat){ + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + if(mat==nullptr){ + float* dst = (float*)m_buf; + float* mk = (float*)msk->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *line = dst; + float *mm = mk; + for (int m = 0; m < m_width; m++) { + *line = *line * (*mm); + line++; + mm++; + } + dst += m_stride; + mk += msk->m_stride; + } + }else { + for (int k = 0; k < m_height; k++) { + float *line = dst; + float *mm = mk; + for (int m = 0; m < m_width; m++) { + for(int n=0;nm_stride; + } + } + }else{ + + if(mat->width()!=msk->width()||mat->height()!=msk->height()) return -3; + + float* src = (float*)m_buf; + float* dst = (float*)mat->m_buf; + float* mk = (float*)msk->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *line = dst; + float *mm = mk; + float *ms = src; + for (int m = 0; m < m_width; m++) { + *line++ = *ms++ * (*mm++); + } + dst += mat->m_stride; + src += m_stride; + mk += msk->m_stride; + } + }else{ + for (int k = 0; k < m_height; k++) { + float *line = dst; + float *mm = mk; + float *ms = src; + for (int m = 0; m < m_width; m++) { + for(int n=0;nm_stride; + src += m_stride; + mk += msk->m_stride; + } + } + } + return 0; +} + +int KMat::clamp(float minval,float maxval,KMat* mat){ + if(!mat){ + float* dst = (float*)m_buf; + for(int k=0;k< m_height;k++){ + float* line = dst; + for(int m=0;mmaxval){ + *line = maxval; + } + line++; + } + dst+=m_stride; + } + }else{ + float* src = (float*)m_buf; + float* dst = (float*)mat->m_buf; + for(int k=0;k< m_height;k++){ + float* ls = src; + float* ld = dst; + for(int m=0;mmaxval){ + *ls = maxval; + }else{ + *ld = *ls; + } + *ld++ = *ls++; + } + src+= m_stride; + dst+= mat->m_stride; + } + } + return 0; +} + +int KMat::blend(KMat* msk,KMat* bgmat,KMat* dstmat){ + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + if(dstmat==nullptr){ + float* dst = (float*)m_buf; + float* mk = (float*)msk->m_buf; + float* bg = (float*)bgmat->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + *dd = *dd * ratio + *bb*(1-ratio); + dd++; mm++; bb++; + } + dst += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + }else { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + for(int n=0;nm_stride; + bg += bgmat->m_stride; + } + } + }else{ + if(dstmat->width()!=msk->width()||dstmat->height()!=msk->height()) return -3; + + float* src = (float*)m_buf; + float* dst = (float*)dstmat->m_buf; + float* mk = (float*)msk->m_buf; + float* bg = (float*)bgmat->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + //float *ss = src; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + *dd = *dd * ratio + *bb*(1-ratio); + dd++; mm++; bb++; + } + dst += dstmat->m_stride; + src += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + }else{ + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + //float *ss = src; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + for(int n=0;nm_stride; + src += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + } + } + return 0; +} + +int KMat::wherezero(KMat* msk, KMat* bgmat, KMat* dstmat){ + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + if(dstmat==nullptr){ + float* dst = (float*)m_buf; + float* mk = (float*)msk->m_buf; + + float* bg = (float*)bgmat->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + *dd = ratio==0?*dd:*bb; + dd++; mm++; bb++; + } + dst += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + }else { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + for(int n=0;nm_stride; + bg += bgmat->m_stride; + } + } + }else{ + if(dstmat->width()!=msk->width()||dstmat->height()!=msk->height()) return -3; + + float* src = (float*)m_buf; + float* dst = (float*)dstmat->m_buf; + float* mk = (float*)msk->m_buf; + float* bg = (float*)bgmat->m_buf; + if(msk->m_channel==3) { + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + //float *ss = src; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + *dd = ratio==0?*dd:*bb; + dd++; mm++; bb++; + } + dst += dstmat->m_stride; + src += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + }else{ + for (int k = 0; k < m_height; k++) { + float *dd = dst; + float *mm = mk; + //float *ss = src; + float *bb = bg; + for (int m = 0; m < m_width; m++) { + float ratio = *mm; + for(int n=0;nm_stride; + src += m_stride; + mk += msk->m_stride; + bg += bgmat->m_stride; + } + } + } + return 0; +} + +int KMat::cvtfloat(KMat* dst,float scale,float delta){ + ppl::cv::arm::ConvertTo(m_height,m_width,m_stride,(uint8_t*)m_buf + ,m_width*m_channel,(float*)m_buf,scale,delta); + return 0; +} + +int KMat::cvtuint8(KMat* dst,float scale,float delta){ + ppl::cv::arm::ConvertTo(m_height,m_width,m_stride,(float*)m_buf ,m_width*m_channel,(uint8_t*)m_buf,scale,delta); + return 0; +} + +void KMat::initgh(){ + m_dev = 0; +} + +KMat::KMat(int w,int h,float *buf ,int c ,int d ):JMat(w,h,buf,c,d){ + // +} + +KMat::KMat(int w,int h,uint8_t *buf ,int c ,int d ):JMat(w,h,buf,c,d){ + // +} + +KMat::KMat(int w,int h,int c ,int d ,int b):JMat(w,h,c,d,b){ +} + + +KMat::~KMat(){ + // +} + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..747c984b9526bcffc2d6cf1ccd58782a72ad8189 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.cpp @@ -0,0 +1,105 @@ +#include "ndkvid.h" + +void MyVideo::reset(){ + renderstart = -1; + sawInputEOS = false; + sawOutputEOS = false; + isPlaying = false; + renderonce = true; +} + +MyVideo::MyVideo(const char* videofile){ + int len = strlen(videofile); + memcpy(filename,videofile,len+1); + reset(); +} + +MyVideo::~MyVideo(){ +} + +int MyVideo::open(){ + ex = AMediaExtractor_new(); + media_status_t err = AMediaExtractor_setDataSource( ex, filename); + if (err != AMEDIA_OK) return -2; + int numtracks = AMediaExtractor_getTrackCount(ex); + for (int i = 0; i < numtracks; i++) { + AMediaFormat *format = AMediaExtractor_getTrackFormat(ex, i); + const char *s = AMediaFormat_toString(format); + const char *mime; + if (!AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime)) { + return -3; + } else if (!strncmp(mime, "video/", 6)) { + AMediaExtractor_selectTrack(ex, i); + + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_FRAME_RATE, &frameRate) ; + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &frameWidth) ; + AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &frameHeight) ; + int64_t dur = 0; + AMediaFormat_getInt64(format, AMEDIAFORMAT_KEY_DURATION, &dur) ; + duration = dur; + codec = AMediaCodec_createDecoderByType(mime); + isPlaying = true; + //AMediaCodec_configure(codec, format, texture->getRenderWindow(), NULL, 0); + AMediaCodec_start(codec); + } + AMediaFormat_delete(format); + } + return 0; +} + +int MyVideo::close(){ + AMediaCodec_stop(codec); + AMediaCodec_delete(codec); + AMediaExtractor_delete(ex); + sawInputEOS = true; + sawOutputEOS = true; + return 0; +} + +int MyVideo::next(JMat* mat){ + size_t outsize = 0; + ssize_t bufidx = -1; + int64_t presentationTimeUs = -1; + while(!sawInputEOS || !sawOutputEOS){ + if(!sawInputEOS){ + bufidx = AMediaCodec_dequeueInputBuffer(codec, 0); + if (bufidx >= 0) { + size_t bufsize; + auto buf = AMediaCodec_getInputBuffer(codec, bufidx, &bufsize); + auto sampleSize = AMediaExtractor_readSampleData(ex, buf, bufsize); + if (sampleSize < 0) { + sampleSize = 0; + sawInputEOS = true; + isPlaying = false; + } + presentationTimeUs = AMediaExtractor_getSampleTime(ex); + AMediaCodec_queueInputBuffer( codec, bufidx, 0, sampleSize, presentationTimeUs, sawInputEOS ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0); + AMediaExtractor_advance(ex); + } + } + if (!sawOutputEOS) { + AMediaCodecBufferInfo info; + bufidx = AMediaCodec_dequeueOutputBuffer(codec, &info, 0); + if (bufidx >= 0) { + if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) { + sawOutputEOS = true; + isPlaying = false; + } + position = presentationTimeUs; + if(mat){ + uint8_t* output = AMediaCodec_getOutputBuffer(codec, bufidx, &outsize); + if(outsize>0){ + memcpy(mat->data(),output,outsize); + } + } + // + AMediaCodec_releaseOutputBuffer(codec, bufidx, false); + break; + } else if (bufidx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { + auto format = AMediaCodec_getOutputFormat(codec); + AMediaFormat_delete(format); + } + } + } + return outsize; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.h new file mode 100644 index 0000000000000000000000000000000000000000..9499598d1c89e2a458c5d2c762fd65f5afb65722 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkvid.h @@ -0,0 +1,49 @@ +#pragma once +#include +#include +#include "jmat.h" +#include +#include +#include +#include +#define FRAME_DIST 40000 + +class MyVideo { + private: + + char filename[1024]; + + int32_t frameHeight = 0; + int32_t frameWidth = 0; + int32_t frameRate = 0; + int32_t duration = 0; + int32_t position = 0; + + int64_t renderstart; + bool sawInputEOS = false; + bool sawOutputEOS = false; + bool isPlaying = false; + bool renderonce = true; + + AMediaExtractor *ex = nullptr; + AMediaCodec *codec = nullptr; + + void indexsample(long time); + void reset(); + int pre(); + public: + int32_t getFrameHeight() const{return frameHeight;}; + int32_t getFrameWidth() const{return frameWidth;}; + int32_t getDuration() const{return duration;}; + int32_t getPosition() const{return position;}; + bool isEof(){return sawOutputEOS||sawInputEOS ;}; + bool getPlaying(){return isPlaying ;}; + + int open(); + int close(); + + int next(JMat* mat); + + MyVideo(const char* videofile); + ~MyVideo(); +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe576300f2c9f765b925a039e15722f2161f81af --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.cpp @@ -0,0 +1,412 @@ +#include "ndkwin.h" + +MyDisp::MyDisp(){ + sensor_manager = 0; + sensor_event_queue = 0; + accelerometer_sensor = 0; + win = 0; + accelerometer_orientation = 0; + sensor_manager = ASensorManager_getInstance(); + accelerometer_sensor = ASensorManager_getDefaultSensor(sensor_manager, ASENSOR_TYPE_ACCELEROMETER); +} + +MyDisp::~MyDisp(){ + if (accelerometer_sensor) + { + ASensorEventQueue_disableSensor(sensor_event_queue, accelerometer_sensor); + accelerometer_sensor = 0; + } + + if (sensor_event_queue) + { + ASensorManager_destroyEventQueue(sensor_manager, sensor_event_queue); + sensor_event_queue = 0; + } + if (win) { + ANativeWindow_release(win); + } +} + +int MyDisp::draw_text(cv::Mat& rgb,const char* text) +{ + //const char text[] = "unsupported"; + + int baseLine = 0; + cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 1.0, 1, &baseLine); + + int y = (rgb.rows - label_size.height) / 10; + int x = (rgb.cols - label_size.width) / 10; + + cv::rectangle(rgb, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), + cv::Scalar(255, 255, 255), -1); + + cv::putText(rgb, text, cv::Point(x, y + label_size.height), + cv::FONT_HERSHEY_SIMPLEX, 1.0, cv::Scalar(0, 0, 0)); + + return 0; +} + +static double t0 = 0.f; +static float fps_history[10] = {0.f}; +int MyDisp::reset_fps(){ + t0 = 0; + memset(fps_history,0,10*sizeof(float)); + return 0; +} + +int MyDisp::draw_fps(cv::Mat& rgb) +{ + // resolve moving average + float avg_fps = 0.f; + { + + double t1 = ncnn::get_current_time(); + if (t0 == 0.f) + { + t0 = t1; + return 0; + } + + float fps = 1000.f / (t1 - t0); + t0 = t1; + + for (int i = 9; i >= 1; i--) + { + fps_history[i] = fps_history[i - 1]; + } + fps_history[0] = fps; + + if (fps_history[9] == 0.f) + { + return 0; + } + + for (int i = 0; i < 10; i++) + { + avg_fps += fps_history[i]; + } + avg_fps /= 10.f; + } + + char text[32]; + sprintf(text, "FPS=%.2f", avg_fps); + + int baseLine = 0; + cv::Size label_size = cv::getTextSize(text, cv::FONT_HERSHEY_SIMPLEX, 0.5, 1, &baseLine); + + int y = 0; + int x = rgb.cols - label_size.width; + + cv::rectangle(rgb, cv::Rect(cv::Point(x, y), cv::Size(label_size.width, label_size.height + baseLine)), + cv::Scalar(255, 255, 255), -1); + + cv::putText(rgb, text, cv::Point(x, y + label_size.height), + cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0)); + + return 0; +} + +static const int NDKCAMERAWINDOW_ID = 233; +int MyDisp::drawMat(JMat* mat,const char* text){ + if(win==NULL)return 0; + //__android_log_print(ANDROID_LOG_WARN, "tooken", "drawmat"); + int nv21_width = mat->width(); + int nv21_height = mat->height(); + int camera_orientation = 0; + int camera_facing = 0; + // resolve orientation from camera_orientation and accelerometer_sensor + { + if (!sensor_event_queue) + { + sensor_event_queue = ASensorManager_createEventQueue(sensor_manager, ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS), NDKCAMERAWINDOW_ID, 0, 0); + + ASensorEventQueue_enableSensor(sensor_event_queue, accelerometer_sensor); + } + + int id = ALooper_pollAll(0, 0, 0, 0); + if (id == NDKCAMERAWINDOW_ID) + { + ASensorEvent e[8]; + ssize_t num_event = 0; + while (ASensorEventQueue_hasEvents(sensor_event_queue) == 1) + { + num_event = ASensorEventQueue_getEvents(sensor_event_queue, e, 8); + if (num_event < 0) + break; + } + + if (num_event > 0) + { + float acceleration_x = e[num_event - 1].acceleration.x; + float acceleration_y = e[num_event - 1].acceleration.y; + float acceleration_z = e[num_event - 1].acceleration.z; +// __android_log_print(ANDROID_LOG_WARN, "NdkCameraWindow", "x = %f, y = %f, z = %f", x, y, z); + + if (acceleration_y > 7) + { + accelerometer_orientation = 0; + } + if (acceleration_x < -7) + { + accelerometer_orientation = 90; + } + if (acceleration_y < -7) + { + accelerometer_orientation = 180; + } + if (acceleration_x > 7) + { + accelerometer_orientation = 270; + } + } + } + } + int nv21_roi_x = 0; + int nv21_roi_y = 0; + int nv21_roi_w = 0; + int nv21_roi_h = 0; + int roi_x = 0; + int roi_y = 0; + int roi_w = 0; + int roi_h = 0; + int rotate_type = 0; + int render_w = 0; + int render_h = 0; + int render_rotate_type = 0; + { + int win_w = ANativeWindow_getWidth(win); + int win_h = ANativeWindow_getHeight(win); + + if (accelerometer_orientation == 90 || accelerometer_orientation == 270) + { + std::swap(win_w, win_h); + } + + const int final_orientation = (camera_orientation + accelerometer_orientation) % 360; + + if (final_orientation == 0 || final_orientation == 180) + { + if (win_w * nv21_height > win_h * nv21_width) + { + roi_w = nv21_width; + roi_h = (nv21_width * win_h / win_w) / 2 * 2; + roi_x = 0; + roi_y = ((nv21_height - roi_h) / 2) / 2 * 2; + } + else + { + roi_h = nv21_height; + roi_w = (nv21_height * win_w / win_h) / 2 * 2; + roi_x = ((nv21_width - roi_w) / 2) / 2 * 2; + roi_y = 0; + } + + nv21_roi_x = roi_x; + nv21_roi_y = roi_y; + nv21_roi_w = roi_w; + nv21_roi_h = roi_h; + } + if (final_orientation == 90 || final_orientation == 270) + { + if (win_w * nv21_width > win_h * nv21_height) + { + roi_w = nv21_height; + roi_h = (nv21_height * win_h / win_w) / 2 * 2; + roi_x = 0; + roi_y = ((nv21_width - roi_h) / 2) / 2 * 2; + } + else + { + roi_h = nv21_width; + roi_w = (nv21_width * win_w / win_h) / 2 * 2; + roi_x = ((nv21_height - roi_w) / 2) / 2 * 2; + roi_y = 0; + } + + nv21_roi_x = roi_y; + nv21_roi_y = roi_x; + nv21_roi_w = roi_h; + nv21_roi_h = roi_w; + } + + if (camera_facing == 0) + { + if (camera_orientation == 0 && accelerometer_orientation == 0) + { + rotate_type = 2; + } + if (camera_orientation == 0 && accelerometer_orientation == 90) + { + rotate_type = 7; + } + if (camera_orientation == 0 && accelerometer_orientation == 180) + { + rotate_type = 4; + } + if (camera_orientation == 0 && accelerometer_orientation == 270) + { + rotate_type = 5; + } + if (camera_orientation == 90 && accelerometer_orientation == 0) + { + rotate_type = 5; + } + if (camera_orientation == 90 && accelerometer_orientation == 90) + { + rotate_type = 2; + } + if (camera_orientation == 90 && accelerometer_orientation == 180) + { + rotate_type = 7; + } + if (camera_orientation == 90 && accelerometer_orientation == 270) + { + rotate_type = 4; + } + if (camera_orientation == 180 && accelerometer_orientation == 0) + { + rotate_type = 4; + } + if (camera_orientation == 180 && accelerometer_orientation == 90) + { + rotate_type = 5; + } + if (camera_orientation == 180 && accelerometer_orientation == 180) + { + rotate_type = 2; + } + if (camera_orientation == 180 && accelerometer_orientation == 270) + { + rotate_type = 7; + } + if (camera_orientation == 270 && accelerometer_orientation == 0) + { + rotate_type = 7; + } + if (camera_orientation == 270 && accelerometer_orientation == 90) + { + rotate_type = 4; + } + if (camera_orientation == 270 && accelerometer_orientation == 180) + { + rotate_type = 5; + } + if (camera_orientation == 270 && accelerometer_orientation == 270) + { + rotate_type = 2; + } + } + else + { + if (final_orientation == 0) + { + rotate_type = 1; + } + if (final_orientation == 90) + { + rotate_type = 6; + } + if (final_orientation == 180) + { + rotate_type = 3; + } + if (final_orientation == 270) + { + rotate_type = 8; + } + } + + if (accelerometer_orientation == 0) + { + render_w = roi_w; + render_h = roi_h; + render_rotate_type = 1; + } + if (accelerometer_orientation == 90) + { + render_w = roi_h; + render_h = roi_w; + render_rotate_type = 8; + } + if (accelerometer_orientation == 180) + { + render_w = roi_w; + render_h = roi_h; + render_rotate_type = 3; + } + if (accelerometer_orientation == 270) + { + render_w = roi_h; + render_h = roi_w; + render_rotate_type = 6; + } + } + + + cv::Mat rgb; + cv::resize(mat->cvmat(),rgb,cv::Size(roi_w,roi_h),cv::INTER_LINEAR); + draw_fps(rgb); + if(text) draw_text(rgb,text); + cv::Mat rgb_render(render_h, render_w, CV_8UC3); + ncnn::kanna_rotate_c3(rgb.data, roi_w, roi_h, rgb_render.data, render_w, render_h, render_rotate_type); + ANativeWindow_setBuffersGeometry(win, render_w, render_h, AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM); + ANativeWindow_Buffer buf; + ANativeWindow_lock(win, &buf, NULL); + + //__android_log_print(ANDROID_LOG_WARN, "tooken", "drawbuf"); + // scale to target size + if (buf.format == AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM || buf.format == AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM) + { + for (int y = 0; y < render_h; y++) + { + const unsigned char* ptr = rgb_render.ptr(y); + unsigned char* outptr = (unsigned char*)buf.bits + buf.stride * 4 * y; + + int x = 0; +#if __ARM_NEON + for (; x + 7 < render_w; x += 8) + { + uint8x8x3_t _rgb = vld3_u8(ptr); + uint8x8x4_t _rgba; + //_rgba.val[0] = _rgb.val[0]; + //_rgba.val[1] = _rgb.val[1]; + //_rgba.val[2] = _rgb.val[2]; + _rgba.val[0] = _rgb.val[2]; + _rgba.val[1] = _rgb.val[1]; + _rgba.val[2] = _rgb.val[0]; + _rgba.val[3] = vdup_n_u8(255); + vst4_u8(outptr, _rgba); + + ptr += 24; + outptr += 32; + } +#endif // __ARM_NEON + for (; x < render_w; x++) + { + //outptr[0] = ptr[0]; + //outptr[1] = ptr[1]; + //outptr[2] = ptr[2]; + outptr[0] = ptr[2]; + outptr[1] = ptr[1]; + outptr[2] = ptr[0]; + outptr[3] = 255; + + ptr += 3; + outptr += 4; + } + } + } + + ANativeWindow_unlockAndPost(win); + + return 0; +} + +int MyDisp::set_window( ANativeWindow* newwin){ + if (win) { + ANativeWindow_release(win); + } + win = newwin; + if(win) ANativeWindow_acquire(win); + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.h new file mode 100644 index 0000000000000000000000000000000000000000..d78c6529cb5a7da9f5d1595fa18cae1a66311227 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/ndkwin.h @@ -0,0 +1,30 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include "mat.h" +#include "jmat.h" +#include "benchmark.h" + +class MyDisp { + private: + ANativeWindow *win = nullptr; + ASensorManager* sensor_manager; + mutable ASensorEventQueue* sensor_event_queue; + const ASensor* accelerometer_sensor; + int draw_text(cv::Mat& rgb,const char* text); + int draw_fps(cv::Mat& rgb); + public: + mutable int accelerometer_orientation; + int drawMat(JMat* mat,const char* text); + MyDisp(); + virtual ~MyDisp(); + int set_window( ANativeWindow* newwin); + int reset_fps(); +}; + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dbfabdb116f1d155a11d16ef647c29eeaefb4b9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.cpp @@ -0,0 +1,428 @@ +#include +#include +#include + +#include + +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include "scrfdncnn.h" + + + +#if __ARM_NEON +#include +#endif // __ARM_NEON + + +int MyDigit::checkfile(char* fn){ + return 0; +} + +int MyDigit::reset_inx(){ + inx_wenet = 0; + return 0; +} + +int MyDigit::picrst(const char* picfn,int* box,int index,const char* dumpfn){ + if(!inited)return -999; + if(!mat_wenet)return -1; + if(index<0)return -2; + if(index>=cnt_wenet)return -3; + std::string picfile(picfn); + JMat onepic(picfile,1); + int* arr = onepic.tagarr(); + arr[10] = box[0]; + arr[11] = box[1]; + arr[12] = box[2]; + arr[13] = box[3]; + // + float* pwenet = ai_wenet->nextbnf(mat_wenet,index); + if(!pwenet){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%d index error",index); + return -1; + } + JMat feat(256, 20, pwenet, 1); + //int* arr = onepic.tagarr(); + double t0 = ncnn::get_current_time(); + ai_munet->process(&onepic, arr, &feat); + double t1 = ncnn::get_current_time(); + char text[1024]; + float dist = t1-t0; + sprintf(text,"%d unet %f",index,dist); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + drawMat(&onepic,text); + if(strlen(dumpfn)){ + onepic.tojpg(dumpfn); + } + return 0; +} + +int MyDigit::netrstpic(const char* picfn,int* box,int index,const char* dumpfn){ + if(!inited)return -999; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>net_wavmat->bnfblocks())return -3; + std::string picfile(picfn); + JMat onepic(picfile,1); + int* arr = onepic.tagarr(); + arr[10] = box[0]; + arr[11] = box[1]; + arr[12] = box[2]; + arr[13] = box[3]; + // + JMat* mw = net_wavmat->bnfmat(); + int* marr = mw->tagarr(); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "arr %d %d %d %d %d %d %d",marr[0],marr[1],marr[2],marr[3],marr[4],marr[5],marr[6]); + float* pwenet = ai_wenet->nextbnf(mw,index); + if(!pwenet){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%d index error",index); + return -1; + } + JMat feat(256, 20, pwenet, 1); + //int* arr = onepic.tagarr(); + double t0 = ncnn::get_current_time(); + ai_munet->process(&onepic, arr, &feat); + double t1 = ncnn::get_current_time(); + char text[1024]; + float dist = t1-t0; + sprintf(text,"%d unet %f",index,dist); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + drawMat(&onepic,text); + if(strlen(dumpfn)){ + onepic.tojpg(dumpfn); + } + return 0; +} + +int MyDigit::netrst(int index,const char* dumpfn){ + if(!inited)return -999; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>net_wavmat->bnfblocks())return -3; + JMat onepic = mat_pic->clone(); + JMat* mw = net_wavmat->bnfmat(); + float* pwenet = ai_wenet->nextbnf(mw,index); + if(!pwenet){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%d index error",index); + return -1; + } + //float* pd = pwenet+256*20*index; + JMat feat(256, 20, pwenet, 1); + int* arr = mat_pic->tagarr(); + double t0 = ncnn::get_current_time(); + ai_munet->process(&onepic, arr, &feat); + double t1 = ncnn::get_current_time(); + char text[1024]; + float dist = t1-t0; + sprintf(text,"%d unet %f",index,dist); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + drawMat(&onepic,text); + if(strlen(dumpfn)){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + onepic.tojpg(dumpfn); + } + return 0; +} + +int MyDigit::newrst(int index,const char* dumpfn){ + if(!inited)return -999; + if(!mat_wenet)return -1; + if(index<0)return -2; + if(index>=cnt_wenet)return -3; + if(!mat_pic)return -4; + JMat onepic = mat_pic->clone(); + float* pwenet = ai_wenet->nextbnf(mat_wenet,index); + if(!pwenet){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%d index error",index); + return -1; + } + //float* pd = pwenet+256*20*index; + JMat feat(256, 20, pwenet, 1); + int* arr = mat_pic->tagarr(); + double t0 = ncnn::get_current_time(); + ai_munet->process(&onepic, arr, &feat); + double t1 = ncnn::get_current_time(); + char text[1024]; + float dist = t1-t0; + sprintf(text,"%d unet %f",index,dist); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + drawMat(&onepic,text); + if(strlen(dumpfn)){ + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s dump %s",text,dumpfn); + onepic.tojpg(dumpfn); + } + return 0; +} + +int MyDigit::drawpic(const char* picfn){ + if(!inited)return -999; + std::string picfile(picfn); + JMat mat(picfile,1); + // + drawMat(&mat,NULL); + return 0; +} + +int MyDigit::newpic(const char* picfn,const char* dumpbox){ + if(!inited)return -999; + if(mat_pic){ + delete mat_pic; + mat_pic = nullptr; + } + std::string picfile(picfn); + mat_pic = new JMat(picfile,1); + int* arr = mat_pic->tagarr(); + double t0 = ncnn::get_current_time(); + ai_scrfd->detect(mat_pic,arr); + double t1 = ncnn::get_current_time(); + if((arr[0]<=0)||(arr[1]<=0))return -1; + int* apts = arr+64; + ai_pfpld->detect(mat_pic,arr,apts); + double t2 = ncnn::get_current_time(); + char text[1024]; + float dist1 = t1-t0; + float dist2 = t2-t1; + sprintf(text,"%s scrfd %f pfpld %f",picfn,dist1,dist2); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s",text); + drawMat(mat_pic,text); + if(apts[0]<=0)return -2; + if(strlen(dumpbox)){ + FILE* file = fopen(dumpbox, "w"); + if(file){ + fprintf(file,"face w %d h %d\n",arr[0],arr[1]); + int* box = arr+2; + fprintf(file,"orig box x1y1 %d %d x2y2 %d %d\n",box[0],box[1],box[2],box[3]); + box = arr+6; + fprintf(file,"scrfd box x1y1 %d %d x2y2 %d %d\n",box[0],box[1],box[2],box[3]); + box = arr+10; + fprintf(file,"pfpld box x1y1 %d %d x2y2 %d %d\n",box[0],box[1],box[2],box[3]); + fclose(file); + } + } + return 0; +} + +int MyDigit::netwav(const char* url,float duration){ + if(!inited)return -999; + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "netwav %s",url); + if(net_curl){ + net_curl->cancel(); + delete net_curl; + net_curl = nullptr; + } + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "netwav gogogo"); + if(net_wavmat){ + delete net_wavmat; + net_wavmat = nullptr; + } + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "netwav %f",duration); + net_wavmat = new KWav(duration); + net_curl = new NetCurl((char*)url,duration,net_wavmat); + for(int k=0;k<20;k++){ + if(net_curl->checked())break; + usleep(100000); + } + int rst = net_wavmat->bnfblocks();//net_curl->checked(); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "netwav %d",rst); + return rst; +} + +int MyDigit::newwav(const char* wavfn,const char* dumpfn){ + if(!inited)return -999; + if(mat_wenet){ + delete mat_wenet; + mat_wenet = nullptr; + } + double t0 = ncnn::get_current_time(); + int rst = ai_wenet->nextwav(wavfn,&mat_wenet); + cnt_wenet = rst; + double t1 = ncnn::get_current_time(); + JMat mat(640,480,CV_8UC3); + char text[1024]; + float dist = t1-t0; + sprintf(text,"%s wenet %f",wavfn,dist); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s",text); + //drawMat(&mat,text); + if(strlen(dumpfn)){ + mat_wenet->tobin(dumpfn); + } + if(!mat_wenet)return -1; + inx_wenet = 0; + return rst; +} + +int MyDigit::initModel(const char* modeldir){ + if(inited)return 0; + guiji_curl_init(modeldir); + double t0 = ncnn::get_current_time(); + ai_wenet = new Wenet(modeldir,"wenet"); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "init wenet"); + double t1 = ncnn::get_current_time(); + ai_scrfd = new Scrfd(modeldir,"scrfd_500m_kps-opt2",1080,1920); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "init scrfd"); + double t2 = ncnn::get_current_time(); + ai_pfpld = new Pfpld(modeldir,"pfpld",1080,1920); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "init pfpld"); + double t3 = ncnn::get_current_time(); + ai_munet = new Mobunet(modeldir,"mobileunet_v5_wenet_sim"); + double t4 = ncnn::get_current_time(); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "init munet"); + JMat mat(640,480,CV_8UC3); + char text[1024]; + float da = t1-t0; + float db = t2-t1; + float dc = t3-t2; + float dd = t4-t3; + sprintf(text,"%s model wenet %f scrfd %f pfpld %f unet %f",modeldir,da,db,dc,dd); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "%s",text); + drawMat(&mat,text); + // + init_wenetloop(ai_wenet); + inited = true; + return 0; +} + +MyDigit::MyDigit(){ +} + +MyDigit::~MyDigit(){ + if(inited){ + final_wenetloop(); + if(mat_wenet){ + delete mat_wenet; + mat_wenet = nullptr; + } + if(net_curl){ + delete net_curl; + net_curl = nullptr; + } + if(net_wavmat){ + delete net_wavmat; + net_wavmat = nullptr; + } + delete ai_wenet; + delete ai_scrfd; + delete ai_pfpld; + delete ai_munet; + } +} + +static MyDigit* g_digit = 0; + +extern "C" { + + JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) { + __android_log_print(ANDROID_LOG_DEBUG, "ncnn", "JNI_OnLoad"); + + g_digit = new MyDigit; + + return JNI_VERSION_1_4; + } + + JNIEXPORT void JNI_OnUnload(JavaVM *vm, void *reserved) { + __android_log_print(ANDROID_LOG_DEBUG, "ncnn", "JNI_OnUnload"); + + delete g_digit; + g_digit = 0; + } + + static std::string getStringUTF(JNIEnv *env, jstring obj) { + char *c_str = (char *) env->GetStringUTFChars(obj, nullptr); + std::string tmpString = std::string(c_str); + env->ReleaseStringUTFChars(obj, c_str); + return tmpString; + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_initModel(JNIEnv *env, jobject thiz, jstring path){ + std::string str = getStringUTF(env,path); + return g_digit->initModel(str.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_onewav(JNIEnv *env, jobject thiz, jstring wavfn,jstring dumpfn){ + std::string s_wav = getStringUTF(env,wavfn); + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newwav(s_wav.c_str(),s_dump.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_netwav(JNIEnv *env, jobject thiz, jstring wavurl,jfloat duration){ + std::string s_wav = getStringUTF(env,wavurl); + return g_digit->netwav(s_wav.c_str(),duration); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_onepic(JNIEnv *env, jobject thiz, jstring picfn,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfn); + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newpic(s_pic.c_str(),s_dump.c_str()); + } + + JNIEXPORT jint JNICALL + Java_com_btows_ncnntest_SCRFDNcnn_drawpic(JNIEnv *env, jobject thiz, jstring picfn){ + std::string s_pic = getStringUTF(env,picfn); + return g_digit->drawpic(s_pic.c_str()); + } + // public native boolean openCamera(int facing); + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_onerst(JNIEnv* env, jobject thiz, jint index,jstring dumpfn) { + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->newrst(index,s_dump.c_str()); + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_netrst(JNIEnv* env, jobject thiz, jint index,jstring dumpfn) { + std::string s_dump = getStringUTF(env,dumpfn); + return g_digit->netrst(index,s_dump.c_str()); + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_picrst(JNIEnv* env, jobject thiz,jstring picfile, jintArray arrbox, jint index,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_dump = getStringUTF(env,dumpfn); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + int rst = g_digit->picrst(s_pic.c_str(),(int*)boxData,index,s_dump.c_str()); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "picrst %d",rst); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_netrstpic(JNIEnv* env, jobject thiz,jstring picfile, jintArray arrbox, jint index,jstring dumpfn){ + std::string s_pic = getStringUTF(env,picfile); + std::string s_dump = getStringUTF(env,dumpfn); + jint *boxData = (jint*) env->GetIntArrayElements( arrbox, NULL); + int rst = g_digit->netrstpic(s_pic.c_str(),(int*)boxData,index,s_dump.c_str()); + __android_log_print(ANDROID_LOG_DEBUG, "tooken", "picrst %d",rst); + env->ReleaseIntArrayElements( arrbox, boxData, 0); + return rst; + } + + + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_reset(JNIEnv* env, jobject thiz){ + //g_digit->reset_fps(); + //g_digit->reset_inx(); + g_digit->set_window(NULL); + return 0; + } + + // public native boolean setOutputWindow(Surface surface); + JNIEXPORT jint JNICALL Java_com_btows_ncnntest_SCRFDNcnn_setOutputWindow(JNIEnv* env, jobject thiz, jobject surface) + { + ANativeWindow* win = ANativeWindow_fromSurface(env, surface); + + __android_log_print(ANDROID_LOG_DEBUG, "ncnn", "setOutputWindow %p", win); + + g_digit->set_window(win); + + return 0; + } + +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.h new file mode 100644 index 0000000000000000000000000000000000000000..b1123bb8ef7c1a30c65b80867f7a8b3c97224be0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/android/scrfdncnn.h @@ -0,0 +1,50 @@ +#pragma once + +#include "jmat.h" +#include "kmat.h" +#include "scrfd.h" +#include "pfpld.h" +#include "munet.h" +#include "wenet.h" +#include "utils/face_utils.h" +#include "netcurl.h" +#include "looper.h" +#include "ndkwin.h" +#include "netwav.h" +#include "netcurl.h" + +class MyDigit:public MyDisp { + private: + Scrfd* ai_scrfd = nullptr; + Pfpld* ai_pfpld = nullptr; + + Wenet* ai_wenet = nullptr; + Mobunet* ai_munet = nullptr; + + int inited = false; + JMat* mat_wenet = nullptr; + int cnt_wenet = 0; + int inx_wenet = 0; + JMat* mat_pic = nullptr; + JMat* mat_bg = nullptr; + int checkfile(char* fn); + NetCurl* net_curl = nullptr; + KWav* net_wavmat = nullptr; + public: + MyDigit(); + virtual ~MyDigit(); + int initModel(const char* modeldir); + + int netwav(const char* url,float duration); + int netrst(int index,const char* dumpfn); + int netrstpic(const char* picfn,int* box,int index,const char* dumpfn); + + int newwav(const char* wavfn,const char* dumpfn); + int newpic(const char* picfn,const char* dumpbox); + int drawpic(const char* picfn); + + int newrst(int index,const char* dumpfn); + int picrst(const char* picfn,int* box,int index,const char* dumpfn); + int reset_inx(); +}; + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..debf920dc13f78004bbb5dc25459a32bd21ef013 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.cpp @@ -0,0 +1,21 @@ +#include +#include "AudioTrack.h" + +#define TAG "AudioTrack" + +AudioTrack::AudioTrack(CommObj* obj) { + audioTrackObj = obj;// +} + +AudioTrack::~AudioTrack() = default; + +void AudioTrack::start(int sampleRate, int sampleFormat, int channels, int bytesPerSample) { + LOGI(TAG, "start %d %d %d %d", sampleRate, sampleFormat, channels, bytesPerSample); +} + +int AudioTrack::write(uint8_t *buffer, int size) { + return -1; +} + +void AudioTrack::stop() { +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.h new file mode 100644 index 0000000000000000000000000000000000000000..d6334d884873b2b269b73ed65dbc07c87264d329 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/AudioTrack.h @@ -0,0 +1,24 @@ +#ifndef GPLAYER_AUDIOTRACK_H +#define GPLAYER_AUDIOTRACK_H + +#include "CommObj.h" +#include + +class AudioTrack { +public: + AudioTrack(CommObj* obj); + + virtual ~AudioTrack(); + + void start(int sampleRate, int sampleFormat, int channels, int bytesPerSample); + + int write(uint8_t *buffer, int size); + + void stop(); + +private: + CommObj* audioTrackObj; +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1bd35ed351db8802cf12300111632ee2c7dc6bb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.cpp @@ -0,0 +1,46 @@ +#include +#include "BaseRenderHelper.h" + +BaseRenderHelper::BaseRenderHelper(FrameSource *source, MessageSource *messageSource, int mediaCodecFlag, bool hasAudio, bool hasVideo) { + this->hasAudio = hasAudio; + this->hasVideo = hasVideo; + this->messageSource = messageSource; +} + +BaseRenderHelper::~BaseRenderHelper() { +} + +void BaseRenderHelper::setNativeWindow(NativeWindowType window) { + nativeWindow = window; +} + +void BaseRenderHelper::setAudioTrack(AudioTrack *track) { +} + +void BaseRenderHelper::setVideoParams(int width, int height) { + videoWidth = width; + videoHeight = height; +} + +void BaseRenderHelper::setAudioParams(int sampleRate, int channels, int format, int bytesPerSample) { +} + +void BaseRenderHelper::initAudioRenderer() { +} + +void BaseRenderHelper::initVideoRenderer() { +} + +int BaseRenderHelper::renderAudio(int arg1, long arg2) { + return 0; +} + +int BaseRenderHelper::renderVideo(int arg1, long arg2) { + return 0; +} + +void BaseRenderHelper::releaseAudioRenderer() { +} + +void BaseRenderHelper::releaseVideoRenderer() { +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..94836d41887cd5decafb89ac720b4721f22052d1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/BaseRenderHelper.h @@ -0,0 +1,54 @@ +#ifndef GPLAYER_BASERENDERHELPER_H +#define GPLAYER_BASERENDERHELPER_H + + +#include "MessageSource.h" +#include "AudioTrack.h" +#include "FrameSource.h" + +#define USE_RENDER +#ifdef USE_RENDER +#include +#else +typedef void* NativeWindowType; +#endif + + +class BaseRenderHelper { +public: + BaseRenderHelper(FrameSource *source, MessageSource *messageSource, int mediaCodecFlag, bool hasAudio, bool hasVideo); + + virtual ~BaseRenderHelper(); + + virtual void setNativeWindow(NativeWindowType window); + + virtual void setAudioTrack(AudioTrack *track); + + virtual void setVideoParams(int width, int height); + + virtual void setAudioParams(int sampleRate, int channels, int format, int bytesPerSample); + + virtual void initAudioRenderer(); + + virtual void initVideoRenderer(); + + virtual int renderAudio(int arg1, long arg2); + + virtual int renderVideo(int arg1, long arg2); + + virtual void releaseAudioRenderer(); + + virtual void releaseVideoRenderer(); + +protected: + MessageSource *messageSource = nullptr; + NativeWindowType nativeWindow = 0; + int videoWidth = 0; + int videoHeight = 0; + + bool hasAudio = false; + bool hasVideo = false; +}; + + +#endif //GPLAYER_RENDERHELPER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/CommObj.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/CommObj.h new file mode 100644 index 0000000000000000000000000000000000000000..9873b25309a331d3b51a5afcc2842ae8fffb3bc9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/CommObj.h @@ -0,0 +1,19 @@ +#ifndef GPLAYER_COMMOBJ_H_ +#define GPLAYER_COMMOBJ_H_ + +#ifdef ANDROID +#include +typedef jobject CommObj; +#else +class CommObj{}; +#endif + +class MessageCb{ + public: + MessageCb(){}; + virtual ~MessageCb(){}; + virtual void onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2){}; + virtual void onMessageCallback(int msgId, int arg1, long arg2, const char *msg1, const char *msg2, CommObj obj){}; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/ConcurrentQueue.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/ConcurrentQueue.h new file mode 100644 index 0000000000000000000000000000000000000000..dd5840c167eea009bc21acb7cfc125cb4b0ad885 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/ConcurrentQueue.h @@ -0,0 +1,165 @@ +#ifndef GPLAYER_CONCURRENTQUEUE_H +#define GPLAYER_CONCURRENTQUEUE_H + +#include +#include +#include +#include + + +template +class ConcurrentQueue { +public: + ConcurrentQueue(int maxSize, std::string,int simp=0); + + ~ConcurrentQueue(); + + unsigned long push(T data); + + unsigned long front(T *data); + + void pop(); + + void flush(); + + unsigned long size(); + + void reset(); + + virtual void deleteItem(T data); + + void log(const char *msg); + +private: + unsigned long maxSize; + int m_simp; + std::string tag; + std::deque queue; + + volatile bool isWaitingIn; + std::mutex inConLock; + std::condition_variable inConVar; + volatile bool isWaitingOut; + std::mutex outConLock; + std::condition_variable outConVar; + std::mutex queueLock; +}; + +template +ConcurrentQueue::ConcurrentQueue(int maxSize, std::string tag,int simp) { + this->maxSize = maxSize > 1 ? maxSize : 1; + this->tag = tag; + this->m_simp = simp; +} + +template +ConcurrentQueue::~ConcurrentQueue() { + +} + +template +unsigned long ConcurrentQueue::push(T data) { + if(m_simp){ + if (size() >= maxSize) { + deleteItem(data); + return 0; + } + queueLock.lock(); + queue.push_back(data); + queueLock.unlock(); + return size(); + } + queue.push_back(data); + if (isWaitingOut) { + log("output notify all"); + outConVar.notify_all(); + } + if (size() >= maxSize) { + isWaitingIn = true; + log("input waiting start"); + std::unique_lock lck(inConLock); + inConVar.wait_for(lck, std::chrono::milliseconds(200)); + log("input waiting end"); + isWaitingIn = false; + } + return size(); +} + +template +unsigned long ConcurrentQueue::front(T *data) { + if(m_simp){ + if (size() <= 0) return 0; + *data = queue.front(); + if (!(*data)) { + pop(); + return 0; + } + return size(); + } + if (size() <= 0) { + isWaitingOut = true; + log("output waiting start"); + std::unique_lock lck(outConLock); + outConVar.wait_for(lck, std::chrono::milliseconds(200)); + log("output waiting end"); + isWaitingOut = false; + return 0; + } + *data = queue.front(); + if (!(*data)) { + pop(); + return 0; + } + return size(); +} + +template +void ConcurrentQueue::pop() { + queueLock.lock(); + if (size() > 0) { + T data = queue.front(); + if(!m_simp)deleteItem(data); + queue.pop_front(); + } + queueLock.unlock(); + if(m_simp)return; + if (isWaitingIn) { + log("input notify all"); + inConVar.notify_all(); + } +} + +template +void ConcurrentQueue::flush() { + queueLock.lock(); + while (size() > 0) { + T data = queue.front(); + deleteItem(data); + queue.pop_front(); + } + queueLock.unlock(); +} + +template +unsigned long ConcurrentQueue::size() { + return queue.size(); +} + +template +void ConcurrentQueue::reset() { + inConVar.notify_all(); + outConVar.notify_all(); +} + +template +void ConcurrentQueue::deleteItem(T data) { + delete data; +} + +template +void ConcurrentQueue::log(const char *msg) { + LOGD(tag.c_str(), msg); +} + + +#endif //GPLAYER_CONCURRENTQUEUE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b018fb7a307fa995c4dc42ce2005958bd8354064 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.cpp @@ -0,0 +1,104 @@ +#include +#include +#include "FrameSource.h" + +#define TAG "FrameSource" + +FrameSource::FrameSource(int audioMaxSize, int videoMaxSize) { + LOGI(TAG, "CoreFlow : create FrameSource"); + audioPacketQueue = new ConcurrentQueue(audioMaxSize, "AudioFrameQueue"); + videoPacketQueue = new ConcurrentQueue(videoMaxSize, "VideoFrameQueue"); + videoRecyleQueue = new ConcurrentQueue(videoMaxSize, "VideoRecyleQueue",1); +} + +FrameSource::~FrameSource() { + LOGI(TAG, "CoreFlow : FrameSource destroyed %d %d", + audioPacketQueue->size(), videoPacketQueue->size()); + delete audioPacketQueue; + audioPacketQueue = nullptr; + delete videoPacketQueue; + videoPacketQueue = nullptr; + delete videoRecyleQueue; + videoRecyleQueue = nullptr; +} + +unsigned long FrameSource::pushAudFrame(MediaData *frame) { + LOGD(TAG, "pushAudFrame %lld", frame->pts); + auto desBuffer = new MediaData(); + //MediaHelper::copy(frame, desBuffer); + desBuffer->copy(frame); + return audioPacketQueue->push(desBuffer); +} + +unsigned long FrameSource::pushVidFrame(MediaData *frame) { + LOGD(TAG, "pushVidFrame %lld", frame->pts); + auto desBuffer = new MediaData(); + //MediaHelper::copy(frame, desBuffer); + desBuffer->copy(frame); + return videoPacketQueue->push(desBuffer); +} + +unsigned long FrameSource::pushVidRecyle(JMat *frame) { + if(!frame)return 0; + return videoRecyleQueue->push(frame); +} + +unsigned long FrameSource::readAudFrame(MediaData **frame) { + unsigned long size = audioPacketQueue->front(frame); + if (size > 0) { + LOGD(TAG, "readAudFrame %lld", (*frame)->pts); + } + return size; +} + +unsigned long FrameSource::readVidFrame(MediaData **frame) { + unsigned long size = videoPacketQueue->front(frame); + if (size > 0) { + LOGD(TAG, "readVidFrame %lld", (*frame)->pts); + } + return size; +} + +unsigned long FrameSource::popVidRecyle(JMat **frame) { + unsigned long size = videoRecyleQueue->front(frame); + if (size > 0) { + videoRecyleQueue->pop(); + } + return size; +} + + +void FrameSource::popAudFrame(MediaData *frame) { + LOGD(TAG, "popAudFrame %lld", frame->pts); + audioPacketQueue->pop(); +} + +void FrameSource::popVidFrame(MediaData *frame) { + LOGD(TAG, "popVidFrame %lld", frame->pts); + videoPacketQueue->pop(); +} + +void FrameSource::flush() { + audioPacketQueue->flush(); + videoPacketQueue->flush(); + videoRecyleQueue->flush(); + LOGI(TAG, "flushBuffer"); +} + +void FrameSource::reset() { + audioPacketQueue->reset(); + videoPacketQueue->reset(); + videoRecyleQueue->reset(); +} + +unsigned long FrameSource::audioSize() { + return audioPacketQueue->size(); +} + +unsigned long FrameSource::videoSize() { + return videoPacketQueue->size(); +} + +unsigned long FrameSource::recyleSize() { + return videoRecyleQueue->size(); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.h new file mode 100644 index 0000000000000000000000000000000000000000..80d55a6cb7fa8fe8ded97af764718bc493d3f9bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/FrameSource.h @@ -0,0 +1,48 @@ +#ifndef GPLAYER_FRAMESOURCE_H +#define GPLAYER_FRAMESOURCE_H + + +#include "MediaData.h" +#include "ConcurrentQueue.h" + + +class FrameSource { + +public: + FrameSource(int audioMaxSize, int videoMaxSize); + + ~FrameSource(); + +public: + unsigned long pushAudFrame(MediaData *frame); + + unsigned long pushVidFrame(MediaData *frame); + + unsigned long pushVidRecyle(JMat *frame); + unsigned long popVidRecyle(JMat **frame); + + unsigned long readAudFrame(MediaData **frame); + + unsigned long readVidFrame(MediaData **frame); + + void popAudFrame(MediaData *frame); + + void popVidFrame(MediaData *frame); + + void flush(); + + void reset(); + + unsigned long audioSize(); + + unsigned long videoSize(); + unsigned long recyleSize(); + +private: + ConcurrentQueue *audioPacketQueue; + ConcurrentQueue *videoPacketQueue; + ConcurrentQueue *videoRecyleQueue; +}; + + +#endif //GPLAYER_FRAMESOURCE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c01e6712bf661c3885e3a5476f537c4e99b2001 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.cpp @@ -0,0 +1,80 @@ +#if defined(_WIN32) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "Log.h" + +#include +#include +#include + +#ifdef __ANDROID__ +#include +android_LogPriority s_android_logprio[LOG_TRACE + 1] = { + ANDROID_LOG_UNKNOWN, + ANDROID_LOG_FATAL, + ANDROID_LOG_ERROR, + ANDROID_LOG_WARN, + ANDROID_LOG_INFO, + ANDROID_LOG_DEBUG, + ANDROID_LOG_VERBOSE +}; + +#endif + +#if defined(_WIN32) +#include +#endif + +void __log_print(int lv, const char *tag, const char *funame, int line, const char *fmt, ...) { + char log_info[2040]; + char *buf = log_info; + int ret, len = sizeof(log_info); + +//Android 不需要时间 +#ifndef __ANDROID__ + /* + if (lv <= LogLevel::LOG_INFO) { // 日志级别不小于INFO则打印时带时间标记 + *buf++ = '['; + _get_curtime_str(buf); + //buf = buf + strlen(buf); + buf += 23; // 时间格式为:XXXX - XX - XX XX : XX : XX.XXX 共占23个字节 + *buf++ = ']'; + *buf++ = ' '; + + len -= buf - log_info; + } + */ + + if (lv <= LogLevel::LOG_WARN) { // 日志级别不小于WARN则打印时带代码行信息 + ret = sprintf(buf, "%s line:%-4d ", funame, line); + buf += ret; + len -= ret; + } +#endif + + va_list arglist; + va_start(arglist, fmt); + + int itemLen = buf - log_info; +#if defined( WIN32 ) + ret = _vsnprintf(buf, len - 1, fmt, arglist); +#else + ret = vsnprintf(buf, len - 1, fmt, arglist); +#endif + if (ret < 0) { + buf[len - 1] = 0; + buf[len - 2] = '\n'; + itemLen += len - 1; + } else + itemLen += ret; + + va_end(arglist); + +#if defined(__ANDROID__) + __android_log_print(s_android_logprio[lv], tag, log_info, ""); +#else + //本地输出 + //printf("Tag=%s %s\n", tag, log_info); +#endif +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.h new file mode 100644 index 0000000000000000000000000000000000000000..ddd4564ba2aa61b1a6fb2cff937a56c1ce9bd8b8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/Log.h @@ -0,0 +1,43 @@ +#ifndef __GPLAYER_LOG_H__ +#define __GPLAYER_LOG_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +//调试日志开关,1为开,其它为关 +#define LOG_OPEN 0 + +enum LogLevel +{ + LOG_OFF = 0, //!< 不打印日志 + LOG_FATAL = 1, //!< 严重 + LOG_ERROR = 2, //!< 错误 + LOG_WARN = 3, //!< 警告 + LOG_INFO = 4, //!< 信息 + LOG_DEBUG = 5, //!< 调试 + LOG_TRACE = 6, //!< 跟踪 +}; + +void __log_print(int lv, const char* tag, const char* funame, int line, const char *fmt, ...); + +#define LOGI(TAG, ...) __log_print(LogLevel::LOG_INFO, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) +#define LOGW(TAG, ...) __log_print(LogLevel::LOG_WARN, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) +#define LOGE(TAG, ...) __log_print(LogLevel::LOG_ERROR, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) +#define LOGF(TAG, ...) __log_print(LogLevel::LOG_FATAL, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) + +#if defined(__ANDROID__) +#if(LOG_OPEN == 1) +#define LOGD(TAG,...) __log_print(LogLevel::LOG_DEBUG, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) +#else +#define LOGD(TAG, ...) NULL +#endif +#else +#define LOGD(TAG, ...) __log_print(LogLevel::LOG_DEBUG, TAG, __FUNCTION__, __LINE__, __VA_ARGS__) +#endif + +#ifdef __cplusplus +}; +#endif + +#endif // !__GPLAYER_LOG_H__ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89c2918fa6e7532d6011ad1d5d2def73806cf615 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.cpp @@ -0,0 +1,84 @@ +/* + * Created by Gibbs on 2021/1/1. + * Copyright (c) 2021 Gibbs. All rights reserved. + */ + +#include "LoopThread.h" + +#include + +LoopThread::LoopThread() { + setFunction(std::bind(&LoopThread::handleRunning, this)); +} + +LoopThread::~LoopThread()= default; + +void LoopThread::handleRunning() { + if (startFunc) { + startFunc(); + } + if (notifyFunc) { + notifyFunc(NOTIFY_START); + } + isStarted = true; + + while (mRunning) { + if (mPausing) { + std::unique_lock lck(threadLock); + conVar.wait(lck); + continue; + } + if (!updateFunc) { + break; + } + bool hasParams = arg1 >= 0 || arg2 >= 0; + int updateResult = updateFunc(arg1, arg2); + if (hasParams) { + arg1 = -1; + arg2 = -1; + } + if (updateResult == ERROR_EXIST) { + mRunning = false; + continue; + } else if (updateResult == ERROR_PAUSE) { + mPausing = true; + continue; + } + } + + if (endFunc) { + endFunc(); + } + if (notifyFunc) { + notifyFunc(NOTIFY_END); + } + isStarted = false; +} + +void LoopThread::setStartFunc(std::function func) { + startFunc = std::move(func); +} + +void LoopThread::setUpdateFunc(std::function func) { + updateFunc = std::move(func); +} + +void LoopThread::setEndFunc(std::function func) { + endFunc = std::move(func); +} + +void LoopThread::setNotifyFunc(std::function func) { + notifyFunc = std::move(func); +} + +void LoopThread::resume() { + XThread::resume(); + conVar.notify_all(); +} + +bool LoopThread::stop() { + if (isPausing()) { + resume(); + } + return XThread::stop(); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.h new file mode 100644 index 0000000000000000000000000000000000000000..c2a1bb9d84d463b2eb3d986afb90368315933cdf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThread.h @@ -0,0 +1,60 @@ +#ifndef GPLAYER_LOOPTHREAD_H +#define GPLAYER_LOOPTHREAD_H + +#include "XThread.h" +#include +#include +#include + +#define ERROR_EXIST -100 +#define ERROR_PAUSE -101 + +#define NOTIFY_START 0 +#define NOTIFY_END 1 + +using namespace std; + +class LoopThread : public XThread { +public: + LoopThread(); + + virtual ~LoopThread(); + + void setStartFunc(std::function func); + + void setUpdateFunc(std::function func); + + void setEndFunc(std::function func); + + void setNotifyFunc(std::function func); + + void resume() override ; + + bool stop() override ; + + bool hasStarted() { + return isStarted; + } + + void setArgs(int a, long b) { + this->arg1 = a; + this->arg2 = b; + } + +protected: + void handleRunning(); + +private: + std::function startFunc; + std::function updateFunc; + std::function endFunc; + std::function notifyFunc; + bool isStarted = false; + std::mutex threadLock; + std::condition_variable conVar; + + int arg1 = -1; + long arg2 = -1; +}; + +#endif //GPLAYER_LOOPTHREAD_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f01b6f652d873a9995c8310e45b90f5772497520 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.cpp @@ -0,0 +1,43 @@ +/* + * Created by Gibbs on 2021/1/1. + * Copyright (c) 2021 Gibbs. All rights reserved. + */ + +#include "LoopThreadHelper.h" + +LoopThread * +LoopThreadHelper::createLoopThread(const std::function& updateFunc) { + return LoopThreadHelper::createLoopThread(nullptr, updateFunc, nullptr); +} + +LoopThread *LoopThreadHelper::createLoopThread(const std::function& updateFunc, + const std::function& notifyFunc) { + return LoopThreadHelper::createLoopThread(nullptr, updateFunc, nullptr, notifyFunc); +} + +LoopThread *LoopThreadHelper::createLoopThread(const std::function& startFunc, + const std::function& updateFunc, + const std::function& endFunc) { + return LoopThreadHelper::createLoopThread(startFunc, updateFunc, endFunc, nullptr); +} + +LoopThread *LoopThreadHelper::createLoopThread(const std::function& startFunc, + const std::function& updateFunc, + const std::function& endFunc, + const std::function& notifyFunc) { + auto *thread = new LoopThread(); + if (startFunc != nullptr) { + thread->setStartFunc(startFunc); + } + if (updateFunc != nullptr) { + thread->setUpdateFunc(updateFunc); + } + if (endFunc != nullptr) { + thread->setEndFunc(endFunc); + } + if (notifyFunc != nullptr) { + thread->setNotifyFunc(notifyFunc); + } + thread->start(); + return thread; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..718bb8bc1676e5c674a5d4aa80c293226372dc9a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/LoopThreadHelper.h @@ -0,0 +1,26 @@ +#ifndef GPLAYER_LOOPTHREADHELPER_H +#define GPLAYER_LOOPTHREADHELPER_H + + +#include "LoopThread.h" +#include + +class LoopThreadHelper { +public: + static LoopThread *createLoopThread(const std::function& updateFunc); + + static LoopThread *createLoopThread(const std::function& updateFunc, + const std::function& notifyFunc); + + static LoopThread *createLoopThread(const std::function& startFunc, + const std::function& updateFunc, + const std::function& endFunc); + + static LoopThread *createLoopThread(const std::function& startFunc, + const std::function& updateFunc, + const std::function& endFunc, + const std::function& notifyFunc); +}; + + +#endif //GPLAYER_LOOPTHREADHELPER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4cfbcb9142cddf2552f35eea1cf4246ed5cf9eed --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.cpp @@ -0,0 +1,87 @@ +/* + * Created by Gibbs on 2021/1/1. + * Copyright (c) 2021 Gibbs. All rights reserved. + */ + +#include +#include +#include +#include +#include "MediaData.h" + +MediaData::MediaData() = default; + +MediaData::MediaData(JMat* mat,bool ref ){ + m_data = mat; + data = mat->udata(); + size = mat->size(); + data1 = nullptr; + size1 = 0; + data2 = nullptr; + size2 = 0; + width = mat->width();; + height = mat->height(); + m_ref = ref; +} + +MediaData::MediaData(JMat* fmat,JMat* mmat,JMat* bmat,bool ref ){ + m_data = fmat; + m_msk = mmat; + m_bg = bmat; + data = fmat->udata(); + size = fmat->size(); + data1 = mmat->udata(); + size1 = mmat->size(); + data2 = bmat->udata(); + size2 = bmat->size(); + width = fmat->width();; + height = fmat->height(); + m_ref = ref; +} + +int MediaData::copy(MediaData* mediadata){ + //copy + MediaData* mmm = mediadata; + data = mmm->data; + size = mmm->size; + data1 = mmm->data1; + size1 = mmm->size1; + data2 = mmm->data2; + size2 = mmm->size2; + width = mmm->width; + height = mmm->height; + pts = mediadata->pts; + dts = mediadata->dts; + m_data = mmm->m_data; + m_msk = mmm->m_msk; + m_bg = mmm->m_bg; + m_ref = true; + mmm->reset(); + return 0; +} + +MediaData::~MediaData() { + if(m_data){ + delete m_data; + m_data = nullptr; + } + if(m_msk){ + delete m_msk; + m_msk = nullptr; + } + if(m_bg){ + delete m_bg; + m_bg = nullptr; + } +} + +void MediaData::reset(int flag){ + m_data = nullptr; + m_msk = nullptr; + if(!flag) m_bg = nullptr; +} + +void MediaData::print() const { + //LOGI("MediaData", "print MediaData %d %d %d", size, size1, size2); +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.h new file mode 100644 index 0000000000000000000000000000000000000000..2fae04b24b439c1f00fe2542b2bc10efde941242 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MediaData.h @@ -0,0 +1,43 @@ +#ifndef GPLAYER_MEDIADATA_H +#define GPLAYER_MEDIADATA_H + +#include +#include "jmat.h" + +class MediaData { + private: + bool m_ref = false; + public: + MediaData(); + + MediaData(JMat* mat,bool ref = true); + MediaData(JMat* fmat,JMat* mmat,JMat* bmat,bool ref = true); + + ~MediaData(); + + void print() const; + int copy(MediaData* mediadata); + void reset(int flag = 0); + + public: + JMat* m_data = nullptr; + JMat* m_msk = nullptr; + JMat* m_bg = nullptr; + + uint8_t *data = nullptr; + uint32_t size = 0; + uint8_t *data1 = nullptr; + uint32_t size1 = 0; + uint8_t *data2 = nullptr; + uint32_t size2 = 0; + + + uint64_t pts = 0; + uint64_t dts = 0; + uint32_t width = 0; + uint32_t height = 0; + uint8_t flag = 0;//与FLAG_KEY_相关 +}; + + +#endif //GPLAYER_MEDIADATA_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..570c2a6e86524a2dd1e3412c6dd89cb5d3df1293 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.cpp @@ -0,0 +1,30 @@ +#include +#include +#include "MessageHelper.h" + + +MessageHelper::MessageHelper(MessageSource *messageSource, MessageCb* obj) { + this->messageSource = messageSource; + msgobj = obj; +} + +MessageHelper::~MessageHelper() { + notifyObj(MSG_DOMAIN_STATE, STATE_END, 0, nullptr, nullptr); +} + +void MessageHelper::handleErrorMessage(Message *message) { + const char *errorMsg = error2String(message->type, (int)message->extra); + printf("===handle msg %s\n",errorMsg); +} + +const char *MessageHelper::error2String(int errorCode, int errorExtra) { + const char *errorMsg = nullptr; + if (errorCode == MSG_ERROR_DEMUXING || errorCode == MSG_ERROR_DECODING) { + errorMsg = "unknown error"; + } + return errorMsg; +} + +void MessageHelper::notifyObj(int msgId, int arg1, long arg2, const char *msg1, const char *msg2) { + if(msgobj) msgobj->onMessageCallback(msgId, arg1, arg2, msg1, msg2); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..2ec54d47853dfcdc9b179a98aeacaf8ea4dc3fca --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageHelper.h @@ -0,0 +1,25 @@ +#ifndef GPLAYER_MESSAGEHELPER_H +#define GPLAYER_MESSAGEHELPER_H +#include "CommObj.h" + +#include "MessageSource.h" + +class MessageHelper { +public: + MessageHelper(MessageSource *messageSource, MessageCb* obj); + + virtual ~MessageHelper(); + + virtual void handleErrorMessage(Message *message); + + static const char *error2String(int errorCode, int errorExtra); + + virtual void notifyObj(int msgId, int arg1, long arg2, const char* msg1, const char* msg2); + +private: + MessageSource *messageSource; + MessageCb *msgobj; +}; + + +#endif //GPLAYER_MESSAGEHELPER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c717d03e0d41476a43c6fa37cc8f026aedf2e393 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.cpp @@ -0,0 +1,58 @@ +/* + * Created by Gibbs on 2021/1/1. + * Copyright (c) 2021 Gibbs. All rights reserved. + */ + +#include +#include +#include "MessageSource.h" + +#define TAG "MessageSource" + +MessageSource::MessageSource() { + LOGI("MessageSource", "CoreFlow : create MessageSource"); + msgQueue = new ConcurrentQueue(1000000, "MessageQueue"); +} + +MessageSource::~MessageSource() { + LOGI("MessageSource", "CoreFlow : MessageSource destroyed %d", msgQueue->size()); + delete msgQueue; + msgQueue = nullptr; +} + +void MessageSource::pushMessage(int from, int type, long extra) { + if (from == MSG_DOMAIN_TIME) { + if (currentTime == type) { + return; + } + currentTime = type; + auto message = new Message(from, type, extra); + msgQueue->push(message); + } else { + auto message = new Message(from, type, extra); + msgQueue->push(message); + } + LOGI(TAG, "pushMessage size = %d", msgQueue->size()); +} + +unsigned long MessageSource::readMessage(Message **message) { + unsigned long size = msgQueue->front(message); + return size; +} + +void MessageSource::popMessage() { + msgQueue->pop(); +} + +void MessageSource::flush() { + msgQueue->flush(); + LOGI(TAG, "flushBuffer"); +} + +void MessageSource::reset() { + msgQueue->reset(); +} + +unsigned long MessageSource::size() { + return msgQueue->size(); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.h new file mode 100644 index 0000000000000000000000000000000000000000..278cfb2aa3c7088603a7414f75666c35e7f5e02f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/MessageSource.h @@ -0,0 +1,79 @@ +#ifndef GPLAYER_MESSAGESOURCE_H +#define GPLAYER_MESSAGESOURCE_H + +#include "ConcurrentQueue.h" + +#define MAX_BUFFER_PACKET_SIZE 40 +#define MAX_BUFFER_FRAME_SIZE 10 + +#define MSG_DOMAIN_ERROR 0 +#define MSG_DOMAIN_STATE 1 +#define MSG_DOMAIN_TIME 2 +#define MSG_DOMAIN_BUFFER 3 +#define MSG_DOMAIN_DEMUXING 4 +#define MSG_DOMAIN_DECODING 5 +#define MSG_DOMAIN_COMPLETE 6 +#define MSG_DOMAIN_SEEK 7 + +#define MSG_ERROR_DEMUXING 0 +#define MSG_ERROR_DECODING 1 +#define MSG_ERROR_RENDERING 2 +#define MSG_ERROR_SEEK 3 + +#define MSG_DEMUXING_INIT 0 +#define MSG_DEMUXING_DESTROY 1 +#define MSG_DEMUXING_EOF 2 + +#define MSG_SEEK_START 0 +#define MSG_SEEK_END 1 + +#define STATE_IDLE 0 +#define STATE_INITIALIZED 1 +#define STATE_PREPARING 2 +#define STATE_PREPARED 3 +#define STATE_STARTED 4 +#define STATE_PAUSED 5 +#define STATE_STOPPED 6 +#define STATE_COMPLETED 7 +#define STATE_END 8 +#define STATE_ERROR 9 + + +class Message { +public: + Message(int from, int type, long extra) { + this->from = from; + this->type = type; + this->extra = extra; + } + + int from; + int type; + long extra; +}; + +class MessageSource { +public: + MessageSource(); + + ~MessageSource(); + + void pushMessage(int from, int type, long extra); + + unsigned long readMessage(Message **message); + + void popMessage(); + + void flush(); + + void reset(); + + unsigned long size(); + +private: + ConcurrentQueue *msgQueue; + int currentTime = 0; +}; + + +#endif //GPLAYER_MESSAGESOURCE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47164950c9b82fb69fac4bdc9cd74785ffd67b47 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.cpp @@ -0,0 +1,54 @@ +/* + * Created by Gibbs on 2021/1/1. + * Copyright (c) 2021 Gibbs. All rights reserved. + */ + +#include "XThread.h" +#include "Log.h" + +#define TAG "Thread" + +XThread::XThread() = default; + +XThread::~XThread() = default; + +bool XThread::start() { + if (mRunning){ + return false; + } + + if(!mFunc){ + LOGE("XThread", "func is not init"); + return false; + } + + delete mThread; + mRunning = true; + mThread = new std::thread(mFunc); + + return true; +} + +void XThread::pause() { + mPausing = true; +} + +void XThread::resume() { + mPausing = false; +} + +bool XThread::stop() { + if (!mRunning) { + return true; + } + + mRunning = false; + + return true; +} + +void XThread::join() { + if (mThread != nullptr && mThread->joinable()) { + mThread->join(); + } +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.h new file mode 100644 index 0000000000000000000000000000000000000000..76bc89f8ec81d78441e7fc61768cdc023a524bcc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XThread.h @@ -0,0 +1,39 @@ +#ifndef __GPLAYER_THREAD_H__ +#define __GPLAYER_THREAD_H__ + +#include +#include + +class XThread { +public: + XThread(); + + virtual ~XThread(); + + virtual bool start(); + + virtual void pause(); + + virtual void resume(); + + virtual bool stop(); + + void join(); + + bool isAlive() { return mRunning; } + + bool isPausing() { return mPausing; } + + void setFunction(std::function func) { mFunc = func; } + +protected: + volatile bool mRunning = false; + + volatile bool mPausing = false; + + std::thread *mThread = nullptr; + + std::function mFunc; +}; + +#endif //__GPLAYER_THREAD_H__ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.c new file mode 100644 index 0000000000000000000000000000000000000000..8b5dfacb937556831c933951c27c9361c6f7177c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.c @@ -0,0 +1,132 @@ +#if defined(_WIN32) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "XTick.h" +#include + +#if defined( _WIN32 ) + +int64_t getTickCount64() +{ + LARGE_INTEGER TicksPerSecond = { 0 }; + LARGE_INTEGER Tick; + if (!TicksPerSecond.QuadPart) + QueryPerformanceFrequency(&TicksPerSecond); + QueryPerformanceCounter(&Tick); + __int64 Seconds = Tick.QuadPart / TicksPerSecond.QuadPart; + __int64 LeftPart = Tick.QuadPart - (TicksPerSecond.QuadPart*Seconds); + __int64 MillSeconds = LeftPart * 1000 / TicksPerSecond.QuadPart; + __int64 Ret = Seconds * 1000 + MillSeconds; + return Ret; +}; + +int32_t get_tick_sec() +{ + LARGE_INTEGER TicksPerSecond = { 0 }; + LARGE_INTEGER Tick; + if (!TicksPerSecond.QuadPart) + QueryPerformanceFrequency(&TicksPerSecond); + QueryPerformanceCounter(&Tick); + return Tick.QuadPart / TicksPerSecond.QuadPart; +} + +#define getTickCount() GetTickCount() + +/*! + \brief WIN32平台获取当前时间,输出格式为:XXXX-XX-XX XX:XX:XX.XXX 一共占23个字节。 +*/ +const char* _get_curtime_str(char* pbuf) +{ + SYSTEMTIME stm; + GetLocalTime(&stm); + sprintf(pbuf, "%04d-%02d-%02d %02d:%02d:%02d.%03d", + stm.wYear, stm.wMonth, stm.wDay, + stm.wHour, stm.wMinute, stm.wSecond, + stm.wMilliseconds); + return pbuf; +} + +#elif defined(__APPLE__) + +int64_t getTickCount64() +{ + struct timeval tv; + gettimeofday(&tv,NULL); + + return ((int64_t)(tv.tv_usec/1000) + (int64_t)(tv.tv_sec*1000)); +} + +int32_t get_tick_sec() +{ + struct timeval tv; + gettimeofday(&tv,NULL); + return tv.tv_sec; +} + +#define getTickCount() (uint32_t)getTickCount64() + +/*! + \brief 非WIN32平台获取当前时间,输出格式为:XXXX-XX-XX XX:XX:XX.XXX 一共占23个字节。 +*/ +const char* _get_curtime_str(char* pbuf) +{ + struct timeval tv; + struct tm tmv; + time_t tmt; + + gettimeofday(&tv, NULL); +#ifdef APP_ENVIRONMENT + tmt = tv.tv_sec + 8 * 60 * 60; +#else + tmt = tv.tv_sec; +#endif + gmtime_r(&tmt, &tmv); + + sprintf(pbuf, "%04d-%02d-%02d %02d:%02d:%02d.%03d", + tmv.tm_year + 1900, tmv.tm_mon + 1, tmv.tm_mday, + tmv.tm_hour, tmv.tm_min, tmv.tm_sec, + tv.tv_usec / 1000); + return pbuf; +} + +#else + +int64_t getTickCount64() { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); //此处可以判断一下返回值 + return ((int64_t) ts.tv_sec * 1000 + ts.tv_nsec / (1000 * 1000)); +} + +int32_t get_tick_sec() { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); //此处可以判断一下返回值 + return ts.tv_sec; +} + +#define getTickCount() (uint32_t)getTickCount64() + +/*! + \brief 非WIN32平台获取当前时间,输出格式为:XXXX-XX-XX XX:XX:XX.XXX 一共占23个字节。 +*/ +const char *_get_curtime_str(char *pbuf) { + struct timeval tv; + struct tm tmv; + time_t tmt; + + gettimeofday(&tv, NULL); +#ifdef APP_ENVIRONMENT + tmt = tv.tv_sec + 8 * 60 * 60; +#else + tmt = tv.tv_sec; +#endif + gmtime_r(&tmt, &tmv); + + sprintf(pbuf, "%04d-%02d-%02d %02d:%02d:%02d.%03ld", + tmv.tm_year + 1900, tmv.tm_mon + 1, tmv.tm_mday, + tmv.tm_hour, tmv.tm_min, tmv.tm_sec, + tv.tv_usec / 1000); + return pbuf; +} + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.h new file mode 100644 index 0000000000000000000000000000000000000000..4032eba90b62a457f1290f9adfbadf9aba57f7ec --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/XTick.h @@ -0,0 +1,75 @@ +#ifndef __GPLAYER_XTICK_H__ +#define __GPLAYER_XTICK_H__ + +#include +#include +#include + +#define ONE_HOUR (3600 * 1000) +#define ONE_MINUTE (60 * 1000) +#define ONE_SEC (1000) + +#if defined( _WIN32 ) +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int64_t getTickCount64(); +int32_t get_tick_sec(); + +#define getTickCount() GetTickCount() + +const char* _get_curtime_str(char* pbuf); + +#ifdef __cplusplus +} +#endif + +#else + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(linux) || defined(APP_IOS) + +#include +#include + +#endif + +/** + * 获取当前系统时间:单位毫秒 + * @return + */ +int64_t getTickCount64(); + +/** + * 获取当前系统时间: 单位秒 + * @return + */ +int32_t get_tick_sec(); + +/** + * 获取当前系统时间:单位毫秒 + * @return + */ +#define getTickCount() (uint32_t)getTickCount64() + +/** + * 获取当前时间字符串 + * 输出格式为:XXXX-XX-XX XX:XX:XX.XXX 一共占23个字节。 + * @param pbuf 字符串存储buffer + * @return + */ +const char *_get_curtime_str(char *pbuf); + +#ifdef __cplusplus +} +#endif + +#endif //_WIN32 + +#endif //__GPLAYER_XTICK_H__ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.c new file mode 100644 index 0000000000000000000000000000000000000000..ed9755b6cb7d6eda57163e85cf707ce49cee924a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.c @@ -0,0 +1,802 @@ + +/* cJSON */ +/* JSON parser in C. */ + +#include +#include +#include +#include +#include +#include +#include +#include "cJSON.h" + +//#define __RE_MEM_H__ +#ifdef __RE_MEM_H__ +#include "gj_re.h" +#endif + +#ifdef WIN32 +#pragma warning(disable:4996) +#endif + +static const char *ep; + +const char *cJSON_GetErrorPtr() { return ep; } + +static int cJSON_strcasecmp(const char *s1, const char *s2) { + if (!s1) return (s1 == s2) ? 0 : 1; + if (!s2) return 1; + for (; tolower(*s1) == tolower(*s2); ++s1, ++s2) if (*s1 == 0) return 0; + return tolower(*(const unsigned char *) s1) - tolower(*(const unsigned char *) s2); +} + +#ifdef __RE_MEM_H__ +static void* re_malloc(size_t sz){ + return mem_zalloc(sz,NULL); +} + +static void re_free(void* ptr){ + if(ptr)mem_deref(ptr); +} + +static void *(*cJSON_malloc)(size_t sz) = re_malloc; +static void (*cJSON_free)(void *ptr) = re_free; + +#else + +static void *(*cJSON_malloc)(size_t sz) = malloc; + +static void (*cJSON_free)(void *ptr) = free; +#endif + +static char *cJSON_strdup(const char *str) { + size_t len; + char *copy; + + len = strlen(str) + 1; + if (!(copy = (char *) cJSON_malloc(len))) return 0; + memcpy(copy, str, len); + return copy; +} + +void cJSON_InitHooks(cJSON_Hooks *hooks) { + if (!hooks) { /* Reset hooks */ + cJSON_malloc = malloc; + cJSON_free = free; + return; + } + + cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; + cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item() { + cJSON *node = (cJSON *) cJSON_malloc(sizeof(cJSON)); + if (node) memset(node, 0, sizeof(cJSON)); + return node; +} + +/* Delete a cJSON structure. */ +void cJSON_Delete(cJSON *c) { + cJSON *next; + while (c) { + next = c->next; + if (!(c->type & cJSON_IsReference) && c->child) cJSON_Delete(c->child); + if (!(c->type & cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); + if (c->string) cJSON_free(c->string); + cJSON_free(c); + c = next; + } +} + +/* Parse the input text to generate a number, and populate the result into item. */ +static const char *parse_number(cJSON *item, const char *num) { + double n = 0, sign = 1, scale = 0; + int subscale = 0, signsubscale = 1; + + /* Could use sscanf for this? */ + if (*num == '-') sign = -1, num++; /* Has sign? */ + if (*num == '0') num++; /* is zero */ + if (*num >= '1' && *num <= '9') + do n = (n * 10.0) + (*num++ - '0'); + while (*num >= '0' && *num <= '9'); /* Number? */ + if (*num == '.' && num[1] >= '0' && num[1] <= '9') { + num++; + do n = (n * 10.0) + (*num++ - '0'), scale--; while (*num >= '0' && *num <= '9'); + } /* Fractional part? */ + if (*num == 'e' || *num == 'E') /* Exponent? */ + { + num++; + if (*num == '+') num++; else if (*num == '-') signsubscale = -1, num++; /* With sign? */ + while (*num >= '0' && *num <= '9') subscale = (subscale * 10) + (*num++ - '0'); /* Number? */ + } + + n = sign * n * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ + + item->valuedouble = n; + item->valueint = (int) n; + item->type = cJSON_Number; + return num; +} + +/* Render the number nicely from the given item into a string. */ +static char *print_number(cJSON *item) { + char *str; + double d = item->valuedouble; + if (fabs(((double) item->valueint) - d) <= DBL_EPSILON && d <= INT_MAX && d >= INT_MIN) { + str = (char *) cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ + if (str) sprintf(str, "%d", item->valueint); + } else { + str = (char *) cJSON_malloc(64); /* This is a nice tradeoff. */ + if (str) { + if (fabs(floor(d) - d) <= DBL_EPSILON) sprintf(str, "%.0f", d); + else if (fabs(d) < 1.0e-6 || fabs(d) > 1.0e9) sprintf(str, "%e", d); + else sprintf(str, "%f", d); + } + } + return str; +} + +/* Parse the input text into an unescaped cstring, and populate item. */ +static const unsigned char firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; + +static const char *parse_string(cJSON *item, const char *str) { + const char *ptr = str + 1; + char *ptr2; + char *out; + int len = 0; + unsigned uc, uc2; + if (*str != '\"') { + ep = str; + return 0; + } /* not a string! */ + + while (*ptr != '\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ + + out = (char *) cJSON_malloc(len + 1); /* This is how long we need for the string, roughly. */ + if (!out) return 0; + + ptr = str + 1; + ptr2 = out; + while (*ptr != '\"' && *ptr) { + if (*ptr != '\\') *ptr2++ = *ptr++; + else { + ptr++; + switch (*ptr) { + case 'b': + *ptr2++ = '\b'; + break; + case 'f': + *ptr2++ = '\f'; + break; + case 'n': + *ptr2++ = '\n'; + break; + case 'r': + *ptr2++ = '\r'; + break; + case 't': + *ptr2++ = '\t'; + break; + case 'u': /* transcode utf16 to utf8. */ + sscanf(ptr + 1, "%4x", &uc); + ptr += 4; /* get the unicode char. */ + + if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) break; // check for invalid. + + if (uc >= 0xD800 && uc <= 0xDBFF) // UTF16 surrogate pairs. + { + if (ptr[1] != '\\' || ptr[2] != 'u') break; // missing second-half of surrogate. + sscanf(ptr + 3, "%4x", &uc2); + ptr += 6; + if (uc2 < 0xDC00 || uc2 > 0xDFFF) break; // invalid second-half of surrogate. + uc = 0x10000 | ((uc & 0x3FF) << 10) | (uc2 & 0x3FF); + } + + len = 4; + if (uc < 0x80) len = 1; else if (uc < 0x800) len = 2; else if (uc < 0x10000) len = 3; + ptr2 += len; + + switch (len) { + case 4: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 3: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 2: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 1: + *--ptr2 = (uc | firstByteMark[len]); + } + ptr2 += len; + break; + default: + *ptr2++ = *ptr; + break; + } + ptr++; + } + } + *ptr2 = 0; + if (*ptr == '\"') ptr++; + item->valuestring = out; + item->type = cJSON_String; + return ptr; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static char *print_string_ptr(const char *str) { + const char *ptr; + char *ptr2, *out; + int len = 0; + unsigned char token; + + if (!str) return cJSON_strdup(""); + ptr = str; + while ((token = *ptr) && ++len) { + if (strchr("\"\\\b\f\n\r\t", token)) len++; else if (token < 32) len += 5; + ptr++; + } + + out = (char *) cJSON_malloc(len + 3); + if (!out) return 0; + + ptr2 = out; + ptr = str; + *ptr2++ = '\"'; + while (*ptr) { + if ((unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\') *ptr2++ = *ptr++; + else { + *ptr2++ = '\\'; + switch (token = *ptr++) { + case '\\': + *ptr2++ = '\\'; + break; + case '\"': + *ptr2++ = '\"'; + break; + case '\b': + *ptr2++ = 'b'; + break; + case '\f': + *ptr2++ = 'f'; + break; + case '\n': + *ptr2++ = 'n'; + break; + case '\r': + *ptr2++ = 'r'; + break; + case '\t': + *ptr2++ = 't'; + break; + default: + sprintf(ptr2, "u%04x", token); + ptr2 += 5; + break; /* escape and print */ + } + } + } + *ptr2++ = '\"'; + *ptr2++ = 0; + return out; +} + +/* Invote print_string_ptr (which is useful) on an item. */ +static char *print_string(cJSON *item) { return print_string_ptr(item->valuestring); } + +/* Predeclare these prototypes. */ +static const char *parse_value(cJSON *item, const char *value); + +static char *print_value(cJSON *item, int depth, int fmt); + +static const char *parse_array(cJSON *item, const char *value); + +static char *print_array(cJSON *item, int depth, int fmt); + +static const char *parse_object(cJSON *item, const char *value); + +static char *print_object(cJSON *item, int depth, int fmt); + +/* Utility to jump whitespace and cr/lf */ +static const char *skip(const char *in) { + while (in && *in && (unsigned char) *in <= 32) in++; + return in; +} + +/* Parse an object - create a new root, and populate. */ +cJSON *cJSON_Parse(const char *value) { + cJSON *c = cJSON_New_Item(); + ep = 0; + if (!c) return 0; /* memory fail */ + + if (!parse_value(c, skip(value))) { + cJSON_Delete(c); + return 0; + } + return c; +} + +/* Render a cJSON item/entity/structure to text. */ +char *cJSON_Print(cJSON *item) { return print_value(item, 0, 1); } + +char *cJSON_PrintUnformatted(cJSON *item) { return print_value(item, 0, 0); } + +/* Parser core - when encountering text, process appropriately. */ +static const char *parse_value(cJSON *item, const char *value) { + if (!value) return 0; /* Fail on null. */ + if (!strncmp(value, "null", 4)) { + item->type = cJSON_NULL; + return value + 4; + } + if (!strncmp(value, "false", 5)) { + item->type = cJSON_False; + return value + 5; + } + if (!strncmp(value, "true", 4)) { + item->type = cJSON_True; + item->valueint = 1; + return value + 4; + } + if (*value == '\"') { return parse_string(item, value); } + if (*value == '-' || (*value >= '0' && *value <= '9')) { return parse_number(item, value); } + if (*value == '[') { return parse_array(item, value); } + if (*value == '{') { return parse_object(item, value); } + + ep = value; + return 0; /* failure. */ +} + +/* Render a value to text. */ +static char *print_value(cJSON *item, int depth, int fmt) { + char *out = 0; + if (!item) return 0; + switch ((item->type) & 255) { + case cJSON_NULL: + out = cJSON_strdup("null"); + break; + case cJSON_False: + out = cJSON_strdup("false"); + break; + case cJSON_True: + out = cJSON_strdup("true"); + break; + case cJSON_Number: + out = print_number(item); + break; + case cJSON_String: + out = print_string(item); + break; + case cJSON_Array: + out = print_array(item, depth, fmt); + break; + case cJSON_Object: + out = print_object(item, depth, fmt); + break; + } + return out; +} + +/* Build an array from input text. */ +static const char *parse_array(cJSON *item, const char *value) { + cJSON *child; + if (*value != '[') { + ep = value; + return 0; + } /* not an array! */ + + item->type = cJSON_Array; + value = skip(value + 1); + if (*value == ']') return value + 1; /* empty array. */ + + item->child = child = cJSON_New_Item(); + if (!item->child) return 0; /* memory fail */ + value = skip(parse_value(child, skip(value))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value == ',') { + cJSON *new_item; + if (!(new_item = cJSON_New_Item())) return 0; /* memory fail */ + child->next = new_item; + new_item->prev = child; + child = new_item; + value = skip(parse_value(child, skip(value + 1))); + if (!value) return 0; /* memory fail */ + } + + if (*value == ']') return value + 1; /* end of array */ + ep = value; + return 0; /* malformed. */ +} + +/* Render an array to text */ +static char *print_array(cJSON *item, int depth, int fmt) { + char **entries; + char *out = 0, *ptr, *ret; + int len = 5; + cJSON *child = item->child; + int numentries = 0, i = 0, fail = 0; + + /* How many entries in the array? */ + while (child) numentries++, child = child->next; + /* Allocate an array to hold the values for each */ + entries = (char **) cJSON_malloc(numentries * sizeof(char *)); + if (!entries) return 0; + memset(entries, 0, numentries * sizeof(char *)); + /* Retrieve all the results: */ + child = item->child; + while (child && !fail) { + ret = print_value(child, depth + 1, fmt); + entries[i++] = ret; + if (ret) len += strlen(ret) + 2 + (fmt ? 1 : 0); else fail = 1; + child = child->next; + } + + /* If we didn't fail, try to malloc the output string */ + if (!fail) out = (char *) cJSON_malloc(len); + /* If that fails, we fail. */ + if (!out) fail = 1; + + /* Handle failure. */ + if (fail) { + for (i = 0; i < numentries; i++) if (entries[i]) cJSON_free(entries[i]); + cJSON_free(entries); + return 0; + } + + /* Compose the output array. */ + *out = '['; + ptr = out + 1; + *ptr = 0; + for (i = 0; i < numentries; i++) { + strcpy(ptr, entries[i]); + ptr += strlen(entries[i]); + if (i != numentries - 1) { + *ptr++ = ','; + if (fmt)*ptr++ = ' '; + *ptr = 0; + } + cJSON_free(entries[i]); + } + cJSON_free(entries); + *ptr++ = ']'; + *ptr++ = 0; + return out; +} + +/* Build an object from the text. */ +static const char *parse_object(cJSON *item, const char *value) { + cJSON *child; + if (*value != '{') { + ep = value; + return 0; + } /* not an object! */ + + item->type = cJSON_Object; + value = skip(value + 1); + if (*value == '}') return value + 1; /* empty array. */ + + item->child = child = cJSON_New_Item(); + if (!item->child) return 0; + value = skip(parse_string(child, skip(value))); + if (!value) return 0; + child->string = child->valuestring; + child->valuestring = 0; + if (*value != ':') { + ep = value; + return 0; + } /* fail! */ + value = skip(parse_value(child, skip(value + 1))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value == ',') { + cJSON *new_item; + if (!(new_item = cJSON_New_Item())) return 0; /* memory fail */ + child->next = new_item; + new_item->prev = child; + child = new_item; + value = skip(parse_string(child, skip(value + 1))); + if (!value) return 0; + child->string = child->valuestring; + child->valuestring = 0; + if (*value != ':') { + ep = value; + return 0; + } /* fail! */ + value = skip(parse_value(child, skip(value + 1))); /* skip any spacing, get the value. */ + if (!value) return 0; + } + + if (*value == '}') return value + 1; /* end of array */ + ep = value; + return 0; /* malformed. */ +} + +/* Render an object to text. */ +static char *print_object(cJSON *item, int depth, int fmt) { + char **entries = 0, **names = 0; + char *out = 0, *ptr, *ret, *str; + int len = 7, i = 0, j; + cJSON *child = item->child; + int numentries = 0, fail = 0; + /* Count the number of entries. */ + while (child) numentries++, child = child->next; + /* Allocate space for the names and the objects */ + entries = (char **) cJSON_malloc(numentries * sizeof(char *)); + if (!entries) return 0; + names = (char **) cJSON_malloc(numentries * sizeof(char *)); + if (!names) { + cJSON_free(entries); + return 0; + } + memset(entries, 0, sizeof(char *) * numentries); + memset(names, 0, sizeof(char *) * numentries); + + /* Collect all the results into our arrays: */ + child = item->child; + depth++; + if (fmt) len += depth; + while (child) { + names[i] = str = print_string_ptr(child->string); + entries[i++] = ret = print_value(child, depth, fmt); + if (str && ret) len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); else fail = 1; + child = child->next; + } + + /* Try to allocate the output string */ + //if (!fail) out = (char *) cJSON_malloc(len); + if (!fail) out = (char *) cJSON_malloc(len); + if (!out) fail = 1; + + /* Handle failure */ + if (fail) { + for (i = 0; i < numentries; i++) { + if (names[i]) cJSON_free(names[i]); + if (entries[i]) cJSON_free(entries[i]); + } + cJSON_free(names); + cJSON_free(entries); + return 0; + } + + /* Compose the output: */ + *out = '{'; + ptr = out + 1; + if (fmt)*ptr++ = '\n'; + *ptr = 0; + for (i = 0; i < numentries; i++) { + if (fmt) for (j = 0; j < depth; j++) *ptr++ = '\t'; + strcpy(ptr, names[i]); + ptr += strlen(names[i]); + *ptr++ = ':'; + if (fmt) *ptr++ = '\t'; + strcpy(ptr, entries[i]); + ptr += strlen(entries[i]); + if (i != numentries - 1) *ptr++ = ','; + if (fmt) *ptr++ = '\n'; + *ptr = 0; + cJSON_free(names[i]); + cJSON_free(entries[i]); + } + + cJSON_free(names); + cJSON_free(entries); + if (fmt) for (i = 0; i < depth - 1; i++) *ptr++ = '\t'; + *ptr++ = '}'; + *ptr++ = 0; + return out; +} + +/* Get Array size/item / object item. */ +int cJSON_GetArraySize(cJSON *array) { + cJSON *c = array->child; + int i = 0; + while (c)i++, c = c->next; + return i; +} + +cJSON *cJSON_GetArrayItem(cJSON *array, int item) { + cJSON *c = array->child; + while (c && item > 0) item--, c = c->next; + return c; +} + +cJSON *cJSON_GetObjectItem(cJSON *object, const char *string) { + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string)) c = c->next; + return c; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) { + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(cJSON *item) { + cJSON *ref = cJSON_New_Item(); + if (!ref) return 0; + memcpy(ref, item, sizeof(cJSON)); + ref->string = 0; + ref->type |= cJSON_IsReference; + ref->next = ref->prev = 0; + return ref; +} + +/* Add item to array/object. */ +void cJSON_AddItemToArray(cJSON *array, cJSON *item) { + cJSON *c = array->child; + if (!item) return; + if (!c) { array->child = item; } + else { + while (c && c->next) c = c->next; + suffix_object(c, item); + } +} + +void cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) { + if (!item) return; + if (item->string) cJSON_free(item->string); + item->string = cJSON_strdup(string); + cJSON_AddItemToArray(object, item); +} + +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) { cJSON_AddItemToArray(array, create_reference(item)); } + +void cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) { + cJSON_AddItemToObject(object, string, create_reference(item)); +} + +cJSON *cJSON_DetachItemFromArray(cJSON *array, int which) { + cJSON *c = array->child; + while (c && which > 0) c = c->next, which--; + if (!c) return 0; + if (c->prev) c->prev->next = c->next; + if (c->next) c->next->prev = c->prev; + if (c == array->child) array->child = c->next; + c->prev = c->next = 0; + return c; +} + +void cJSON_DeleteItemFromArray(cJSON *array, int which) { cJSON_Delete(cJSON_DetachItemFromArray(array, which)); } + +cJSON *cJSON_DetachItemFromObject(cJSON *object, const char *string) { + int i = 0; + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string)) i++, c = c->next; + if (c) return cJSON_DetachItemFromArray(object, i); + return 0; +} + +void cJSON_DeleteItemFromObject(cJSON *object, const char *string) { + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +/* Replace array/object items with new ones. */ +void cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) { + cJSON *c = array->child; + while (c && which > 0) c = c->next, which--; + if (!c) return; + newitem->next = c->next; + newitem->prev = c->prev; + if (newitem->next) newitem->next->prev = newitem; + if (c == array->child) array->child = newitem; else newitem->prev->next = newitem; + c->next = c->prev = 0; + cJSON_Delete(c); +} + +void cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) { + int i = 0; + cJSON *c = object->child; + while (c && cJSON_strcasecmp(c->string, string))i++, c = c->next; + if (c) { + newitem->string = cJSON_strdup(string); + cJSON_ReplaceItemInArray(object, i, newitem); + } +} + +/* Create basic types: */ +cJSON *cJSON_CreateNull() { + cJSON *item = cJSON_New_Item(); + if (item)item->type = cJSON_NULL; + return item; +} + +cJSON *cJSON_CreateTrue() { + cJSON *item = cJSON_New_Item(); + if (item)item->type = cJSON_True; + return item; +} + +cJSON *cJSON_CreateFalse() { + cJSON *item = cJSON_New_Item(); + if (item)item->type = cJSON_False; + return item; +} + +cJSON *cJSON_CreateBool(int b) { + cJSON *item = cJSON_New_Item(); + if (item)item->type = b ? cJSON_True : cJSON_False; + return item; +} + +cJSON *cJSON_CreateNumber(double num) { + cJSON *item = cJSON_New_Item(); + if (item) { + item->type = cJSON_Number; + item->valuedouble = num; + item->valueint = (int) num; + } + return item; +} + +cJSON *cJSON_CreateString(const char *string) { + cJSON *item = cJSON_New_Item(); + if (item) { + item->type = cJSON_String; + item->valuestring = cJSON_strdup(string); + } + return item; +} + +cJSON *cJSON_CreateArray() { + cJSON *item = cJSON_New_Item(); + if (item)item->type = cJSON_Array; + return item; +} + +cJSON *cJSON_CreateObject() { + cJSON *item = cJSON_New_Item(); + if (item)item->type = cJSON_Object; + return item; +} + +/* Create Arrays: */ +cJSON *cJSON_CreateIntArray(int *numbers, int count) { + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!i)a->child = n; else suffix_object(p, n); + p = n; + } + return a; +} + +cJSON *cJSON_CreateFloatArray(float *numbers, int count) { + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!i)a->child = n; else suffix_object(p, n); + p = n; + } + return a; +} + +cJSON *cJSON_CreateDoubleArray(double *numbers, int count) { + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!i)a->child = n; else suffix_object(p, n); + p = n; + } + return a; +} + +cJSON *cJSON_CreateStringArray(const char **strings, int count) { + int i; + cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); + for (i = 0; a && i < count; i++) { + n = cJSON_CreateString(strings[i]); + if (!i)a->child = n; else suffix_object(p, n); + p = n; + } + return a; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.h new file mode 100644 index 0000000000000000000000000000000000000000..78dcbafcf72b604dc722ced906209a3565fd8cc9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/cJSON.h @@ -0,0 +1,135 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" { +#endif + +/* cJSON Types: */ +#define cJSON_False 0 +#define cJSON_True 1 +#define cJSON_NULL 2 +#define cJSON_Number 3 +#define cJSON_String 4 +#define cJSON_Array 5 +#define cJSON_Object 6 + +#define cJSON_IsReference 256 + +/* The cJSON structure: */ +typedef struct cJSON { + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + + int type; /* The type of the item, as above. */ + + char *valuestring; /* The item's string, if type==cJSON_String */ + int valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ + + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} cJSON; + +typedef struct cJSON_Hooks { + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +/* Supply malloc, realloc and free functions to cJSON */ +extern void cJSON_InitHooks(cJSON_Hooks* hooks); + + +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */ +extern cJSON *cJSON_Parse(const char *value); +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ +extern char *cJSON_Print(cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */ +extern char *cJSON_PrintUnformatted(cJSON *item); +/* Delete a cJSON entity and all subentities. */ +extern void cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +extern int cJSON_GetArraySize(cJSON *array); +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); +/* Get item "string" from object. Case insensitive. */ +extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); + +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +extern const char *cJSON_GetErrorPtr(); + +/* These calls create a cJSON item of the appropriate type. */ +extern cJSON *cJSON_CreateNull(); +extern cJSON *cJSON_CreateTrue(); +extern cJSON *cJSON_CreateFalse(); +extern cJSON *cJSON_CreateBool(int b); +extern cJSON *cJSON_CreateNumber(double num); +extern cJSON *cJSON_CreateString(const char *string); +extern cJSON *cJSON_CreateArray(); +extern cJSON *cJSON_CreateObject(); + +/* These utilities create an Array of count items. */ +extern cJSON *cJSON_CreateIntArray(int *numbers,int count); +extern cJSON *cJSON_CreateFloatArray(float *numbers,int count); +extern cJSON *cJSON_CreateDoubleArray(double *numbers,int count); +extern cJSON *cJSON_CreateStringArray(const char **strings,int count); + +/* Append item to the specified array/object. */ +extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); + +/* Remove/Detatch items from Arrays/Objects. */ +extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which); +extern void cJSON_DeleteItemFromArray(cJSON *array,int which); +extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string); +extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string); + +/* Update array items. */ +extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); +extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); + +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) + + +#define CHECKSTRVAL(root,name,pval,r) if(1){*pval=NULL;cJSON* obj=cJSON_GetObjectItem(root,name);if(obj==NULL)return r;char* v=obj->valuestring;if(v==NULL)return r;*pval=v;printf("%s=%s\n",name,*pval);} + +#define CHECKDBLVAL(root,name,pval,r) if(1){cJSON* obj=cJSON_GetObjectItem(root,name);if(obj==NULL)return r;double v=obj->valuedouble;*pval=v;} + +#define CHECKINTVAL(root,name,pval,r) if(1){cJSON* obj=cJSON_GetObjectItem(root,name);if(obj==NULL)return r;int v=obj->valueint;*pval=v;} + + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.c new file mode 100644 index 0000000000000000000000000000000000000000..159c642e8c2fb3d944029f9514f0fd3f94ffd8bb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.c @@ -0,0 +1,1419 @@ +/* CoffeeCatch, a tiny native signal handler/catcher for JNI code. + * (especially for Android/Dalvik) + * + * Copyright (c) 2013, Xavier Roche (http://www.httrack.com/) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifdef __ANDROID__ +#define USE_UNWIND +#define USE_CORKSCREW +#define USE_LIBUNWIND +#else +#endif + +/* #undef NO_USE_SIGALTSTACK */ +/* #undef USE_SILENT_SIGALTSTACK */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(__ANDROID__) && !defined(__BIONIC_HAVE_UCONTEXT_T) && \ + defined(__arm__) && !defined(__BIONIC_HAVE_STRUCT_SIGCONTEXT) +#include +#endif +#if (defined(USE_UNWIND) && !defined(USE_CORKSCREW)) +#include +#endif +#include +#include +#include "coffeecatch.h" + +/*#define NDK_DEBUG 1*/ +#if ( defined(NDK_DEBUG) && ( NDK_DEBUG == 1 ) ) +#define DEBUG(A) do { A; } while(0) +#define FD_ERRNO 2 +static void print(const char *const s) { + size_t count; + for(count = 0; s[count] != '\0'; count++) ; + /* write() is async-signal-safe. */ + (void) write(FD_ERRNO, s, count); +} +#else +#define DEBUG(A) +#endif + +/* Alternative stack size. */ +#define SIG_STACK_BUFFER_SIZE SIGSTKSZ + +#ifdef USE_UNWIND +/* Number of backtraces to get. */ +#define BACKTRACE_FRAMES_MAX 32 +#endif + +/* Signals to be caught. */ +#define SIG_CATCH_COUNT 7 +static const int native_sig_catch[SIG_CATCH_COUNT + 1] + = { SIGABRT, SIGILL, SIGTRAP, SIGBUS, SIGFPE, SIGSEGV +#ifdef SIGSTKFLT + , SIGSTKFLT +#endif + , 0 }; + +/* Maximum value of a caught signal. */ +#define SIG_NUMBER_MAX 32 + +#if defined(__ANDROID__) +#ifndef ucontext_h_seen +#define ucontext_h_seen + +/* stack_t definition */ +#include + +#if defined(__arm__) + +/* Taken from richard.quirk's header file. (Android does not have it) */ + +#if !defined(__BIONIC_HAVE_UCONTEXT_T) +typedef struct ucontext { + unsigned long uc_flags; + struct ucontext *uc_link; + stack_t uc_stack; + struct sigcontext uc_mcontext; + unsigned long uc_sigmask; +} ucontext_t; +#endif + +#elif defined(__aarch64__) + +#elif defined(__i386__) + +/* Taken from Google Breakpad. */ + +/* 80-bit floating-point register */ +struct _libc_fpreg { + unsigned short significand[4]; + unsigned short exponent; +}; + +/* Simple floating-point state, see FNSTENV instruction */ +struct _libc_fpstate { + unsigned long cw; + unsigned long sw; + unsigned long tag; + unsigned long ipoff; + unsigned long cssel; + unsigned long dataoff; + unsigned long datasel; + struct _libc_fpreg _st[8]; + unsigned long status; +}; + +typedef uint32_t greg_t; + +typedef struct { + uint32_t gregs[19]; + struct _libc_fpstate* fpregs; + uint32_t oldmask; + uint32_t cr2; +} mcontext_t; + +enum { + REG_GS = 0, + REG_FS, + REG_ES, + REG_DS, + REG_EDI, + REG_ESI, + REG_EBP, + REG_ESP, + REG_EBX, + REG_EDX, + REG_ECX, + REG_EAX, + REG_TRAPNO, + REG_ERR, + REG_EIP, + REG_CS, + REG_EFL, + REG_UESP, + REG_SS, +}; + +#if !defined(__BIONIC_HAVE_UCONTEXT_T) +typedef struct ucontext { + uint32_t uc_flags; + struct ucontext* uc_link; + stack_t uc_stack; + mcontext_t uc_mcontext; +} ucontext_t; +#endif + +#elif defined(__mips__) + +/* Taken from Google Breakpad. */ + +typedef struct { + uint32_t regmask; + uint32_t status; + uint64_t pc; + uint64_t gregs[32]; + uint64_t fpregs[32]; + uint32_t acx; + uint32_t fpc_csr; + uint32_t fpc_eir; + uint32_t used_math; + uint32_t dsp; + uint64_t mdhi; + uint64_t mdlo; + uint32_t hi1; + uint32_t lo1; + uint32_t hi2; + uint32_t lo2; + uint32_t hi3; + uint32_t lo3; +} mcontext_t; + +#if !defined(__BIONIC_HAVE_UCONTEXT_T) +typedef struct ucontext { + uint32_t uc_flags; + struct ucontext* uc_link; + stack_t uc_stack; + mcontext_t uc_mcontext; +} ucontext_t; +#endif + +#else +#error "Architecture is not supported (unknown ucontext layout)" +#endif + +#endif + +#ifdef USE_CORKSCREW +typedef struct map_info_t map_info_t; +/* Extracted from Android's include/corkscrew/backtrace.h */ +typedef struct { + uintptr_t absolute_pc; + uintptr_t stack_top; + size_t stack_size; +} backtrace_frame_t; +typedef struct { + uintptr_t relative_pc; + uintptr_t relative_symbol_addr; + char* map_name; + char* symbol_name; + char* demangled_name; +} backtrace_symbol_t; +/* Extracted from Android's libcorkscrew/arch-arm/backtrace-arm.c */ +typedef ssize_t (*t_unwind_backtrace_signal_arch) +(siginfo_t* si, void* sc, const map_info_t* lst, backtrace_frame_t* bt, +size_t ignore_depth, size_t max_depth); +typedef map_info_t* (*t_acquire_my_map_info_list)(); +typedef void (*t_release_my_map_info_list)(map_info_t* milist); +typedef void (*t_get_backtrace_symbols)(const backtrace_frame_t* backtrace, + size_t frames, + backtrace_symbol_t* symbols); +typedef void (*t_free_backtrace_symbols)(backtrace_symbol_t* symbols, + size_t frames); +#endif + +#endif + +/* Process-wide crash handler structure. */ +typedef struct native_code_global_struct { + /* Initialized. */ + int initialized; + + /* Lock. */ + pthread_mutex_t mutex; + + /* Backup of sigaction. */ + struct sigaction *sa_old; +} native_code_global_struct; +#define NATIVE_CODE_GLOBAL_INITIALIZER { 0, PTHREAD_MUTEX_INITIALIZER, NULL } + +/* Thread-specific crash handler structure. */ +typedef struct native_code_handler_struct { + /* Restore point context. */ + sigjmp_buf ctx; + int ctx_is_set; + int reenter; + + /* Alternate stack. */ + char *stack_buffer; + size_t stack_buffer_size; + stack_t stack_old; + + /* Signal code and info. */ + int code; + siginfo_t si; + ucontext_t uc; + + /* Uwind context. */ +#if (defined(USE_CORKSCREW)) + backtrace_frame_t frames[BACKTRACE_FRAMES_MAX]; +#elif (defined(USE_UNWIND)) + uintptr_t frames[BACKTRACE_FRAMES_MAX]; +#endif +#ifdef USE_LIBUNWIND + void* uframes[BACKTRACE_FRAMES_MAX]; +#endif + size_t frames_size; + size_t frames_skip; + + /* Custom assertion failures. */ + const char *expression; + const char *file; + int line; + + /* Alarm was fired. */ + int alarm; +} native_code_handler_struct; + +/* Global crash handler structure. */ +static native_code_global_struct native_code_g = + NATIVE_CODE_GLOBAL_INITIALIZER; + +/* Thread variable holding context. */ +pthread_key_t native_code_thread; + +#if (defined(USE_UNWIND) && !defined(USE_CORKSCREW)) +/* Unwind callback */ +static _Unwind_Reason_Code +coffeecatch_unwind_callback(struct _Unwind_Context* context, void* arg) { + native_code_handler_struct *const s = (native_code_handler_struct*) arg; + + const uintptr_t ip = _Unwind_GetIP(context); + + DEBUG(print("called unwind callback\n")); + + if (ip != 0x0) { + if (s->frames_skip == 0) { + s->frames[s->frames_size] = ip; + s->frames_size++; + } else { + s->frames_skip--; + } + } + + if (s->frames_size == BACKTRACE_FRAMES_MAX) { + return _URC_END_OF_STACK; + } else { + DEBUG(print("returned _URC_OK\n")); + return _URC_OK; + } +} +#endif + +/* Use libcorkscrew to get a backtrace inside a signal handler. + Will only return a non-zero code on Android >= 4 (with libcorkscrew.so + being shipped) */ +#ifdef USE_CORKSCREW +static size_t coffeecatch_backtrace_signal(siginfo_t* si, void* sc, + backtrace_frame_t* frames, + size_t ignore_depth, + size_t max_depth) { + void *const libcorkscrew = dlopen("libcorkscrew.so", RTLD_LAZY | RTLD_LOCAL); + if (libcorkscrew != NULL) { + t_unwind_backtrace_signal_arch unwind_backtrace_signal_arch + = (t_unwind_backtrace_signal_arch) + dlsym(libcorkscrew, "unwind_backtrace_signal_arch"); + t_acquire_my_map_info_list acquire_my_map_info_list + = (t_acquire_my_map_info_list) + dlsym(libcorkscrew, "acquire_my_map_info_list"); + t_release_my_map_info_list release_my_map_info_list + = (t_release_my_map_info_list) + dlsym(libcorkscrew, "release_my_map_info_list"); + if (unwind_backtrace_signal_arch != NULL + && acquire_my_map_info_list != NULL + && release_my_map_info_list != NULL) { + map_info_t*const info = acquire_my_map_info_list(); + const ssize_t size = + unwind_backtrace_signal_arch(si, sc, info, frames, ignore_depth, + max_depth); + release_my_map_info_list(info); + return size >= 0 ? size : 0; + } else { + DEBUG(print("symbols not found in libcorkscrew.so\n")); + } + dlclose(libcorkscrew); + } else { + DEBUG(print("libcorkscrew.so could not be loaded\n")); + } + return 0; +} + +static int coffeecatch_backtrace_symbols(const backtrace_frame_t* backtrace, + size_t frames, + void (*fun)(void *arg, + const backtrace_symbol_t *sym), + void *arg) { + int success = 0; + void *const libcorkscrew = dlopen("libcorkscrew.so", RTLD_LAZY | RTLD_LOCAL); + if (libcorkscrew != NULL) { + t_get_backtrace_symbols get_backtrace_symbols + = (t_get_backtrace_symbols) + dlsym(libcorkscrew, "get_backtrace_symbols"); + t_free_backtrace_symbols free_backtrace_symbols + = (t_free_backtrace_symbols) + dlsym(libcorkscrew, "free_backtrace_symbols"); + if (get_backtrace_symbols != NULL + && free_backtrace_symbols != NULL) { + backtrace_symbol_t symbols[BACKTRACE_FRAMES_MAX]; + size_t i; + if (frames > BACKTRACE_FRAMES_MAX) { + frames = BACKTRACE_FRAMES_MAX; + } + get_backtrace_symbols(backtrace, frames, symbols); + for(i = 0; i < frames; i++) { + fun(arg, &symbols[i]); + } + free_backtrace_symbols(symbols, frames); + success = 1; + } else { + DEBUG(print("symbols not found in libcorkscrew.so\n")); + } + dlclose(libcorkscrew); + } else { + DEBUG(print("libcorkscrew.so could not be loaded\n")); + } + return success; +} +#endif + +/* Use libunwind to get a backtrace inside a signal handler. + Will only return a non-zero code on Android >= 5 (with libunwind.so + being shipped) */ +#ifdef USE_LIBUNWIND +static ssize_t coffeecatch_unwind_signal(siginfo_t* si, void* sc, + void** frames, + size_t ignore_depth, + size_t max_depth) { + void *libunwind = dlopen("libunwind.so", RTLD_LAZY | RTLD_LOCAL); + if (libunwind != NULL) { + int (*backtrace)(void **buffer, int size) = + dlsym(libunwind, "unw_backtrace"); + if (backtrace != NULL) { + int nb = backtrace(frames, max_depth); + if (nb > 0) { + } + return nb; + } else { + DEBUG(print("symbols not found in libunwind.so\n")); + } + dlclose(libunwind); + } else { + DEBUG(print("libunwind.so could not be loaded\n")); + } + return -1; +} +#endif + +/* Call the old handler. */ +static void coffeecatch_call_old_signal_handler(const int code, siginfo_t *const si, + void * const sc) { + /* Call the "real" Java handler for JIT and internals. */ + if (code >= 0 && code < SIG_NUMBER_MAX) { + if (native_code_g.sa_old[code].sa_sigaction != NULL) { + native_code_g.sa_old[code].sa_sigaction(code, si, sc); + } else if (native_code_g.sa_old[code].sa_handler != NULL) { + native_code_g.sa_old[code].sa_handler(code); + } + } +} + +/* Unflag "on stack" */ +static void coffeecatch_revert_alternate_stack(void) { +#ifndef NO_USE_SIGALTSTACK + stack_t ss; + if (sigaltstack(NULL, &ss) == 0) { + ss.ss_flags &= ~SS_ONSTACK; + sigaltstack (&ss, NULL); + } +#endif +} + +/* Try to jump to userland. */ +static void coffeecatch_try_jump_userland(native_code_handler_struct* + const t, + const int code, + siginfo_t *const si, + void * const sc) { + (void) si; /* UNUSED */ + (void) sc; /* UNUSED */ + + /* Valid context ? */ + if (t != NULL && t->ctx_is_set) { + DEBUG(print("calling siglongjmp()\n")); + + /* Invalidate the context */ + t->ctx_is_set = 0; + + /* We need to revert the alternate stack before jumping. */ + coffeecatch_revert_alternate_stack(); + + /* + * Note on async-signal-safety of siglongjmp() [POSIX] : + * "Note that longjmp() and siglongjmp() are not in the list of + * async-signal-safe functions. This is because the code executing after + * longjmp() and siglongjmp() can call any unsafe functions with the same + * danger as calling those unsafe functions directly from the signal + * handler. Applications that use longjmp() and siglongjmp() from within + * signal handlers require rigorous protection in order to be portable. + * Many of the other functions that are excluded from the list are + * traditionally implemented using either malloc() or free() functions or + * the standard I/O library, both of which traditionally use data + * structures in a non-async-signal-safe manner. Since any combination of + * different functions using a common data structure can cause + * async-signal-safety problems, this volume of POSIX.1-2008 does not + * define the behavior when any unsafe function is called in a signal + * handler that interrupts an unsafe function." + */ + siglongjmp(t->ctx, code); + } +} + +static void coffeecatch_start_alarm(void) { + /* Ensure we do not deadlock. Default of ALRM is to die. + * (signal() and alarm() are signal-safe) */ + (void) alarm(30); +} + +static void coffeecatch_mark_alarm(native_code_handler_struct *const t) { + t->alarm = 1; +} + +/* Copy context infos (signal code, etc.) */ +static void coffeecatch_copy_context(native_code_handler_struct *const t, + const int code, siginfo_t *const si, + void *const sc) { + t->code = code; + t->si = *si; + if (sc != NULL) { + ucontext_t *const uc = (ucontext_t*) sc; + t->uc = *uc; + } else { + memset(&t->uc, 0, sizeof(t->uc)); + } + +#ifdef USE_UNWIND + /* Frame buffer initial position. */ + t->frames_size = 0; + + /* Skip us and the caller. */ + t->frames_skip = 2; + + /* Use the corkscrew library to extract the backtrace. */ +#ifdef USE_CORKSCREW + t->frames_size = coffeecatch_backtrace_signal(si, sc, t->frames, 0, + BACKTRACE_FRAMES_MAX); +#else + /* Unwind frames (equivalent to backtrace()) */ + _Unwind_Backtrace(coffeecatch_unwind_callback, t); +#endif + +#ifdef USE_LIBUNWIND + if (t->frames_size == 0) { + size_t i; + t->frames_size = coffeecatch_unwind_signal(si, sc, t->uframes, 0, + BACKTRACE_FRAMES_MAX); + for(i = 0 ; i < t->frames_size ; i++) { + t->frames[i].absolute_pc = (uintptr_t) t->uframes[i]; + t->frames[i].stack_top = 0; + t->frames[i].stack_size = 0; + } + } +#endif + + if (t->frames_size != 0) { + DEBUG(print("called _Unwind_Backtrace()\n")); + } else { + DEBUG(print("called _Unwind_Backtrace(), but no traces\n")); + } +#endif +} + +/* Return the thread-specific native_code_handler_struct structure, or + * @c null if no such structure is available. */ +static native_code_handler_struct* coffeecatch_get() { + return (native_code_handler_struct*) + pthread_getspecific(native_code_thread); +} + +int coffeecatch_cancel_pending_alarm() { + native_code_handler_struct *const t = coffeecatch_get(); + if (t != NULL && t->alarm) { + t->alarm = 0; + /* "If seconds is 0, a pending alarm request, if any, is canceled." */ + alarm(0); + return 0; + } + return -1; +} + +/* Internal signal pass-through. Allows to peek the "real" crash before + * calling the Java handler. Remember than Java needs many of the signals + * (for the JIT, for test-free NullPointerException handling, etc.) + * We record the siginfo_t context in this function each time it is being + * called, to be able to know what error caused an issue. + */ +static void coffeecatch_signal_pass(const int code, siginfo_t *const si, + void *const sc) { + native_code_handler_struct *t; + + DEBUG(print("caught signal\n")); + + /* Call the "real" Java handler for JIT and internals. */ + coffeecatch_call_old_signal_handler(code, si, sc); + + /* Still here ? + * FIXME TODO: This is the Dalvik behavior - but is it the SunJVM one ? */ + + /* Ensure we do not deadlock. Default of ALRM is to die. + * (signal() and alarm() are signal-safe) */ + signal(code, SIG_DFL); + coffeecatch_start_alarm(); + + /* Available context ? */ + t = coffeecatch_get(); + if (t != NULL) { + /* An alarm() call was triggered. */ + coffeecatch_mark_alarm(t); + + /* Take note of the signal. */ + coffeecatch_copy_context(t, code, si, sc); + + /* Back to the future. */ + coffeecatch_try_jump_userland(t, code, si, sc); + } + + /* Nope. (abort() is signal-safe) */ + DEBUG(print("calling abort()\n")); + signal(SIGABRT, SIG_DFL); + abort(); +} + +/* Internal crash handler for abort(). Java calls abort() if its signal handler + * could not resolve the signal ; thus calling us through this handler. */ +static void coffeecatch_signal_abort(const int code, siginfo_t *const si, + void *const sc) { + native_code_handler_struct *t; + + (void) sc; /* UNUSED */ + + DEBUG(print("caught abort\n")); + + /* Ensure we do not deadlock. Default of ALRM is to die. + * (signal() and alarm() are signal-safe) */ + signal(code, SIG_DFL); + coffeecatch_start_alarm(); + + /* Available context ? */ + t = coffeecatch_get(); + if (t != NULL) { + /* An alarm() call was triggered. */ + coffeecatch_mark_alarm(t); + + /* Take note (real "abort()") */ + coffeecatch_copy_context(t, code, si, sc); + + /* Back to the future. */ + coffeecatch_try_jump_userland(t, code, si, sc); + } + + /* No such restore point, call old signal handler then. */ + DEBUG(print("calling old signal handler\n")); + coffeecatch_call_old_signal_handler(code, si, sc); + + /* Nope. (abort() is signal-safe) */ + DEBUG(print("calling abort()\n")); + abort(); +} + +/* Internal globals initialization. */ +static int coffeecatch_handler_setup_global(void) { + if (native_code_g.initialized++ == 0) { + size_t i; + struct sigaction sa_abort; + struct sigaction sa_pass; + + DEBUG(print("installing global signal handlers\n")); + + /* Setup handler structure. */ + memset(&sa_abort, 0, sizeof(sa_abort)); + sigemptyset(&sa_abort.sa_mask); + sa_abort.sa_sigaction = coffeecatch_signal_abort; + sa_abort.sa_flags = SA_SIGINFO | SA_ONSTACK; + + memset(&sa_pass, 0, sizeof(sa_pass)); + sigemptyset(&sa_pass.sa_mask); + sa_pass.sa_sigaction = coffeecatch_signal_pass; + sa_pass.sa_flags = SA_SIGINFO | SA_ONSTACK; + + /* Allocate */ + native_code_g.sa_old = calloc(sizeof(struct sigaction), SIG_NUMBER_MAX); + if (native_code_g.sa_old == NULL) { + return -1; + } + + /* Setup signal handlers for SIGABRT (Java calls abort()) and others. **/ + for (i = 0; native_sig_catch[i] != 0; i++) { + const int sig = native_sig_catch[i]; + const struct sigaction * const action = + sig == SIGABRT ? &sa_abort : &sa_pass; + assert(sig < SIG_NUMBER_MAX); + if (sigaction(sig, action, &native_code_g.sa_old[sig]) != 0) { + return -1; + } + } + + /* Initialize thread var. */ + if (pthread_key_create(&native_code_thread, NULL) != 0) { + return -1; + } + + DEBUG(print("installed global signal handlers\n")); + } + + /* OK. */ + return 0; +} + +/** + * Free a native_code_handler_struct structure. + **/ +static int coffeecatch_native_code_handler_struct_free(native_code_handler_struct *const t) { + int code = 0; + + if (t == NULL) { + return -1; + } + +#ifndef NO_USE_SIGALTSTACK + /* Restore previous alternative stack. */ + if (t->stack_old.ss_sp != NULL && sigaltstack(&t->stack_old, NULL) != 0) { +#ifndef USE_SILENT_SIGALTSTACK + code = -1; +#endif + } +#endif + + /* Free alternative stack */ + if (t->stack_buffer != NULL) { + free(t->stack_buffer); + t->stack_buffer = NULL; + t->stack_buffer_size = 0; + } + + /* Free structure. */ + free(t); + + return code; +} + +/** + * Create a native_code_handler_struct structure. + **/ +static native_code_handler_struct* coffeecatch_native_code_handler_struct_init(void) { + stack_t stack; + native_code_handler_struct *const t = + calloc(sizeof(native_code_handler_struct), 1); + + if (t == NULL) { + return NULL; + } + + DEBUG(print("installing thread alternative stack\n")); + + /* Initialize structure */ + t->stack_buffer_size = SIG_STACK_BUFFER_SIZE; + t->stack_buffer = malloc(t->stack_buffer_size); + if (t->stack_buffer == NULL) { + coffeecatch_native_code_handler_struct_free(t); + return NULL; + } + + /* Setup alternative stack. */ + memset(&stack, 0, sizeof(stack)); + stack.ss_sp = t->stack_buffer; + stack.ss_size = t->stack_buffer_size; + stack.ss_flags = 0; + +#ifndef NO_USE_SIGALTSTACK + /* Install alternative stack. This is thread-safe */ + if (sigaltstack(&stack, &t->stack_old) != 0) { +#ifndef USE_SILENT_SIGALTSTACK + coffeecatch_native_code_handler_struct_free(t); + return NULL; +#endif + } +#endif + + return t; +} + +/** + * Acquire the crash handler for the current thread. + * The coffeecatch_handler_cleanup() must be called to release allocated + * resources. + **/ +static int coffeecatch_handler_setup(int setup_thread) { + int code; + + DEBUG(print("setup for a new handler\n")); + + /* Initialize globals. */ + if (pthread_mutex_lock(&native_code_g.mutex) != 0) { + return -1; + } + code = coffeecatch_handler_setup_global(); + if (pthread_mutex_unlock(&native_code_g.mutex) != 0) { + return -1; + } + + /* Global initialization failed. */ + if (code != 0) { + return -1; + } + + /* Initialize locals. */ + if (setup_thread && coffeecatch_get() == NULL) { + native_code_handler_struct *const t = + coffeecatch_native_code_handler_struct_init(); + + if (t == NULL) { + return -1; + } + + DEBUG(print("installing thread alternative stack\n")); + + /* Set thread-specific value. */ + if (pthread_setspecific(native_code_thread, t) != 0) { + coffeecatch_native_code_handler_struct_free(t); + return -1; + } + + DEBUG(print("installed thread alternative stack\n")); + } + + /* OK. */ + return 0; +} + +/** + * Release the resources allocated by a previous call to + * coffeecatch_handler_setup(). + * This function must be called as many times as + * coffeecatch_handler_setup() was called to fully release allocated + * resources. + **/ +static int coffeecatch_handler_cleanup() { + /* Cleanup locals. */ + native_code_handler_struct *const t = coffeecatch_get(); + if (t != NULL) { + DEBUG(print("removing thread alternative stack\n")); + + /* Erase thread-specific value now (detach). */ + if (pthread_setspecific(native_code_thread, NULL) != 0) { + assert(! "pthread_setspecific() failed"); + } + + /* Free handler and reset slternate stack */ + if (coffeecatch_native_code_handler_struct_free(t) != 0) { + return -1; + } + + DEBUG(print("removed thread alternative stack\n")); + } + + /* Cleanup globals. */ + if (pthread_mutex_lock(&native_code_g.mutex) != 0) { + assert(! "pthread_mutex_lock() failed"); + } + assert(native_code_g.initialized != 0); + if (--native_code_g.initialized == 0) { + size_t i; + + DEBUG(print("removing global signal handlers\n")); + + /* Restore signal handler. */ + for(i = 0; native_sig_catch[i] != 0; i++) { + const int sig = native_sig_catch[i]; + assert(sig < SIG_NUMBER_MAX); + if (sigaction(sig, &native_code_g.sa_old[sig], NULL) != 0) { + return -1; + } + } + + /* Free old structure. */ + free(native_code_g.sa_old); + native_code_g.sa_old = NULL; + + /* Delete thread var. */ + if (pthread_key_delete(native_code_thread) != 0) { + assert(! "pthread_key_delete() failed"); + } + + DEBUG(print("removed global signal handlers\n")); + } + if (pthread_mutex_unlock(&native_code_g.mutex) != 0) { + assert(! "pthread_mutex_unlock() failed"); + } + + return 0; +} + +/** + * Get the signal associated with the crash. + */ +int coffeecatch_get_signal() { + const native_code_handler_struct* const t = coffeecatch_get(); + if (t != NULL) { + return t->code; + } else { + return -1; + } +} + +/* Signal descriptions. + See +*/ +static const char* coffeecatch_desc_sig(int sig, int code) { + switch(sig) { + case SIGILL: + switch(code) { + case ILL_ILLOPC: + return "Illegal opcode"; + case ILL_ILLOPN: + return "Illegal operand"; + case ILL_ILLADR: + return "Illegal addressing mode"; + case ILL_ILLTRP: + return "Illegal trap"; + case ILL_PRVOPC: + return "Privileged opcode"; + case ILL_PRVREG: + return "Privileged register"; + case ILL_COPROC: + return "Coprocessor error"; + case ILL_BADSTK: + return "Internal stack error"; + default: + return "Illegal operation"; + } + break; + case SIGFPE: + switch(code) { + case FPE_INTDIV: + return "Integer divide by zero"; + case FPE_INTOVF: + return "Integer overflow"; + case FPE_FLTDIV: + return "Floating-point divide by zero"; + case FPE_FLTOVF: + return "Floating-point overflow"; + case FPE_FLTUND: + return "Floating-point underflow"; + case FPE_FLTRES: + return "Floating-point inexact result"; + case FPE_FLTINV: + return "Invalid floating-point operation"; + case FPE_FLTSUB: + return "Subscript out of range"; + default: + return "Floating-point"; + } + break; + case SIGSEGV: + switch(code) { + case SEGV_MAPERR: + return "Address not mapped to object"; + case SEGV_ACCERR: + return "Invalid permissions for mapped object"; + default: + return "Segmentation violation"; + } + break; + case SIGBUS: + switch(code) { + case BUS_ADRALN: + return "Invalid address alignment"; + case BUS_ADRERR: + return "Nonexistent physical address"; + case BUS_OBJERR: + return "Object-specific hardware error"; + default: + return "Bus error"; + } + break; + case SIGTRAP: + switch(code) { + case TRAP_BRKPT: + return "Process breakpoint"; + case TRAP_TRACE: + return "Process trace trap"; + default: + return "Trap"; + } + break; + case SIGCHLD: + switch(code) { + case CLD_EXITED: + return "Child has exited"; + case CLD_KILLED: + return "Child has terminated abnormally and did not create a core file"; + case CLD_DUMPED: + return "Child has terminated abnormally and created a core file"; + case CLD_TRAPPED: + return "Traced child has trapped"; + case CLD_STOPPED: + return "Child has stopped"; + case CLD_CONTINUED: + return "Stopped child has continued"; + default: + return "Child"; + } + break; + case SIGPOLL: + switch(code) { + case POLL_IN: + return "Data input available"; + case POLL_OUT: + return "Output buffers available"; + case POLL_MSG: + return "Input message available"; + case POLL_ERR: + return "I/O error"; + case POLL_PRI: + return "High priority input available"; + case POLL_HUP: + return "Device disconnected"; + default: + return "Pool"; + } + break; + case SIGABRT: + return "Process abort signal"; + case SIGALRM: + return "Alarm clock"; + case SIGCONT: + return "Continue executing, if stopped"; + case SIGHUP: + return "Hangup"; + case SIGINT: + return "Terminal interrupt signal"; + case SIGKILL: + return "Kill"; + case SIGPIPE: + return "Write on a pipe with no one to read it"; + case SIGQUIT: + return "Terminal quit signal"; + case SIGSTOP: + return "Stop executing"; + case SIGTERM: + return "Termination signal"; + case SIGTSTP: + return "Terminal stop signal"; + case SIGTTIN: + return "Background process attempting read"; + case SIGTTOU: + return "Background process attempting write"; + case SIGUSR1: + return "User-defined signal 1"; + case SIGUSR2: + return "User-defined signal 2"; + case SIGPROF: + return "Profiling timer expired"; + case SIGSYS: + return "Bad system call"; + case SIGVTALRM: + return "Virtual timer expired"; + case SIGURG: + return "High bandwidth data is available at a socket"; + case SIGXCPU: + return "CPU time limit exceeded"; + case SIGXFSZ: + return "File size limit exceeded"; + default: + switch(code) { + case SI_USER: + return "Signal sent by kill()"; + case SI_QUEUE: + return "Signal sent by the sigqueue()"; + case SI_TIMER: + return "Signal generated by expiration of a timer set by timer_settime()"; + case SI_ASYNCIO: + return "Signal generated by completion of an asynchronous I/O request"; + case SI_MESGQ: + return + "Signal generated by arrival of a message on an empty message queue"; + default: + return "Unknown signal"; + } + break; + } +} + +/** + * Get the backtrace size. Returns 0 if no backtrace is available. + */ +size_t coffeecatch_get_backtrace_size(void) { +#ifdef USE_UNWIND + const native_code_handler_struct* const t = coffeecatch_get(); + if (t != NULL) { + return t->frames_size; + } else { + return 0; + } +#else + return 0; +#endif +} + +/** + * Get the th element of the backtrace, or 0 upon error. + */ +uintptr_t coffeecatch_get_backtrace(ssize_t index) { +#ifdef USE_UNWIND + const native_code_handler_struct* const t = coffeecatch_get(); + if (t != NULL) { + if (index < 0) { + index = t->frames_size + index; + } + if (index >= 0 && (size_t) index < t->frames_size) { +#ifdef USE_CORKSCREW + return t->frames[index].absolute_pc; +#else + return t->frames[index]; +#endif + } + } +#else + (void) index; +#endif + return 0; +} + +/** + * Get the program counter, given a pointer to a ucontext_t context. + **/ +static uintptr_t coffeecatch_get_pc_from_ucontext(const ucontext_t *uc) { +#if (defined(__arm__)) + return uc->uc_mcontext.arm_pc; +#elif defined(__aarch64__) + return uc->uc_mcontext.pc; +#elif (defined(__x86_64__)) + return uc->uc_mcontext.gregs[REG_RIP]; +#elif (defined(__i386)) + return uc->uc_mcontext.gregs[REG_EIP]; +#elif (defined (__ppc__)) || (defined (__powerpc__)) + return uc->uc_mcontext.regs->nip; +#elif (defined(__hppa__)) + return uc->uc_mcontext.sc_iaoq[0] & ~0x3UL; +#elif (defined(__sparc__) && defined (__arch64__)) + return uc->uc_mcontext.mc_gregs[MC_PC]; +#elif (defined(__sparc__) && !defined (__arch64__)) + return uc->uc_mcontext.gregs[REG_PC]; +#elif (defined(__mips__)) + return uc->uc_mcontext.gregs[31]; +#else +#error "Architecture is unknown, please report me!" +#endif +} + +/* Is this module name look like a DLL ? + FIXME: find a better way to do that... */ +static int coffeecatch_is_dll(const char *name) { + size_t i; + for(i = 0; name[i] != '\0'; i++) { + if (name[i + 0] == '.' && + name[i + 1] == 's' && + name[i + 2] == 'o' && + ( name[i + 3] == '\0' || name[i + 3] == '.') ) { + return 1; + } + } + return 0; +} + +/* Extract a line information on a PC address. */ +static void format_pc_address_cb(uintptr_t pc, + void (*fun)(void *arg, const char *module, + uintptr_t addr, + const char *function, + uintptr_t offset), void *arg) { + if (pc != 0) { + Dl_info info; + void * const addr = (void*) pc; + /* dladdr() returns 0 on error, and nonzero on success. */ + if (dladdr(addr, &info) != 0 && info.dli_fname != NULL) { + const uintptr_t near = (uintptr_t) info.dli_saddr; + const uintptr_t offs = pc - near; + const uintptr_t addr_rel = pc - (uintptr_t) info.dli_fbase; + /* We need the absolute address for the main module (?). + TODO FIXME to be investigated. */ + const uintptr_t addr_to_use = coffeecatch_is_dll(info.dli_fname) + ? addr_rel : pc; + fun(arg, info.dli_fname, addr_to_use, info.dli_sname, offs); + } else { + fun(arg, NULL, pc, NULL, 0); + } + } +} + +typedef struct t_print_fun { + char *buffer; + size_t buffer_size; +} t_print_fun; + +static void print_fun(void *arg, const char *module, uintptr_t uaddr, + const char *function, uintptr_t offset) { + t_print_fun *const t = (t_print_fun*) arg; + char *const buffer = t->buffer; + const size_t buffer_size = t->buffer_size; + const void*const addr = (void*) uaddr; + if (module == NULL) { + snprintf(buffer, buffer_size, "[at %p]", addr); + } else if (function != NULL) { + snprintf(buffer, buffer_size, "[at %s:%p (%s+0x%x)]", module, addr, + function, (int) offset); + } else { + snprintf(buffer, buffer_size, "[at %s:%p]", module, addr); + } +} + +/* Format a line information on a PC address. */ +static void format_pc_address(char *buffer, size_t buffer_size, uintptr_t pc) { + t_print_fun t; + t.buffer = buffer; + t.buffer_size = buffer_size; + format_pc_address_cb(pc, print_fun, &t); +} + +/** + * Get the full error message associated with the crash. + */ +const char* coffeecatch_get_message() { + const int error = errno; + const native_code_handler_struct* const t = coffeecatch_get(); + + /* Found valid handler. */ + if (t != NULL) { + char * const buffer = t->stack_buffer; + const size_t buffer_len = t->stack_buffer_size; + size_t buffer_offs = 0; + + const char* const posix_desc = + coffeecatch_desc_sig(t->si.si_signo, t->si.si_code); + + /* Assertion failure ? */ + if ((t->code == SIGABRT +#ifdef __ANDROID__ + /* See Android BUG #16672: + * "C assert() failure causes SIGSEGV when it should cause SIGABRT" */ + || (t->code == SIGSEGV && (uintptr_t) t->si.si_addr == 0xdeadbaad) +#endif + ) && t->expression != NULL) { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, + "assertion '%s' failed at %s:%d", + t->expression, t->file, t->line); + buffer_offs += strlen(&buffer[buffer_offs]); + } + /* Signal */ + else { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, "signal %d", + t->si.si_signo); + buffer_offs += strlen(&buffer[buffer_offs]); + + /* Description */ + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, " (%s)", + posix_desc); + buffer_offs += strlen(&buffer[buffer_offs]); + + /* Address of faulting instruction */ + if (t->si.si_signo == SIGILL || t->si.si_signo == SIGSEGV) { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, " at address %p", + t->si.si_addr); + buffer_offs += strlen(&buffer[buffer_offs]); + } + } + + /* [POSIX] If non-zero, an errno value associated with this signal, + as defined in . */ + if (t->si.si_errno != 0) { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, ": "); + buffer_offs += strlen(&buffer[buffer_offs]); + if (strerror_r(t->si.si_errno, &buffer[buffer_offs], + buffer_len - buffer_offs) == 0) { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, + "unknown error"); + buffer_offs += strlen(&buffer[buffer_offs]); + } + } + + /* Sending process ID. */ + if (t->si.si_signo == SIGCHLD && t->si.si_pid != 0) { + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, + " (sent by pid %d)", (int) t->si.si_pid); + buffer_offs += strlen(&buffer[buffer_offs]); + } + + /* Faulting program counter location. */ + if (coffeecatch_get_pc_from_ucontext(&t->uc) != 0) { + const uintptr_t pc = coffeecatch_get_pc_from_ucontext(&t->uc); + snprintf(&buffer[buffer_offs], buffer_len - buffer_offs, " "); + buffer_offs += strlen(&buffer[buffer_offs]); + format_pc_address(&buffer[buffer_offs], buffer_len - buffer_offs, pc); + buffer_offs += strlen(&buffer[buffer_offs]); + } + + /* Return string. */ + buffer[buffer_offs] = '\0'; + return t->stack_buffer; + } else { + /* Static buffer in case of emergency */ + static char buffer[256]; +#ifdef _GNU_SOURCE + return strerror_r(error, &buffer[0], sizeof(buffer)); +#else + const int code = strerror_r(error, &buffer[0], sizeof(buffer)); + errno = error; + if (code == 0) { + return buffer; + } else { + return "unknown error during crash handler setup"; + } +#endif + } +} + +#if (defined(USE_CORKSCREW)) +typedef struct t_coffeecatch_backtrace_symbols_fun { + void (*fun)(void *arg, const char *module, uintptr_t addr, + const char *function, uintptr_t offset); + void *arg; +} t_coffeecatch_backtrace_symbols_fun; + +static void coffeecatch_backtrace_symbols_fun(void *arg, const backtrace_symbol_t *sym) { + t_coffeecatch_backtrace_symbols_fun *const bt = + (t_coffeecatch_backtrace_symbols_fun*) arg; + const char *symbol = sym->demangled_name != NULL + ? sym->demangled_name : sym->symbol_name; + const uintptr_t rel = sym->relative_pc - sym->relative_symbol_addr; + bt->fun(bt->arg, sym->map_name, sym->relative_pc, symbol, rel); +} +#endif + +/** + * Enumerate backtrace information. + */ +void coffeecatch_get_backtrace_info(void (*fun)(void *arg, + const char *module, + uintptr_t addr, + const char *function, + uintptr_t offset), void *arg) { + const native_code_handler_struct* const t = coffeecatch_get(); + if (t != NULL) { + size_t i; +#if (defined(USE_CORKSCREW)) + t_coffeecatch_backtrace_symbols_fun bt; + bt.fun = fun; + bt.arg = arg; + if (coffeecatch_backtrace_symbols(t->frames, t->frames_size, + coffeecatch_backtrace_symbols_fun, + &bt)) { + return; + } +#endif + for(i = 0; i < t->frames_size; i++) { + const uintptr_t pc = t->frames[i].absolute_pc; + format_pc_address_cb(pc, fun, arg); + } + } +} + +/** + * Returns 1 if we are already inside a coffeecatch block, 0 otherwise. + */ +int coffeecatch_inside() { + native_code_handler_struct *const t = coffeecatch_get(); + if (t != NULL && t->reenter > 0) { + t->reenter++; + return 1; + } + return 0; +} + +/** + * Calls coffeecatch_handler_setup(1) to setup a crash handler, mark the + * context as valid, and return 0 upon success. + */ +int coffeecatch_setup() { + if (coffeecatch_handler_setup(1) == 0) { + native_code_handler_struct *const t = coffeecatch_get(); + assert(t != NULL); + assert(t->reenter == 0); + t->reenter = 1; + t->ctx_is_set = 1; + return 0; + } else { + return -1; + } +} + +/** + * Calls coffeecatch_handler_cleanup() + */ +void coffeecatch_cleanup() { + native_code_handler_struct *const t = coffeecatch_get(); + assert(t != NULL); + assert(t->reenter > 0); + t->reenter--; + if (t->reenter == 0) { + t->ctx_is_set = 0; + coffeecatch_handler_cleanup(); + } +} + +sigjmp_buf* coffeecatch_get_ctx() { + native_code_handler_struct* t = coffeecatch_get(); + assert(t != NULL); + return &t->ctx; +} + +void coffeecatch_abort(const char* exp, const char* file, int line) { + native_code_handler_struct *const t = coffeecatch_get(); + if (t != NULL) { + t->expression = exp; + t->file = file; + t->line = line; + } + abort(); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1f6d1b7fe5c173efe404d616a3d24df20e61addf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/coffeecatch.h @@ -0,0 +1,228 @@ +/* CoffeeCatch, a tiny native signal handler/catcher for JNI code. + * (especially for Android/Dalvik) + * + * Copyright (c) 2013, Xavier Roche (http://www.httrack.com/) + * All rights reserved. + * See the "License" section below for the licensing terms. + * + * Description: + * + * Allows to "gracefully" recover from a signal (segv, sibus...) as if it was + * a Java exception. It will not gracefully recover from allocator/mutexes + * corruption etc., however, but at least "most" gentle crashes (null pointer + * dereferencing, integer division, stack overflow etc.) should be handled + * without too much troubles. + * + * The handler is thread-safe, but client must have exclusive control on the + * signal handlers (ie. the library is installing its own signal handlers on + * top of the existing ones). + * + * You must build all your libraries with `-funwind-tables', to get proper + * unwinding information on all binaries. On ARM, you may also use the + * `--no-merge-exidx-entries` linker switch, to solve certain issues with + * unwinding (the switch is possibly not needed anymore). + * On Android, this can be achieved by using this line in the Android.mk file + * in each library block: + * LOCAL_CFLAGS := -funwind-tables -Wl,--no-merge-exidx-entries + * + * Example: + * + * COFFEE_TRY() { + * call_some_native_function() + * } COFFEE_CATCH() { + * const char*const message = coffeecatch_get_message(); + * jclass cls = (*env)->FindClass(env, "java/lang/RuntimeException"); + * (*env)->ThrowNew(env, cls, strdup(message)); + * } COFFEE_END(); + * + * Implementation notes: + * + * Currently the library is installing both alternate stack and signal + * handlers for known signals (SIGABRT, SIGILL, SIGTRAP, SIGBUS, SIGFPE, + * SIGSEGV, SIGSTKFLT), and is using sigsetjmp()/siglongjmp() to return to + * "userland" (compared to signal handler context). As a security, an alarm + * is started as soon as a fatal signal is detected (ie. not something the + * JVM will handle) to kill the process after a grace period. Be sure your + * program will exit quickly after the error is caught, or call alarm(0) + * to cancel the pending time-bomb. + * The signal handlers had to be written with caution, because the virtual + * machine might be using signals (including SEGV) to handle JIT compiler, + * and some clever optimizations (such as NullPointerException handling) + * We are using several signal-unsafe functions, namely: + * - siglongjmp() to return to userland + * - pthread_getspecific() to get thread-specific setup + * + * License: + * + * Copyright (c) 2013, Xavier Roche (http://www.httrack.com/) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef COFFEECATCH_H +#define COFFEECATCH_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Setup crash handler to enter in a protected section. If a recognized signal + * is received in this section, the execution will be diverted to the + * COFFEE_CATCH() block. + * + * Note: you MUST use the following pattern when using this macro: + * COFFEE_TRY() { + * .. protected section without exit point + * } COFFEE_CATCH() { + * .. handler section without exit point + * } COFFEE_END(); + * + * You can not exit the protected section block, or the handler section block, + * using statements such as "return", because the cleanup code would not be + * executed. + * + * It is advised to enclose this complete try/catch/end block in a dedicated + * function declared extern or __attribute__ ((noinline)). + * + * Example: + * + * void my_native_function(JNIEnv* env, jobject object, jint *retcode) { + * COFFEE_TRY() { + * *retcode = call_dangerous_function(env, object); + * } COFFEE_CATCH() { + * const char*const message = coffeecatch_get_message(); + * jclass cls = (*env)->FindClass(env, "java/lang/RuntimeException"); + * (*env)->ThrowNew(env, cls, strdup(message)); + * *retcode = -1; + * } COFFEE_END(); + * } + * + * In addition, the following restrictions MUST be followed: + * - the function must be declared extern, or with the special attribute + * __attribute__ ((noinline)). + * - you must not use local variables before the complete try/catch/end block, + * or define them as "volatile". + * - your function should not ignore the crash silently, as the library will + * ensure the process is killed after a grace period (typically 30s) to + * prevent any deadlock that may occur if the crash was caught inside a + * non-signal-safe function, for example (such as malloc()). + * +COFFEE_TRY() + **/ + +/** + * Declare the signal handler block. This block will be executed if a signal + * was received, and recognized, in the previous COFFEE_TRY() {} section. + * You may call audit functions in this block, such as coffeecatch_get_signal() + * or coffeecatch_get_message(). + * +COFFEE_CATCH() + **/ + +/** + * Declare the end of the COFFEE_TRY()/COFFEE_CATCH() section. + * Diagnostic functions must not be called beyond this point. + * +COFFEE_END() + **/ + +/** + * Get the signal associated with the crash. + * This function can only be called inside a COFFEE_CATCH() block. + */ +extern int coffeecatch_get_signal(void); + +/** + * Get the full error message associated with the crash. + * This function can only be called inside a COFFEE_CATCH() block, and the + * returned pointer is only valid within this block. (you may want to copy + * the string in a static buffer, or use strdup()) + */ +const char* coffeecatch_get_message(void); + +/** + * Raise an abort() signal in the current thread. If the current code section + * is protected, the 'exp', 'file' and 'line' information are stored for + * further audit. + */ +extern void coffeecatch_abort(const char* exp, const char* file, int line); + +/** + * Assertion check. If the expression is false, an abort() signal is raised + * using coffeecatch_abort(). + */ +#define coffeecatch_assert(EXP) (void)( (EXP) || (coffeecatch_abort(#EXP, __FILE__, __LINE__), 0) ) + +/** + * Get the backtrace size, or 0 upon error. + * This function can only be called inside a COFFEE_CATCH() block. + */ +extern size_t coffeecatch_get_backtrace_size(void); + +/** + * Get the backtrace pointer, or 0 upon error. + * This function can only be called inside a COFFEE_CATCH() block. + */ +extern uintptr_t coffeecatch_get_backtrace(ssize_t index); + +/** + * Enumerate the backtrace with information. + * This function can only be called inside a COFFEE_CATCH() block. + */ +extern void coffeecatch_get_backtrace_info(void (*fun)(void *arg, + const char *module, + uintptr_t addr, + const char *function, + uintptr_t offset), void *arg); + +/** + * Cancel any pending alarm() triggered after a signal was caught. + * Calling this function is dangerous, because it exposes the process to + * a possible deadlock if the signal was caught due to internal low-level + * library error (mutex being in a locked state, for example). + */ +extern int coffeecatch_cancel_pending_alarm(void); + +/** Internal functions & definitions, not to be used directly. **/ +#include +extern int coffeecatch_inside(void); +extern int coffeecatch_setup(void); +extern sigjmp_buf* coffeecatch_get_ctx(void); +extern void coffeecatch_cleanup(void); +#define COFFEE_TRY() \ + if (coffeecatch_inside() || \ + (coffeecatch_setup() == 0 \ + && sigsetjmp(*coffeecatch_get_ctx(), 1) == 0)) +#define COFFEE_CATCH() else +#define COFFEE_END() coffeecatch_cleanup() +/** End of internal functions & definitions. **/ + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_atomic.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_atomic.h new file mode 100644 index 0000000000000000000000000000000000000000..54d082eaf6ff20c0f1bfb1b494bfd5aebb23a23b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_atomic.h @@ -0,0 +1,1199 @@ +#ifndef DH_H_ATOMIC__ +#define DH_H_ATOMIC__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* C11 */ +#if defined(HAVE_ATOMIC) && __STDC_VERSION__ >= 201112L && \ + !defined(__STDC_NO_ATOMICS__) + +#include + +#define DH_ATOMIC _Atomic + +#define DH_ATOMIC_BOOL_LOCK_FREE ATOMIC_BOOL_LOCK_FREE +#define DH_ATOMIC_CHAR_LOCK_FREE ATOMIC_CHAR_LOCK_FREE +#define DH_ATOMIC_WCHAR_T_LOCK_FREE ATOMIC_WCHAR_T_LOCK_FREE +#define DH_ATOMIC_SHORT_LOCK_FREE ATOMIC_SHORT_LOCK_FREE +#define DH_ATOMIC_INT_LOCK_FREE ATOMIC_INT_LOCK_FREE +#define DH_ATOMIC_LONG_LOCK_FREE ATOMIC_LONG_LOCK_FREE +#define DH_ATOMIC_LLONG_LOCK_FREE ATOMIC_LLONG_LOCK_FREE +#define DH_ATOMIC_POINTER_LOCK_FREE ATOMIC_POINTER_LOCK_FREE + +#define re_memory_order_relaxed memory_order_relaxed +#define re_memory_order_acquire memory_order_acquire +#define re_memory_order_release memory_order_release +#define re_memory_order_acq_rel memory_order_acq_rel +#define re_memory_order_seq_cst memory_order_seq_cst + +#define re_atomic_store(_a, _v, _mo) \ + atomic_store_explicit(_a, _v, _mo) + +#define re_atomic_load(_a, _mo) \ + atomic_load_explicit(_a, _mo) + +#define re_atomic_exchange(_a, _v, _mo) \ + atomic_exchange_explicit(_a, _v, _mo) + +#define re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + atomic_compare_exchange_strong_explicit(\ + _a, _expected, _desired, _success_mo, _fail_mo) + +#define re_atomic_compare_exchange_weak(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + atomic_compare_exchange_weak_explicit(\ + _a, _expected, _desired, _success_mo, _fail_mo) + +#define re_atomic_fetch_add(_a, _v, _mo) \ + atomic_fetch_add_explicit(_a, _v, _mo) + +#define re_atomic_fetch_sub(_a, _v, _mo) \ + atomic_fetch_sub_explicit(_a, _v, _mo) + +#define re_atomic_fetch_or(_a, _v, _mo) \ + atomic_fetch_or_explicit(_a, _v, _mo) + +#define re_atomic_fetch_xor(_a, _v, _mo) \ + atomic_fetch_xor_explicit(_a, _v, _mo) + +#define re_atomic_fetch_and(_a, _v, _mo) \ + atomic_fetch_and_explicit(_a, _v, _mo) + +/* gcc-style __atomic* intrinsics. + * Note: clang-cl also supports these, even though it impersonates MSVC. */ +#elif (defined(__GNUC__) || defined(__clang__)) && \ + defined(__GCC_ATOMIC_BOOL_LOCK_FREE) && \ + defined(__GCC_ATOMIC_CHAR_LOCK_FREE) && \ + defined(__GCC_ATOMIC_WCHAR_T_LOCK_FREE) && \ + defined(__GCC_ATOMIC_SHORT_LOCK_FREE) && \ + defined(__GCC_ATOMIC_INT_LOCK_FREE) && \ + defined(__GCC_ATOMIC_LONG_LOCK_FREE) && \ + defined(__GCC_ATOMIC_LLONG_LOCK_FREE) && \ + defined(__GCC_ATOMIC_POINTER_LOCK_FREE) && \ + defined(__ATOMIC_RELAXED) && defined(__ATOMIC_ACQUIRE) && \ + defined(__ATOMIC_RELEASE) && defined(__ATOMIC_ACQ_REL) && \ + defined(__ATOMIC_SEQ_CST) + +#define DH_ATOMIC_BOOL_LOCK_FREE __GCC_ATOMIC_BOOL_LOCK_FREE +#define DH_ATOMIC_CHAR_LOCK_FREE __GCC_ATOMIC_CHAR_LOCK_FREE +#define DH_ATOMIC_WCHAR_T_LOCK_FREE __GCC_ATOMIC_WCHAR_T_LOCK_FREE +#define DH_ATOMIC_SHORT_LOCK_FREE __GCC_ATOMIC_SHORT_LOCK_FREE +#define DH_ATOMIC_INT_LOCK_FREE __GCC_ATOMIC_INT_LOCK_FREE +#define DH_ATOMIC_LONG_LOCK_FREE __GCC_ATOMIC_LONG_LOCK_FREE +#define DH_ATOMIC_LLONG_LOCK_FREE __GCC_ATOMIC_LLONG_LOCK_FREE +#define DH_ATOMIC_POINTER_LOCK_FREE __GCC_ATOMIC_POINTER_LOCK_FREE + +#define re_memory_order_relaxed __ATOMIC_RELAXED +#define re_memory_order_acquire __ATOMIC_ACQUIRE +#define re_memory_order_release __ATOMIC_RELEASE +#define re_memory_order_acq_rel __ATOMIC_ACQ_REL +#define re_memory_order_seq_cst __ATOMIC_SEQ_CST + +#define re_atomic_store(_a, _v, _mo) \ + __atomic_store_n(_a, _v, _mo) + +#define re_atomic_load(_a, _mo) \ + __atomic_load_n(_a, _mo) + +#define re_atomic_exchange(_a, _v, _mo) \ + __atomic_exchange_n(_a, _v, _mo) + +#define re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + __atomic_compare_exchange_n(\ + _a, _expected, _desired, 0, _success_mo, _fail_mo) + +#define re_atomic_compare_exchange_weak(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + __atomic_compare_exchange_n(\ + _a, _expected, _desired, 1, _success_mo, _fail_mo) + +#define re_atomic_fetch_add(_a, _v, _mo) \ + __atomic_fetch_add(_a, _v, _mo) + +#define re_atomic_fetch_sub(_a, _v, _mo) \ + __atomic_fetch_sub(_a, _v, _mo) + +#define re_atomic_fetch_or(_a, _v, _mo) \ + __atomic_fetch_or(_a, _v, _mo) + +#define re_atomic_fetch_xor(_a, _v, _mo) \ + __atomic_fetch_xor(_a, _v, _mo) + +#define re_atomic_fetch_and(_a, _v, _mo) \ + __atomic_fetch_and(_a, _v, _mo) + +/* gcc-style __sync* intrinsics. */ +#elif defined(__GNUC__) && \ + (defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_1) || \ + defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_2) || \ + defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_4) || \ + defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_8)) + +#if !defined(__SIZEOF_SHORT__) || !defined(__SIZEOF_INT__) || \ + !defined(__SIZEOF_LONG__) || !defined(__SIZEOF_LONG_LONG__) +#include +#endif +#if !defined(__SIZEOF_POINTER__) +#include +#endif +#if !defined(__SIZEOF_WCHAR_T__) +#include +#endif + +#if defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_1) +#define DH_ATOMIC_CHAR_LOCK_FREE 2 +#endif + +#if defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_2) +#if (defined(__SIZEOF_SHORT__) && __SIZEOF_SHORT__ == 2) || \ + (defined(USHRT_MAX) && USHRT_MAX == 0xffffu) +#define DH_ATOMIC_SHORT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_INT__) && __SIZEOF_INT__ == 2) || \ + (defined(UINT_MAX) && UINT_MAX == 0xffffu) +#define DH_ATOMIC_INT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 2) || \ + (defined(ULONG_MAX) && ULONG_MAX == 0xffffu) +#define DH_ATOMIC_LONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 2) || \ + (defined(ULLONG_MAX) && ULLONG_MAX == 0xffffu) +#define DH_ATOMIC_LLONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 2) || \ + (defined(UINTPTR_MAX) && UINTPTR_MAX == 0xffffu) +#define DH_ATOMIC_POINTER_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_WCHAR_T__) && __SIZEOF_WCHAR_T__ == 2) || \ + (defined(WCHAR_MAX) && (WCHAR_MAX == 0xffff || WCHAR_MAX == 0x7fff)) +#define DH_ATOMIC_WCHAR_T_LOCK_FREE 2 +#endif +#endif + +#if defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_4) +#if (defined(__SIZEOF_SHORT__) && __SIZEOF_SHORT__ == 4) || \ + (defined(USHRT_MAX) && USHRT_MAX == 0xffffffffu) +#define DH_ATOMIC_SHORT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_INT__) && __SIZEOF_INT__ == 4) || \ + (defined(UINT_MAX) && UINT_MAX == 0xffffffffu) +#define DH_ATOMIC_INT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ + (defined(ULONG_MAX) && ULONG_MAX == 0xffffffffu) +#define DH_ATOMIC_LONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 4) || \ + (defined(ULLONG_MAX) && ULLONG_MAX == 0xffffffffu) +#define DH_ATOMIC_LLONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \ + (defined(UINTPTR_MAX) && UINTPTR_MAX == 0xffffffffu) +#define DH_ATOMIC_POINTER_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_WCHAR_T__) && __SIZEOF_WCHAR_T__ == 4) || \ + (defined(WCHAR_MAX) && (WCHAR_MAX == 0xffffffff || \ + WCHAR_MAX == 0x7fffffff)) +#define DH_ATOMIC_WCHAR_T_LOCK_FREE 2 +#endif +#endif + +#if defined(__GCC_HAVE_SYNC_COMPADH_AND_SWAP_8) +#if (defined(__SIZEOF_SHORT__) && __SIZEOF_SHORT__ == 8) || \ + (defined(USHRT_MAX) && USHRT_MAX == 0xffffffffffffffffu) +#define DH_ATOMIC_SHORT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_INT__) && __SIZEOF_INT__ == 8) || \ + (defined(UINT_MAX) && UINT_MAX == 0xffffffffffffffffu) +#define DH_ATOMIC_INT_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ + (defined(ULONG_MAX) && ULONG_MAX == 0xffffffffffffffffu) +#define DH_ATOMIC_LONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_LONG_LONG__) && __SIZEOF_LONG_LONG__ == 8) || \ + (defined(ULLONG_MAX) && ULLONG_MAX == 0xffffffffffffffffu) +#define DH_ATOMIC_LLONG_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8) || \ + (defined(UINTPTR_MAX) && UINTPTR_MAX == 0xffffffffffffffffu) +#define DH_ATOMIC_POINTER_LOCK_FREE 2 +#endif +#if (defined(__SIZEOF_WCHAR_T__) && __SIZEOF_WCHAR_T__ == 8) || \ + (defined(WCHAR_MAX) && (WCHAR_MAX == 0xffffffffffffffff || \ + WCHAR_MAX == 0x7fffffffffffffff)) +#define DH_ATOMIC_WCHAR_T_LOCK_FREE 2 +#endif +#endif + +#if !defined(DH_ATOMIC_CHAR_LOCK_FREE) +#define DH_ATOMIC_CHAR_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_SHORT_LOCK_FREE) +#define DH_ATOMIC_SHORT_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_INT_LOCK_FREE) +#define DH_ATOMIC_INT_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_LONG_LOCK_FREE) +#define DH_ATOMIC_LONG_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_LLONG_LOCK_FREE) +#define DH_ATOMIC_LLONG_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_POINTER_LOCK_FREE) +#define DH_ATOMIC_POINTER_LOCK_FREE 0 +#endif +#if !defined(DH_ATOMIC_WCHAR_T_LOCK_FREE) +#define DH_ATOMIC_WCHAR_T_LOCK_FREE 0 +#endif + +/* Assume bool is always 1 byte. Add platform-specific exceptions, + * if needed. */ +#define DH_ATOMIC_BOOL_LOCK_FREE DH_ATOMIC_CHAR_LOCK_FREE + +/* These constants match __ATOMIC_* predefined macros on + * gcc versions that support __atomic intrinsics. */ +#define re_memory_order_relaxed 0 +#define re_memory_order_acquire 2 +#define re_memory_order_release 3 +#define re_memory_order_acq_rel 4 +#define re_memory_order_seq_cst 5 + +#if defined(__x86_64__) + +#define re_atomic_store(_a, _v, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val = (_v);\ + if ((_mo) != re_memory_order_seq_cst) {\ + __asm__ __volatile__ ("mov %1, %0"\ + : "=m" (*(_a))\ + : "q" (_val)\ + : "memory");\ + }\ + else {\ + __asm__ __volatile__ ("xchg %1, %0"\ + : "=m" (*(_a)), "+q" (_val)\ + : \ + : "memory");\ + }\ + }) + +#define re_atomic_load(_a, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val;\ + __asm__ __volatile__ ("mov %1, %0"\ + : "=q" (_val)\ + : "m" (*(_a))\ + : "memory");\ + _val;\ + }) + +#define re_atomic_exchange(_a, _v, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val = (_v);\ + __asm__ __volatile__ ("xchg %1, %0"\ + : "+m" (*(_a)), "+q" (_val)\ + : \ + : "memory");\ + _val;\ + }) + +#elif defined(__i386__) + +#define re_atomic_store(_a, _v, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val = (_v);\ + if (sizeof(_val) < 8) {\ + if ((_mo) != re_memory_order_seq_cst) {\ + __asm__ __volatile__ ("mov %1, %0"\ + : "=m" (*(_a))\ + : "q" (_val)\ + : "memory");\ + }\ + else {\ + __asm__ __volatile__ ("xchg %1, %0"\ + : "=m" (*(_a)), "+q" (_val)\ + : \ + : "memory");\ + }\ + }\ + else {\ + __typeof__(*(_a)) _expected = *(_a);\ + while (1) {\ + __typeof__(*(_a)) _prev_val =\ + __sync_val_compare_and_swap(\ + _a, _expected, _val);\ + if (_prev_val == _expected)\ + break;\ + _expected = _prev_val;\ + }\ + }\ + }) + +#define re_atomic_load(_a, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val;\ + if (sizeof(_val) < 8) {\ + __asm__ __volatile__ ("mov %1, %0"\ + : "=q" (_val)\ + : "m" (*(_a))\ + : "memory");\ + }\ + else {\ + _val = __sync_val_compare_and_swap(\ + _a,\ + (__typeof__(*(_a)))0,\ + (__typeof__(*(_a)))0);\ + }\ + _val;\ + }) + +#define re_atomic_exchange(_a, _v, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val = (_v);\ + if (sizeof(_val) < 8) {\ + __asm__ __volatile__ ("xchg %1, %0"\ + : "+m" (*(_a)), "+q" (_val)\ + : \ + : "memory");\ + }\ + else {\ + __typeof__(*(_a)) _expected = *(_a);\ + while (1) {\ + __typeof__(*(_a)) _prev_val =\ + __sync_val_compare_and_swap(\ + _a, _expected, _val);\ + if (_prev_val == _expected)\ + break;\ + _expected = _prev_val;\ + }\ + _val = _expected;\ + }\ + _val;\ + }) + +#else + +#define re_atomic_store(_a, _v, _mo) \ + (void)re_atomic_exchange(_a, _v, _mo) + +#define re_atomic_load(_a, _mo) \ + __sync_val_compare_and_swap(\ + _a, (__typeof__(*(_a)))0, (__typeof__(*(_a)))0) + +#define re_atomic_exchange(_a, _v, _mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _val = (_v);\ + __typeof__(*(_a)) _expected = *(_a);\ + while (1) {\ + __typeof__(*(_a)) _prev_val =\ + __sync_val_compare_and_swap(\ + _a, _expected, _val);\ + if (_prev_val == _expected)\ + break;\ + _expected = _prev_val;\ + }\ + _expected;\ + }) + +#endif + +#define re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + __extension__\ + ({\ + __typeof__(*(_a)) _exp_val = *(_expected);\ + __typeof__(*(_a)) _prev_val =\ + __sync_val_compare_and_swap(_a, _exp_val,\ + (__typeof__(*(_a)))(_desired));\ + *(_expected) = _prev_val;\ + _prev_val == _exp_val;\ + }) + +#define re_atomic_compare_exchange_weak(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) + +#define re_atomic_fetch_add(_a, _v, _mo) \ + __sync_fetch_and_add(_a, (__typeof__(*(_a)))(_v)) + +#define re_atomic_fetch_sub(_a, _v, _mo) \ + __sync_fetch_and_sub(_a, (__typeof__(*(_a)))(_v)) + +#define re_atomic_fetch_or(_a, _v, _mo) \ + __sync_fetch_and_or(_a, (__typeof__(*(_a)))(_v)) + +#define re_atomic_fetch_xor(_a, _v, _mo) \ + __sync_fetch_and_xor(_a, (__typeof__(*(_a)))(_v)) + +#define re_atomic_fetch_and(_a, _v, _mo) \ + __sync_fetch_and_and(_a, (__typeof__(*(_a)))(_v)) + +/* MSVC Interlocked* intrinsics. This needs to go after clang to let clang-cl + * get handled above. */ +#elif defined(_MSC_VER) + +#include +#include +#include "dh_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define DH_ATOMIC_BOOL_LOCK_FREE 2 +#define DH_ATOMIC_CHAR_LOCK_FREE 2 +#define DH_ATOMIC_WCHAR_T_LOCK_FREE 2 +#define DH_ATOMIC_SHORT_LOCK_FREE 2 +#define DH_ATOMIC_INT_LOCK_FREE 2 +#define DH_ATOMIC_LONG_LOCK_FREE 2 +#define DH_ATOMIC_LLONG_LOCK_FREE 2 +#define DH_ATOMIC_POINTER_LOCK_FREE 2 + +/* These constants don't matter but for consistency they match + * values in std::memory_order from in C++. + * There are specialized intrinsics for ARM and ARM64 + * for different memory ordering types, but they are not used (yet) below. */ +#define re_memory_order_relaxed 0 +#define re_memory_order_acquire 2 +#define re_memory_order_release 3 +#define re_memory_order_acq_rel 4 +#define re_memory_order_seq_cst 5 + +static unsigned __int64 _re_atomic_exchange( + size_t size, void *a, unsigned __int64 v); + +#if defined(_M_IX86) || defined(_M_AMD64) + +static __forceinline void _re_atomic_store( + size_t size, void *a, unsigned __int64 v, unsigned int mo) +{ + assert(size == 1u || size == 2u || size == 4u || size == 8u); + if (mo != re_memory_order_seq_cst) { + _ReadWriteBarrier(); + switch (size) { + case 1u: + *(volatile unsigned __int8*)a = (unsigned __int8)v; + break; + case 2u: + *(volatile unsigned __int16*)a = (unsigned __int16)v; + break; + case 4u: + *(volatile unsigned __int32*)a = (unsigned __int32)v; + break; + default: +#if defined(_M_IX86) + { + __int64 prev_val = + *(const volatile __int64*)(a); + while (1) { + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)v, + prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + } +#else + *(volatile unsigned __int64*)a = v; +#endif + break; + } + _ReadWriteBarrier(); + } + else { + _re_atomic_exchange(size, a, v); + } +} + +static __forceinline unsigned __int64 _re_atomic_load( + size_t size, void *a) +{ + unsigned __int64 v; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + _ReadWriteBarrier(); + switch (size) { + case 1u: + v = *(const volatile unsigned __int8*)a; + break; + case 2u: + v = *(const volatile unsigned __int16*)a; + break; + case 4u: + v = *(const volatile unsigned __int32*)a; + break; + default: +#if defined(_M_IX86) + v = _InterlockedCompareExchange64((__int64*)a, 0, 0); +#else + v = *(const volatile unsigned __int64*)a; +#endif + break; + } + _ReadWriteBarrier(); + + return v; +} + +#elif defined(_M_ARM) || defined(_M_ARM64) + +static __forceinline void _re_atomic_store( + size_t size, void *a, unsigned __int64 v, unsigned int mo) +{ + assert(size == 1u || size == 2u || size == 4u || size == 8u); + _ReadWriteBarrier(); + + if (mo >= re_memory_order_release) + __dmb(0x0b); /* dmb ish */ + + _ReadWriteBarrier(); + + switch (size) { + case 1u: + __iso_volatile_store8((__int8*)a, (__int8)v); + break; + case 2u: + __iso_volatile_store16((__int16*)a, (__int16)v); + break; + case 4u: + __iso_volatile_store32((__int32*)a, (__int32)v); + break; + default: + __iso_volatile_store64((__int64*)a, (__int64)v); + break; + } + + _ReadWriteBarrier(); + + if (mo == re_memory_order_seq_cst) + __dmb(0x0b); /* dmb ish */ + + _ReadWriteBarrier(); +} + +static __forceinline unsigned __int64 _re_atomic_load( + size_t size, void *a) +{ + unsigned __int64 v; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + _ReadWriteBarrier(); + + switch (size) { + case 1u: + v = __iso_volatile_load8((const unsigned __int8*)a); + break; + case 2u: + v = __iso_volatile_load16((const unsigned __int16*)a); + break; + case 4u: + v = __iso_volatile_load32((const unsigned __int32*)a); + break; + default: + v = __iso_volatile_load64(*(const unsigned __int64*)a); + break; + } + + _ReadWriteBarrier(); + + if (mo != re_memory_order_relaxed && mo <= re_memory_order_acquire) + __dmb(0x0b); /* dmb ish */ + + _ReadWriteBarrier(); + + return v; +} + +#else + +static __forceinline void _re_atomic_store( + size_t size, void *a, unsigned __int64 v) +{ + assert(size == 1u || size == 2u || size == 4u || size == 8u); + _ReadWriteBarrier(); + switch (size) { + case 1u: + { + char prev_val = *(const volatile char*)(a); + while (1) { + char prev_val2 = + _InterlockedCompareExchange8( + (char*)a, + (char)v, + prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + } + break; + case 2u: + { + short prev_val = *(const volatile short*)(a); + while (1) { + short prev_val2 = + _InterlockedCompareExchange16( + (short*)a, + (short)v, + prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + } + break; + case 4u: + { + long prev_val = *(const volatile long*)(a); + while (1) { + long prev_val2 = + _InterlockedCompareExchange( + (long*)a, + (long)v, + prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + } + break; + default: + { + __int64 prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)v, + prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + } + break; + } + _ReadWriteBarrier(); +} + +static __forceinline unsigned __int64 _re_atomic_load( + size_t size, void *a) +{ + unsigned __int64 v; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + v = _InterlockedCompareExchange8((char*)a, 0, 0); + break; + case 2u: + v = _InterlockedCompareExchange16((short*)a, 0, 0); + break; + case 4u: + v = _InterlockedCompareExchange((long*)a, 0, 0); + break; + default: + v = _InterlockedCompareExchange64((__int64*)a, 0, 0); + break; + } + + return v; +} + +#endif + +#define re_atomic_store(_a, _v, _mo) \ + _re_atomic_store(sizeof(*(_a)), _a, _v, _mo); + +#define re_atomic_load(_a, _mo) \ + _re_atomic_load(sizeof(*(_a)), _a) + +static __forceinline unsigned __int64 _re_atomic_exchange( + size_t size, void *a, unsigned __int64 v) +{ + unsigned __int64 prev_val; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + prev_val = _InterlockedExchange8((char*)a, (char)v); + break; + case 2u: + prev_val = _InterlockedExchange16((short*)a, (short)v); + break; + case 4u: + prev_val = _InterlockedExchange((long*)a, (long)v); + break; + default: +#if defined(_M_IX86) + { + _ReadWriteBarrier(); + prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)v, + (__int64)prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + _ReadWriteBarrier(); + } +#else + prev_val = _InterlockedExchange64((__int64*)a, (__int64)v); +#endif + break; + } + + return prev_val; +} + +#define re_atomic_exchange(_a, _v, _mo) \ + _re_atomic_exchange(sizeof(*(_a)), _a, _v) + +static __forceinline bool _re_atomic_compare_exchange_strong( + size_t size, void *a, void *expected, unsigned __int64 desired) +{ + bool res; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + { + char expected_val = *(char*)expected; + char prev_val = + _InterlockedCompareExchange8( + (char*)a, + (char)desired, + expected_val); + *(char*)expected = prev_val; + res = prev_val == expected_val; + } + break; + case 2u: + { + short expected_val = *(short*)expected; + short prev_val = + _InterlockedCompareExchange16( + (short*)a, + (short)desired, + expected_val); + *(short*)expected = prev_val; + res = prev_val == expected_val; + } + break; + case 4u: + { + long expected_val = *(long*)expected; + long prev_val = + _InterlockedCompareExchange( + (long*)a, + (long)desired, + expected_val); + *(long*)expected = prev_val; + res = prev_val == expected_val; + } + break; + default: + { + __int64 expected_val = *(__int64*)expected; + __int64 prev_val = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)desired, + expected_val); + *(__int64*)expected = prev_val; + res = prev_val == expected_val; + } + break; + } + + return res; +} + +#define re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + _re_atomic_compare_exchange_strong(\ + sizeof(*(_a)), _a, _expected, _desired) + +#define re_atomic_compare_exchange_weak(\ + _a, _expected, _desired, _success_mo, _fail_mo) \ + re_atomic_compare_exchange_strong(\ + _a, _expected, _desired, _success_mo, _fail_mo) + +static __forceinline unsigned __int64 _re_atomic_fetch_add( + size_t size, void *a, unsigned __int64 v) +{ + unsigned __int64 prev_val; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + prev_val = _InterlockedExchangeAdd8((char*)a, (char)v); + break; + case 2u: + prev_val = _InterlockedExchangeAdd16((short*)a, (short)v); + break; + case 4u: + prev_val = _InterlockedExchangeAdd((long*)a, (long)v); + break; + default: +#if defined(_M_IX86) + { + _ReadWriteBarrier(); + prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 new_val = prev_val + v; + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)new_val, + (__int64)prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + _ReadWriteBarrier(); + } +#else + prev_val = _InterlockedExchangeAdd64((__int64*)a, (__int64)v); +#endif + break; + } + + return prev_val; +} + +#define re_atomic_fetch_add(_a, _v, _mo) \ + _re_atomic_fetch_add(sizeof(*(_a)), _a, _v) + +#define re_atomic_fetch_sub(_a, _v, _mo) \ + re_atomic_fetch_add(_a, -(__int64)(_v), _mo) + +static __forceinline unsigned __int64 _re_atomic_fetch_or( + size_t size, void *a, unsigned __int64 v) +{ + unsigned __int64 prev_val; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + prev_val = _InterlockedOr8((char*)a, (char)v); + break; + case 2u: + prev_val = _InterlockedOr16((short*)a, (short)v); + break; + case 4u: + prev_val = _InterlockedOr((long*)a, (long)v); + break; + default: +#if defined(_M_IX86) + { + _ReadWriteBarrier(); + prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 new_val = prev_val | v; + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)new_val, + (__int64)prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + _ReadWriteBarrier(); + } +#else + prev_val = _InterlockedOr64((__int64*)a, (__int64)v); +#endif + break; + } + + return prev_val; +} + +#define re_atomic_fetch_or(_a, _v, _mo) \ + _re_atomic_fetch_or(sizeof(*(_a)), _a, _v) + +static __forceinline unsigned __int64 _re_atomic_fetch_xor( + size_t size, void *a, unsigned __int64 v) +{ + unsigned __int64 prev_val; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + prev_val = _InterlockedXor8((char*)a, (char)v); + break; + case 2u: + prev_val = _InterlockedXor16((short*)a, (short)v); + break; + case 4u: + prev_val = _InterlockedXor((long*)a, (long)v); + break; + default: +#if defined(_M_IX86) + { + _ReadWriteBarrier(); + prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 new_val = prev_val ^ v; + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)new_val, + (__int64)prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + _ReadWriteBarrier(); + } +#else + prev_val = _InterlockedXor64((__int64*)a, (__int64)v); +#endif + break; + } + + return prev_val; +} + +#define re_atomic_fetch_xor(_a, _v, _mo) \ + _re_atomic_fetch_xor(sizeof(*(_a)), _a, _v) + +static __forceinline unsigned __int64 _re_atomic_fetch_and( + size_t size, void *a, unsigned __int64 v) +{ + unsigned __int64 prev_val; + assert(size == 1u || size == 2u || size == 4u || size == 8u); + switch (size) { + case 1u: + prev_val = _InterlockedAnd8((char*)a, (char)v); + break; + case 2u: + prev_val = _InterlockedAnd16((short*)a, (short)v); + break; + case 4u: + prev_val = _InterlockedAnd((long*)a, (long)v); + break; + default: +#if defined(_M_IX86) + { + _ReadWriteBarrier(); + prev_val = *(const volatile __int64*)(a); + while (1) { + __int64 new_val = prev_val & v; + __int64 prev_val2 = + _InterlockedCompareExchange64( + (__int64*)a, + (__int64)new_val, + (__int64)prev_val); + if (prev_val2 == prev_val) + break; + prev_val = prev_val2; + } + _ReadWriteBarrier(); + } +#else + prev_val = _InterlockedAnd64((__int64*)a, (__int64)v); +#endif + break; + } + + return prev_val; +} + +#define re_atomic_fetch_and(_a, _v, _mo) \ + _re_atomic_fetch_and(sizeof(*(_a)), _a, _v) + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#else +#error "Compiler does not support atomics" +#endif /* HAVE_ATOMIC */ + +#ifndef DH_ATOMIC +#define DH_ATOMIC +#endif + + +/* --- Some short alias helpers --- */ + +/** + * @def re_atomic_rlx(_a) + * + * Load value from an atomic object with relaxed order + * + * @param _a pointer to the atomic object + * + * @return value of the atomic variable + */ +#define re_atomic_rlx(_a) re_atomic_load(_a, re_memory_order_relaxed) + + +/** + * @def re_atomic_rlx_set(_a, _v) + * + * Store value in an atomic object with relaxed order + * + * @param _a pointer to the atomic object + * @param _v new value + */ +#define re_atomic_rlx_set(_a, _v) \ + re_atomic_store(_a, _v, re_memory_order_relaxed) + + +/** + * @def re_atomic_rlx_add(_a, _v) + * + * Replace value from an atomic object with addition and relaxed order + * + * @param _a pointer to the atomic object + * @param _v value to add + * + * @return value held previously by the atomic variable + */ +#define re_atomic_rlx_add(_a, _v) \ + re_atomic_fetch_add(_a, _v, re_memory_order_relaxed) + + +/** + * @def re_atomic_rlx_sub(_a, _v) + * + * Replace value from an atomic object with substraction and relaxed order + * + * @param _a pointer to the atomic object + * @param _v value to subtract + * + * @return value held previously by the atomic variable + */ +#define re_atomic_rlx_sub(_a, _v) \ + re_atomic_fetch_sub(_a, _v, re_memory_order_relaxed) + + +/** + * @def re_atomic_acq(_a) + * + * Load value from an atomic object with acquire order + * + * @param _a pointer to the atomic object + * + * @return value of the atomic variable + */ +#define re_atomic_acq(_a) re_atomic_load(_a, re_memory_order_acquire) + + +/** + * @def re_atomic_rls_set(_a, _v) + * + * Store value in an atomic object with release order + * + * @param _a pointer to the atomic object + * @param _v new value + */ +#define re_atomic_rls_set(_a, _v) \ + re_atomic_store(_a, _v, re_memory_order_release) + + +/** + * @def re_atomic_acq_add(_a, _v) + * + * Replace value from an atomic object with addition and acquire-release order + * + * @param _a pointer to the atomic object + * @param _v value to add + * + * @return value held previously by the atomic variable + */ +#define re_atomic_acq_add(_a, _v) \ + re_atomic_fetch_add(_a, _v, re_memory_order_acq_rel) + + +/** + * @def re_atomic_acq_sub(_a, _v) + * + * Replace value from an atomic object with substraction and acquire-release + * order + * + * @param _a pointer to the atomic object + * @param _v value to subtract + * + * @return value held previously by the atomic variable + */ +#define re_atomic_acq_sub(_a, _v) \ + re_atomic_fetch_sub(_a, _v, re_memory_order_acq_rel) + + +/** + * @def re_atomic_seq(_a) + * + * Load value from an atomic object with sequentially-consistent order + * + * @param _a pointer to the atomic object + * + * @return value of the atomic variable + */ +#define re_atomic_seq(_a) re_atomic_load(_a, re_memory_order_seq_cst) + + +/** + * @def re_atomic_seq_set(_a, _v) + * + * Store value in an atomic object with sequentially-consistent order + * + * @param _a pointer to the atomic object + * @param _v new value + */ +#define re_atomic_seq_set(_a, _v) \ + re_atomic_store(_a, _v, re_memory_order_seq_cst) + + +/** + * @def re_atomic_seq_add(_a, _v) + * + * Replace value from an atomic object with addition and + * sequentially-consistent order + * + * @param _a pointer to the atomic object + * @param _v value to add + * + * @return value held previously by the atomic variable + */ +#define re_atomic_seq_add(_a, _v) \ + re_atomic_fetch_add(_a, _v, re_memory_order_seq_cst) + + +/** + * @def re_atomic_seq_sub(_a, _v) + * + * Replace value from an atomic object with substraction and + * sequentially-consistent order + * + * @param _a pointer to the atomic object + * @param _v value to substract + * + * @return value held previously by the atomic variable + */ +#define re_atomic_seq_sub(_a, _v) \ + re_atomic_fetch_sub(_a, _v, re_memory_order_seq_cst) + +#ifdef __cplusplus +} +#endif + +#endif /* DH_H_ATOMIC__ */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..655af9d0ff288ddfc6a41dea0b8189c75d750b84 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.c @@ -0,0 +1,339 @@ +#include +#include +#include +#include + +#include "dh_mem.h" +#include "dh_atomic.h" + + +/** Defines a reference-counting memory object */ +struct mem { + DH_ATOMIC uint32_t nrefs; /**< Number of references */ + uint32_t size; /**< Size of memory object */ + mem_destroy_h *dh; /**< Destroy handler */ +}; + + +#define STAT_ALLOC(_m, _size) (_m)->size = (uint32_t)(_size); +#define STAT_REALLOC(_m, _size) (_m)->size = (uint32_t)(_size); +#define STAT_DEREF(_m) +#define MAGIC_CHECK(_m) + + +enum { +#if defined(__x86_64__) + /* Use 16-byte alignment on x86-x32 as well */ + mem_alignment = 16u, +#else + mem_alignment = sizeof(void*) >= 8u ? 16u : 8u, +#endif + alignment_mask = mem_alignment - 1u, + mem_header_size = (sizeof(struct mem) + alignment_mask) & + (~(size_t)alignment_mask) +}; + +#define MEM_SIZE_MAX \ + (size_t)(sizeof(size_t) > sizeof(uint32_t) ? \ + (~(uint32_t)0u) : (~(size_t)0u) - mem_header_size) + + +static inline struct mem *get_mem(void *p) +{ + return (struct mem *)(void *)(((unsigned char *)p) - mem_header_size); +} + + +static inline void *get_mem_data(struct mem *m) +{ + return (void *)(((unsigned char *)m) + mem_header_size); +} + + +/** + * Allocate a new reference-counted memory object + * + * @param size Size of memory object + * @param dh Optional destructor, called when destroyed + * + * @return Pointer to allocated object + */ +void *mem_alloc(size_t size, mem_destroy_h *dh) +{ + struct mem *m; + + if (size > MEM_SIZE_MAX) + return NULL; + + + m = (struct mem*)malloc(mem_header_size + size); + if (!m) return NULL; + + re_atomic_rlx_set(&m->nrefs, 1u); + m->dh = dh; + + STAT_ALLOC(m, size); + + return get_mem_data(m); +} + + +/** + * Allocate a new reference-counted memory object. Memory is zeroed. + * + * @param size Size of memory object + * @param dh Optional destructor, called when destroyed + * + * @return Pointer to allocated object + */ +void *mem_zalloc(size_t size, mem_destroy_h *dh) +{ + void *p; + + p = mem_alloc(size, dh); + if (!p) + return NULL; + + memset(p, 0, size); + + return p; +} + + +/** + * Re-allocate a reference-counted memory object + * + * @param data Memory object + * @param size New size of memory object + * + * @return New pointer to allocated object + * + * @note Realloc NULL pointer is not supported + */ +void *mem_realloc(void *data, size_t size) +{ + struct mem *m, *m2; + + if (!data) + return NULL; + + if (size > MEM_SIZE_MAX) + return NULL; + + m = get_mem(data); + + MAGIC_CHECK(m); + + if (re_atomic_acq(&m->nrefs) > 1u) { + void* p = mem_alloc(size, m->dh); + if (p) { + memcpy(p, data, m->size); + mem_deref(data); + } + return p; + } + + + m2 = (struct mem*)realloc(m, mem_header_size + size); + + + if (!m2) { + return NULL; + } + + STAT_REALLOC(m2, size); + + return get_mem_data(m2); +} + + +/** + * Re-allocate a reference-counted array + * + * @param ptr Pointer to existing array, NULL to allocate a new array + * @param nmemb Number of members in array + * @param membsize Number of bytes in each member + * @param dh Optional destructor, only used when ptr is NULL + * + * @return New pointer to allocated array + */ +void *mem_reallocarray(void *ptr, size_t nmemb, size_t membsize, + mem_destroy_h *dh) +{ + size_t tsize; + + if (membsize && nmemb > MEM_SIZE_MAX / membsize) { + return NULL; + } + + tsize = nmemb * membsize; + + if (ptr) { + return mem_realloc(ptr, tsize); + } + else { + return mem_alloc(tsize, dh); + } +} + + +/** + * Set or unset a destructor for a memory object + * + * @param data Memory object + * @param dh called when destroyed, NULL for remove + */ +void mem_destructor(void *data, mem_destroy_h *dh) +{ + struct mem *m; + + if (!data) + return; + + m = get_mem(data); + + MAGIC_CHECK(m); + + m->dh = dh; +} + + +/** + * Reference a reference-counted memory object + * + * @param data Memory object + * + * @return Memory object (same as data) + */ +void *mem_ref(void *data) +{ + struct mem *m; + + if (!data) + return NULL; + + m = get_mem(data); + + MAGIC_CHECK(m); + + re_atomic_rlx_add(&m->nrefs, 1u); + + return data; +} + + +/** + * Dereference a reference-counted memory object. When the reference count + * is zero, the destroy handler will be called (if present) and the memory + * will be freed + * + * @param data Memory object + * + * @return Always NULL + */ +/* coverity[-tainted_data_sink: arg-0] */ +void *mem_deref(void *data) +{ + struct mem *m; + + if (!data) + return NULL; + + m = get_mem(data); + + MAGIC_CHECK(m); + + if (re_atomic_acq_sub(&m->nrefs, 1u) > 1u) { + return NULL; + } + + if (m->dh) + m->dh(data); + + /* NOTE: check if the destructor called mem_ref() */ + if (re_atomic_rlx(&m->nrefs) > 0u) + return NULL; + + + STAT_DEREF(m); + + free(m); + + return NULL; +} + + +/** + * Get number of references to a reference-counted memory object + * + * @param data Memory object + * + * @return Number of references + */ +uint32_t mem_nrefs(const void *data) +{ + struct mem *m; + + if (!data) + return 0; + + m = get_mem((void*)data); + + MAGIC_CHECK(m); + + return (uint32_t)re_atomic_acq(&m->nrefs); +} + + + + +/** + * Debug all allocated memory objects + */ +void mem_debug(void) +{ +} + + +/** + * Set the memory allocation threshold. This is only used for debugging + * and out-of-memory simulation + * + * @param n Threshold value + */ +void mem_threshold_set(ssize_t n) +{ + (void)n; +} + + +/** + * Print memory status + * + * @param pf Print handler for debug output + * @param unused Unused parameter + * + * @return 0 if success, otherwise errorcode + */ +int mem_status(struct re_printf *pf, void *unused) +{ + (void)pf; + (void)unused; + return 0; +} + + +/** + * Get memory statistics + * + * @param mstat Returned memory statistics + * + * @return 0 if success, otherwise errorcode +int mem_get_stat(struct memstat *mstat) +{ + if (!mstat) + return EINVAL; + return ENOSYS; +} + */ + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.h new file mode 100644 index 0000000000000000000000000000000000000000..4e6d9c758831e2093190f54d046c90c8d74d1644 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_mem.h @@ -0,0 +1,36 @@ +#ifndef DH_H_MEM_ +#define DH_H_MEM_ + +#include "dh_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + typedef void (mem_destroy_h)(void *data); + + void *mem_alloc(size_t size, mem_destroy_h *dh); + void *mem_zalloc(size_t size, mem_destroy_h *dh); + void *mem_realloc(void *data, size_t size); + void *mem_reallocarray(void *ptr, size_t nmemb, + size_t membsize, mem_destroy_h *dh); + void mem_destructor(void *data, mem_destroy_h *dh); + void *mem_ref(void *data); + void *mem_deref(void *data); + uint32_t mem_nrefs(const void *data); + + void mem_debug(void); + void mem_threshold_set(ssize_t n); + struct re_printf; + int mem_status(struct re_printf *pf, void *unused); + //int mem_get_stat(struct memstat *mstat); + + + /* Secure memory functions */ + int mem_seccmp(const uint8_t *s1, const uint8_t *s2, size_t n); + void mem_secclean(void *data, size_t size); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_types.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_types.h new file mode 100644 index 0000000000000000000000000000000000000000..8ab810c7c8ff4ee0e54c75ea97ecba62f2bc821d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/dh_types.h @@ -0,0 +1,267 @@ +#ifndef DH_H_TYPES +#define DH_H_TYPES + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#ifdef __cplusplus +#define restrict +#endif + +#ifdef _MSC_VER +#include + +#include +typedef SSIZE_T ssize_t; + +#endif + +/* + * Basic integral types and boolean from C99 + */ +#include +#include + + +/* Needed for MS compiler */ +#ifdef _MSC_VER +#ifndef __cplusplus +#define inline _inline +#endif +#endif + + +/* + * Misc macros + */ + +/** Defines the NULL pointer */ +#ifndef NULL +#define NULL ((void *)0) +#endif + +/** Get number of elements in an array */ +#undef ARRAY_SIZE +#define ARRAY_SIZE(a) ((sizeof(a))/(sizeof((a)[0]))) + +/** Align a value to the boundary of mask */ +#define ALIGN_MASK(x, mask) (((x)+(mask))&~(mask)) + +/** Check alignment of pointer (p) and byte count (c) **/ +#define is_aligned(p, c) (((uintptr_t)(const void *)(p)) % (c) == 0) + +/** Get the minimal value */ +#undef MIN +#define MIN(a,b) (((a)<(b)) ? (a) : (b)) + +/** Get the maximal value */ +#undef MAX +#define MAX(a,b) (((a)>(b)) ? (a) : (b)) + +#ifndef __cplusplus + +/** Get the minimal value */ +#undef min +#define min(x,y) MIN(x, y) + +/** Get the maximal value */ +#undef max +#define max(x,y) MAX(x, y) + +#endif + +/** Defines a soft breakpoint */ +#if (defined(__i386__) || defined(__x86_64__)) +#define BREAKPOINT __asm__("int $0x03") +#else +#define BREAKPOINT +#endif + +/* Error return/goto debug helpers */ +#ifdef TRACE_ERR +#define PRINT_TRACE_ERR(err) \ + (void)re_fprintf(stderr, "TRACE_ERR: %s:%u: %s():" \ + " %m (%d)\n", \ + __FILE__, __LINE__, __func__, \ + (err), (err)); +#else +#define PRINT_TRACE_ERR(err) +#endif + +#define IF_ERR_GOTO_OUT(err) \ + if ((err)) { \ + PRINT_TRACE_ERR((err)) \ + goto out; \ + } + +#define IF_ERR_GOTO_OUT1(err) \ + if ((err)) { \ + PRINT_TRACE_ERR((err)) \ + goto out1; \ + } + +#define IF_ERR_GOTO_OUT2(err) \ + if ((err)) { \ + PRINT_TRACE_ERR((err)) \ + goto out2; \ + } + +#define IF_ERR_RETURN(err) \ + if ((err)) { \ + PRINT_TRACE_ERR((err)) \ + return (err); \ + } + +#define IF_RETURN_EINVAL(exp) \ + if ((exp)) { \ + PRINT_TRACE_ERR(EINVAL) \ + return (EINVAL); \ + } + +#define RETURN_ERR(err) \ + if ((err)) { \ + PRINT_TRACE_ERR((err)) \ + } \ + return (err); + + +/* Error codes */ +#include + +/* Duplication of error codes. Values are from linux asm-generic/errno.h */ + +/** No data available */ +#ifndef ENODATA +#define ENODATA 200 +#endif + +/** Protocol error */ +#ifndef EPROTO +#define EPROTO 201 +#endif + +/** Not a data message */ +#ifndef EBADMSG +#define EBADMSG 202 +#endif + +/** Value too large for defined data type */ +#ifndef EOVERFLOW +#define EOVERFLOW 203 +#endif + +/** Accessing a corrupted shared library */ +#ifndef ELIBBAD +#define ELIBBAD 204 +#endif + +/** Destination address required */ +#ifndef EDESTADDRREQ +#define EDESTADDRREQ 205 +#endif + +/** Protocol not supported */ +#ifndef EPROTONOSUPPORT +#define EPROTONOSUPPORT 206 +#endif + +/** Operation not supported */ +#ifndef ENOTSUP +#define ENOTSUP 207 +#endif + +/** Address family not supported by protocol */ +#ifndef EAFNOSUPPORT +#define EAFNOSUPPORT 208 +#endif + +/** Cannot assign requested address */ +#ifndef EADDRNOTAVAIL +#define EADDRNOTAVAIL 209 +#endif + +/** Software caused connection abort */ +#ifndef ECONNABORTED +#define ECONNABORTED 210 +#endif + +/** Connection reset by peer */ +#ifndef ECONNRESET +#define ECONNRESET 211 +#endif + +/** Transport endpoint is not connected */ +#ifndef ENOTCONN +#define ENOTCONN 212 +#endif + +/** Connection timed out */ +#ifndef ETIMEDOUT +#define ETIMEDOUT 213 +#endif + +/** Connection refused */ +#ifndef ECONNREFUSED +#define ECONNREFUSED 214 +#endif + +/** Operation already in progress */ +#ifndef EALREADY +#define EALREADY 215 +#endif + +/** Operation now in progress */ +#ifndef EINPROGRESS +#define EINPROGRESS 216 +#endif + +/** Authentication error */ +#ifndef EAUTH +#define EAUTH 217 +#endif + +/** No STREAM resources */ +#ifndef ENOSR +#define ENOSR 218 +#endif + +/** Key was rejected by service */ +#ifndef EKEYREJECTED +#define EKEYREJECTED 129 +#endif + +/* + * Any C compiler conforming to C99 or later MUST support __func__ + */ +#if __STDC_VERSION__ >= 199901L +#define __REFUNC__ (const char *)__func__ +#else +#define __REFUNC__ __FUNCTION__ +#endif + +/* + * Give the compiler a hint which branch is "likely" or "unlikely" (inspired + * by linux kernel and C++20/C2X) + */ +#ifdef __GNUC__ +#define likely(x) __builtin_expect(!!(x), 1) +#define unlikely(x) __builtin_expect(!!(x), 0) +#else +#define likely(x) x +#define unlikely(x) x +#endif + +#ifdef WIN32 +#define re_restrict __restrict +#else +#define re_restrict restrict +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/grefmem.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/grefmem.h new file mode 100644 index 0000000000000000000000000000000000000000..d04e6a7b317809d146dceb0bc0b4a972af343aa6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/base/grefmem.h @@ -0,0 +1,64 @@ +#ifndef GUIJI_REFCOUNT_H +#define GUIJI_REFCOUNT_H + +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include "dh_mem.h" +#endif +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(_WIN32) + +#define BILLION (1E9) +static BOOL g_first_time = 1; +static LARGE_INTEGER g_counts_per_sec; + +static inline uint64_t timer_msstamp() { + struct timespec ts; + struct timespec *ct = &ts; + LARGE_INTEGER count; + if (g_first_time) { + g_first_time = 0; + if (0 == QueryPerformanceFrequency(&g_counts_per_sec)) { + g_counts_per_sec.QuadPart = 0; + } + } + if ((NULL == ct) || (g_counts_per_sec.QuadPart <= 0) || (0 == QueryPerformanceCounter(&count))) { + return -1; + } + ct->tv_sec = count.QuadPart / g_counts_per_sec.QuadPart; + ct->tv_nsec = ((count.QuadPart % g_counts_per_sec.QuadPart) * BILLION) / g_counts_per_sec.QuadPart; + return (ts.tv_sec*1000l) + (ts.tv_nsec/CLOCKS_PER_SEC); +} +#else +static inline uint64_t timer_msstamp() { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (ts.tv_sec*1000l) + (ts.tv_nsec/CLOCKS_PER_SEC); +} +#endif + +#define gjrefobj_alloc(memrefp, memsize , free_fn) { \ + *((char**)&memrefp) = (char*)mem_alloc(memsize,free_fn);\ +} + +#define gjrefobj_ref(memrefp) { \ + mem_ref(memrefp);\ +} + +#define gjrefobj_unref(memrefp) { \ + mem_deref(memrefp);\ +} + +#ifdef __cplusplus +} +#endif +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/cuda/kmatcuda.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/cuda/kmatcuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d04fb469128ffbcc370596260ff9e18f3b44d41 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/cuda/kmatcuda.cpp @@ -0,0 +1,194 @@ +#include "ghmat.h" +#ifdef _TENSORRT_ +#include +#include +#include +#include "ppl/cv/cuda/resize.h" +#include "ppl/cv/cuda/convertto.h" +#include "ppl/cv/cuda/split.h" +#include "ppl/cv/cuda/merge.h" +#include "ppl/cv/cuda/convertto.h" +#include "cudautil.h" + +int GhMat::vtacc(GpMat mat,void* stream ){ + if(m_dev!=mat->m_dev)return -1; + cavtacc((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, mat->m_stride, (float*)mat->m_buf); +} + +int GhMat::resize(GpMat mat,void* stream){ + if(m_dev!=mat->m_dev)return -1; + ppl::cv::cuda::Resize((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, mat->m_height, mat->m_width, mat->m_stride, (float*)mat->m_buf); + return 0; +} + +int GhMat::img2hwc(GpMat mat,void* stream){ + if(m_dev!=mat->m_dev)return -1; + if(m_channel!=3)return -2; + float* gpu_split = (float*)mat->m_buf; + float* gpu_s0 = gpu_split ; + int line = mat->m_stride*mat->m_height; + float* gpu_s1 = gpu_split + line; + float* gpu_s2 = gpu_split + line*2; + ppl::cv::cuda::Split3Channels((cudaStream_t)stream,m_height, m_width,m_stride, (float*)m_buf, mat->m_width,gpu_s2,gpu_s1,gpu_s0); + return 0; +} + +int GhMat::hwc2img(GpMat mat,void* stream){ + if(m_dev!=mat->m_dev)return -1; + if(m_channel!=3)return -2; + return 0; +} + +int GhMat::downzero(GpMat mat,void* stream){ + if(m_dev!=mat->m_dev)return -1; + if((m_height!=mat->m_height)||(m_width!=mat->m_width))return -2; + ppl::cv::cuda::ConvertTo((cudaStream_t)stream,m_height,m_width,m_stride,(const float*)m_buf, mat->m_stride,(float*)mat->m_buf, 2.0f,-1.0f); + return 0; +} + +int GhMat::upzero(GpMat mat ,void* stream){ + if(m_dev!=mat->m_dev)return -1; + if((m_height!=mat->m_height)||(m_width!=mat->m_width))return -2; + ppl::cv::cuda::ConvertTo((cudaStream_t)stream,m_height,m_width,m_stride,(const float*)m_buf, mat->m_stride,(float*)mat->m_buf, 0.5f,0.5f); + return 0; +} + + +int GhMat::filtermask(GpMat msk, GpMat mat,void* stream) { + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + return cafiltermsk((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, msk->m_stride,(float*)msk->m_buf, mat->m_stride, (float*)mat->m_buf); +} + +int GhMat::clamp(float minval,float maxval,GpMat mat,void* stream ){ + if(!mat)return -1; + return caclamp((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, mat->m_stride, (float*)mat->m_buf,minval,maxval); +} + +int GhMat::blend(GpMat msk,GpMat bgmat,GpMat dstmat,void* stream ){ + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + return cablendmsk((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, msk->m_stride,(float*)msk->m_buf, bgmat->m_stride,(float*)bgmat->m_buf,dstmat->m_stride, (float*)dstmat->m_buf); +} + +int GhMat::wherezero(GpMat msk, GpMat bgmat, GpMat dstmat,void* stream) { + if(!msk)return -1; + if((msk->width()!=m_width) ||(msk->height()!=m_height))return -2; + return cablendzero((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, msk->m_stride,(float*)msk->m_buf, bgmat->m_stride,(float*)bgmat->m_buf,dstmat->m_stride, (float*)dstmat->m_buf); +} + +int GhMat::cvtfloat(GpMat dst,void* stream) { + ppl::cv::cuda::ConvertTo((cudaStream_t)stream,m_height,m_width,m_width*m_channel,(uint8_t*)m_buf, dst->m_stride,(float*)dst->m_buf, 1.0/255.0f,0.f); + return 0; +} + +int GhMat::cvtuint8(GpMat dst,void* stream) { + ppl::cv::cuda::ConvertTo((cudaStream_t)stream,m_height,m_width,m_stride,(float*)m_buf, dst->m_stride,(uint8_t*)dst->m_buf, 255.0f,0.f); + return 0; +} + +static void *cudaalloc(size_t sz){ + void* pmem = NULL; + cudaMalloc(&pmem,sz); + return pmem; +} + +static void cudafree(void* ptr) { + if(ptr)cudaFree(ptr); +} + +static void *cudaset(void* s,int ch,size_t n){ + cudaMemset(s,ch,n); + return s; +} + +static void *cudacpy(void* dst,const void* src,size_t n){ + cudaMemcpy(dst,src,n,cudaMemcpyDeviceToDevice); + return dst; +} + +static int cudaext(void* dst,const void* src,size_t n,int h2d,void* sync){ + if(sync){ + if(h2d){ + printf("====host to dev async\n"); + cudaMemcpyAsync(dst,src,n,cudaMemcpyHostToDevice,(cudaStream_t)sync); + }else{ + cudaMemcpyAsync(dst,src,n,cudaMemcpyDeviceToHost,(cudaStream_t)sync); + } + }else{ + if(h2d){ + cudaMemcpy(dst,src,n,cudaMemcpyHostToDevice); + }else{ + printf("====dev to host\n"); + cudaMemcpy(dst,src,n,cudaMemcpyDeviceToHost); + } + } + return 0; +} + +void GhMat::initgh(){ + m_dev = 1; + dhalloc = cudaalloc; + dhfree = cudafree; + dhset = cudaset; + dhcpy = cudacpy; + dhext = cudaext; +} + + +GhMat::GhMat(DpMat mat):DhMat(){ + initgh(); + m_width = mat->width(); + m_height = mat->height(); + m_stride = mat->stride(); + m_channel = mat->channel();; + m_cnt = mat->count(); + m_size = mat->size(); + if(mat->dev() != m_dev){ + m_ref = 0; + m_buf = (float*)dhalloc(m_size+m_stride*sizeof(float)); + m_devhost = mat; + }else{ + m_buf = mat->buffer(); + m_ref = 1; + } +} + +GhMat::GhMat(GpMat mat):DhMat(){ + initgh(); + m_width = mat->width(); + m_height = mat->height(); + m_stride = mat->stride(); + m_channel = mat->channel();; + m_cnt = mat->count(); + m_size = mat->size(); + if(mat->dev() != m_dev){ + m_ref = 0; + m_buf = (float*)dhalloc(m_size+m_stride*sizeof(float)); + m_devhost = mat; + }else{ + m_buf = mat->buffer(); + m_ref = 1; + } +} + +GhMat::GhMat(int w,int h,float *buf ,int c ,int d ):DhMat(w,h,buf,c,d){ + initgh(); +} + +GhMat::GhMat(int w,int h,int c ,int d):DhMat(){ + initgh(); + m_width = w; + m_height = h; + m_stride = d?d:w*c; + m_channel = c; + m_cnt = m_stride*m_height; + m_size = m_cnt*sizeof(float); + m_ref = 0; + m_buf = (float*)dhalloc(m_size+d*sizeof(float)); +} + +GhMat::~GhMat(){ + if(!m_ref&&m_buf)dhfree(m_buf); +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54a607db0aa55ef813cdda3ba805847ffae1cf31 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.cpp @@ -0,0 +1,842 @@ +#include "GDigit.h" +#include "MediaData.h" +#include "LoopThreadHelper.h" +#include +#include +#include +#include "grtcfg.h" +#include "benchmark.h" + +#ifdef __ANDROID__ +#include "coffeecatch.h" +#endif + + +#define TAG "tooken" + +int LoopWenet::calcinx(KWav* wavmat,int index){ + float* pwav = NULL; + float* pmfcc = NULL; + float* pbnf = NULL; + int melcnt = 0; + int bnfcnt = 0; + int rst = wavmat->calcbuf(index, &pwav,&pmfcc,&pbnf,&melcnt,&bnfcnt); + LOGE(TAG,"===tooken calcinx %d index %d \n",index,rst); + if(rst == index){ + m_wenet->calcmfcc(pwav,pmfcc); + //double t0 = ncnn::get_current_time(); + m_wenet->calcbnf(pmfcc,melcnt,pbnf,bnfcnt); + //double t1 = ncnn::get_current_time(); + //float dist = t1-t0; + //dumpfloat(pbnf,10); + wavmat->finishone(index); + } + return 0; +} + +int LoopWenet::calcall(KWav* wavmat){ + int rst =wavmat->readyall(); + int cnt = 0; + while(cnt<1000){ + rst = wavmat->isready(); + if(!rst)break; + calcinx(wavmat,rst); + } + return 0; +} + +void LoopWenet::handle(int what, void *obj){ + LOGD(TAG,"===tooken loopwenet %d\n",what); +#ifdef __ANDROID__ +COFFEE_TRY() { +#else +try{ +#endif + if(what==9999){ + if(m_wenet){ + KWav* matwav = (KWav*)obj; + calcall(matwav); + } + }else if(what>=0){ + if(m_wenet){ + KWav* matwav = (KWav*)obj; + calcinx(matwav,what); + } + }else if(what==-1){ + Wenet* wenet = (Wenet*)obj; + m_wenet = wenet; + }else if(what==-2){ + m_wenet = nullptr; + Wenet* wenet = (Wenet*)obj; + delete wenet; + }else if(what==-11){ + KWav* matwav = (KWav*)obj; + delete matwav; + } +#ifdef __ANDROID__ +}COFFEE_CATCH() { + LOGE(TAG,"loopcurl err %d",what); +} COFFEE_END(); +#else +}catch(...){ + LOGE(TAG,"loopwenet err %d",what); +} +#endif +} + +LoopWenet::LoopWenet():looper(){ + // +} + +LoopWenet::~LoopWenet(){ + m_wenet = nullptr; +} + +void LoopCurl::handle(int what, void *obj){ +#ifdef __ANDROID__ +COFFEE_TRY() { +#else +try{ +#endif + if(what==1){ + LOGD(TAG,"===docurl \n"); + NetCurl* curl = (NetCurl*)obj; + int rst = curl->docurl(); + LOGD(TAG, " docurl %d ",rst); + }else if(what==-1){ + NetCurl* curl = (NetCurl*)obj; + delete curl; + } +#ifdef __ANDROID__ +}COFFEE_CATCH() { + LOGE(TAG,"loopcurl err %d",what); +} COFFEE_END(); +#else +}catch(...){ + LOGE(TAG,"loopcurl err %d",what); +} +#endif +} + +LoopCurl::LoopCurl():looper(){ +} + +LoopCurl::~LoopCurl(){ +} + +void GDigit::asyncWenet(int act,Wenet* wenet){ + if(act){ + wenetThread->post(-2,wenet); + }else{ + wenetThread->post(-1,wenet); + } +} + +void GDigit::asyncNetwav(int act,KWav* netwav){ + if(act){ + wenetThread->post(-11,netwav); + } +} + +void GDigit::asyncCurl(int act,NetCurl* curl){ + if(act){ + curlThread->post(-1,curl); + }else{ + curlThread->post(1,curl); + } +} + +GDigit::GDigit(int width,int height, MessageCb *obj):GRender(width,height,obj) { + dispThread = new DispatchQueue("Digit"); + curlThread = new LoopCurl(); + wenetThread = new LoopWenet(); + bnf_cache = new MBnfCache(); + lock_munet = new std::mutex(); +} + +GDigit::~GDigit() { + if(m_status)stop(); + recyle(); + usleep(1000); + if(1){ + curlThread->quit(); + delete curlThread; + curlThread = nullptr; + } + if(1){ + wenetThread->quit(); + delete wenetThread; + wenetThread = nullptr; + } + if(1){ + dispThread->removePending(); + delete dispThread; + dispThread = nullptr; + } + if(1){ + if(bnf_cache ){ + delete bnf_cache ; + bnf_cache = nullptr; + } + } + if(1){ + lock_munet->lock(); + lock_munet->unlock(); + delete lock_munet; + } +} + +int GDigit::config(const char* cfgtxt){ + rtcfg_t* cfg = make_rtcfgjson((char*)cfgtxt); + if(!cfg)return -1; + LOGE(TAG,"cfg %p",cfg); + if(cfg->videowidth && cfg->videoheight){ + m_width = cfg->videowidth; + m_height = cfg->videoheight; + LOGD(TAG,"w %d h %d",m_width,m_height); + } + LOGE(TAG,"aaa %s",cfg->cacertfn); + if(cfg->timeoutms&&cfg->cacertfn){ + initCurl(cfg->cacertfn,cfg->timeoutms); + } + LOGE(TAG,"bbb %s",cfg->wenetfn); + if(cfg->wenetfn){ + initWenet(cfg->wenetfn); + } + LOGE(TAG,"ccc %s",cfg->unetmsk); + if(cfg->unetbin&&cfg->unetparam&&cfg->unetmsk){ + initMunet(cfg->unetparam,cfg->unetbin,cfg->unetmsk); + } + if(cfg->alphabin&&cfg->alphaparam){ + initMalpha(cfg->alphaparam,cfg->alphabin); + } + LOGE(TAG,"ddd"); + if(cfg->scrfdbin&&cfg->scrfdparam){ + initScrfd(cfg->scrfdparam,cfg->scrfdbin); + } + if(cfg->pfpldbin&&cfg->pfpldparam){ + initPfpld(cfg->pfpldparam,cfg->pfpldbin); + } + final_rtcfg(cfg); + LOGE(TAG,"eee"); + return 0; +} + +int GDigit::initScrfd(char* fnparam,char* fnbin){ + return 0; +} +int GDigit::initPfpld(char* fnparam,char* fnbin){ + return 0; +} + +int GDigit::initWenet(char* fnwenet){ + if(ai_wenet){ + asyncWenet(1,ai_wenet); + ai_wenet = nullptr; + } + ai_wenet = new Wenet(fnwenet); + asyncWenet(0,ai_wenet); + return 0; +} + +int GDigit::initMunet(char* fnparam,char* fnbin,char* fnmsk){ + Mobunet* munet = ai_munet; + lock_munet->lock(); + ai_munet = new Mobunet(fnbin,fnparam,fnmsk); + lock_munet->unlock(); +dispThread->dispatch([munet,this]() { + if(munet){ + delete munet; + } +}); + LOGE(TAG,"init munet"); + return 0; +} + +int GDigit::initMalpha(char* fnparam,char* fnbin){ + if(1)return 0; + MAlpha* malpha = ai_malpha; +dispThread->dispatch([malpha,this]() { + if(malpha){ + delete malpha; + } +}); + ai_malpha = new MAlpha(fnbin,fnparam); + LOGE(TAG,"init alpha"); + return 0; +} + +int GDigit::initCurl(char* cacertfn,int timeoutms){ + guiji_curl_init(cacertfn); + m_timeoutms = timeoutms; + return 0; +} + +int GDigit::netwav(const char* url,float duration){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(duration>1000.0f)return -990; + if(duration<1.0f)return -991; + int len = strlen(url); + if(len<10)return -101; + char* fn = (char*)(url+0); + if((fn[0]!='h')||(fn[1]!='t')||(fn[2]!='t'))return -102; + fn =(char*)(url+len-3); + if((fn[0]!='w')||(fn[1]!='a')||(fn[2]!='v'))return -103; + if(net_curl){ + net_curl->cancel(); + asyncCurl(1,net_curl); + net_curl = nullptr; + } + if(net_wavmat){ + KWav* wm = net_wavmat; + asyncNetwav(1,wm); + //net_wavmat = nullptr; + } + net_wavmat = new KWav(duration,bnf_cache); + net_curl = new NetCurl((char*)url,duration,net_wavmat,wenetThread,m_timeoutms); + asyncCurl(0,net_curl); + // + int finished = 0; + for(int k=0;k<100;k++){ + if(net_curl->status()){ + finished = 1; + break; + } + if(net_wavmat->resultcnt())break; + usleep(100000); + } + int rst = 0; + if(!finished){ + rst = net_wavmat->bnfblocks();//net_curl->checked(); + cnt_wenet = rst; + inx_wenet = 0; + } + return rst; +} + +int GDigit::bgpic(const char* bgfn){ + if(!m_status)return -1000; + std::string picbg(bgfn); + lock_munet->lock(); + if(!mat_bg)mat_bg = new JMat();//picbg,1); + mat_bg->load(picbg); + lock_munet->unlock(); + /* + JMat* bg = mat_bg; +dispThread->dispatch([picbg,bg,this]() { + delete bg; +}); + mat_bg = new JMat(picbg,1); + */ + return 0; +} + +int GDigit::drawmskbuf(const char* picfn,const char* mskfn,char* dstbuf,char* mskbuf,int size){ + //if(!m_status)return -1000; + std::string picfile(picfn); + std::string mskfile(mskfn); + + JMat* mat_pic = NULL;//new JMat(picfile,1); + JMat* mat_msk = NULL;//new JMat(mskfile,1); + frameSource->popVidRecyle(&mat_pic); + frameSource->popVidRecyle(&mat_msk); + if(!mat_pic)mat_pic = new JMat(); + if(!mat_msk)mat_msk = new JMat(); + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + if(rst)break; + rst = mat_msk->load(mskfile); + break; + } + if(rst){ + delete mat_pic; + delete mat_msk; + return rst*1000; + } + memcpy(dstbuf,mat_pic->data(),size); + memcpy(mskbuf,mat_msk->data(),size); + frameSource->pushVidRecyle(mat_pic); + frameSource->pushVidRecyle(mat_msk); + return 0;//}); +} + +int GDigit::drawonebuf(const char* picfn,char* dstbuf,int size){ + //if(!m_status)return -1000; + std::string picfile(picfn); + + JMat* mat_pic = NULL;//new JMat(picfile,1); + frameSource->popVidRecyle(&mat_pic); + if(!mat_pic)mat_pic = new JMat(); + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + if(rst)break; + break; + } + if(rst){ + delete mat_pic; + return rst*1000; + } + memcpy(dstbuf,mat_pic->data(),size); + frameSource->pushVidRecyle(mat_pic); + return 0;//}); +} + + +int GDigit::drawmskpic(const char* picfn,const char* mskfn){ + if(!m_status)return -1000; + if(!mat_bg)return -1; + std::string picfile(picfn); + std::string mskfile(mskfn); + + JMat* mat_pic = NULL;//new JMat(picfile,1); + JMat* mat_msk = NULL;//new JMat(mskfile,1); + frameSource->popVidRecyle(&mat_pic); + frameSource->popVidRecyle(&mat_msk); + if(!mat_pic)mat_pic = new JMat(); + if(!mat_msk)mat_msk = new JMat(); + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + if(rst)break; + rst = mat_msk->load(mskfile); + break; + } + if(rst){ + delete mat_pic; + delete mat_msk; + return rst*1000; + } + +//dispThread->dispatch([mat_pic,mat_msk,this]() { + if(!mat_bg)return -11; + JMat* bgm = mat_bg->refclone(); + MediaData md(mat_pic,mat_msk,bgm); + frameSource->pushVidFrame(&md); +//}); + return 0; +} + +int GDigit::mskrstbuf(int index,const char* picfn,int* box,const char* mskfn,const char* fgfn,char* dstbuf,char* mskbuf,int size){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(!ai_munet)return -998; + //if(!mat_bg)return -3; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>=cnt_wenet)return -3; + std::string picfile(picfn); + std::string mskfile(mskfn); + std::string fgfile(strlen(fgfn)?fgfn:""); + + JMat* mat_fg = NULL;//new JMat(fgfile,1); + JMat* mat_pic = NULL;//new JMat(picfile,1); + JMat* mat_msk = NULL;//new JMat(mskfile,1); + int hasfg = fgfile.length(); + frameSource->popVidRecyle(&mat_pic); + frameSource->popVidRecyle(&mat_msk); + if(!mat_pic)mat_pic = new JMat(); + if(!mat_msk)mat_msk = new JMat(); + if(hasfg){ + frameSource->popVidRecyle(&mat_fg); + if(!mat_fg)mat_fg = new JMat(); + } + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + if(rst)break; + rst = mat_msk->load(mskfile); + if(rst)break; + if(hasfg) rst = mat_fg->load(fgfile); + break; + } + if(rst){ + if(mat_pic) delete mat_pic; + if(mat_msk) delete mat_msk; + if(mat_fg) delete mat_fg; + return rst*10000; + } + if(sizesize()){ + if(mat_pic) delete mat_pic; + if(mat_msk) delete mat_msk; + if(mat_fg) delete mat_fg; + return -10000; + } + int arr[4]={box[0],box[1],box[2],box[3]}; + if((!ai_wenet)|| (!ai_munet) ||(!net_wavmat))return -13; + JMat* mat_feat = bnf_cache->inxBuf(index); + if(!mat_feat)return -14; + MWorkMat wmat(mat_pic,mat_msk,arr); + wmat.premunet(); + JMat *mpic, *mmsk; + wmat.munet(&mpic,&mmsk); + lock_munet->lock(); + if(ai_munet) ai_munet->domodel(mpic, mmsk, mat_feat); + lock_munet->unlock(); + wmat.finmunet(mat_fg); + //memcpy(mat_fg->data(),dstbuf,size); + memcpy(dstbuf,mat_fg->data(),size); + memcpy(mskbuf,mat_msk->data(),size); + //todo + frameSource->pushVidRecyle(mat_pic); + frameSource->pushVidRecyle(mat_msk); + frameSource->pushVidRecyle(mat_fg); + return 0; +} + +int GDigit::onerstbuf(int index,const char* picfn,int* box,char* dstbuf,int size){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(!ai_munet)return -998; + //if(!mat_bg)return -3; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>=cnt_wenet)return -3; + std::string picfile(picfn); + + JMat* mat_pic = NULL;//new JMat(picfile,1); + frameSource->popVidRecyle(&mat_pic); + if(!mat_pic)mat_pic = new JMat(); + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + if(rst)break; + break; + } + if(rst){ + if(mat_pic) delete mat_pic; + return rst*10000; + } + if(sizesize()){ + if(mat_pic) delete mat_pic; + return -10000; + } + int arr[4]={box[0],box[1],box[2],box[3]}; + if((!ai_wenet)|| (!ai_munet) ||(!net_wavmat))return -13; + JMat* mat_feat = bnf_cache->inxBuf(index); + if(!mat_feat)return -14; + MWorkMat wmat(mat_pic,NULL,arr); + wmat.premunet(); + JMat *mpic, *mmsk; + wmat.munet(&mpic,&mmsk); + lock_munet->lock(); + if(ai_munet) ai_munet->domodel(mpic, mmsk, mat_feat); + lock_munet->unlock(); + //todo + wmat.finmunet(mat_pic); + //memcpy(mat_fg->data(),dstbuf,size); + memcpy(dstbuf,mat_pic->data(),size); + //todo + frameSource->pushVidRecyle(mat_pic); + return 0; +} + +int GDigit::mskrstpic(int index,const char* picfn,int* box,const char* mskfn,const char* fgfn){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(!ai_munet)return -998; + if(!mat_bg)return -3; + if(!net_wavmat)return -1; + if(index<0)return -2; + //if(!net_wavmat)return -1; + //if(index>net_wavmat->bnfblocks())return -3; + if(index>=cnt_wenet)return -3; + std::string picfile(picfn); + std::string mskfile(mskfn); + std::string fgfile(strlen(fgfn)?fgfn:""); + + JMat* mat_fg = NULL;//new JMat(fgfile,1); + JMat* mat_pic = NULL;//new JMat(picfile,1); + JMat* mat_msk = NULL;//new JMat(mskfile,1); + int hasfg = fgfile.length(); + frameSource->popVidRecyle(&mat_pic); + frameSource->popVidRecyle(&mat_msk); + if(!mat_pic)mat_pic = new JMat(); + if(!mat_msk)mat_msk = new JMat(); + if(hasfg){ + frameSource->popVidRecyle(&mat_fg); + if(!mat_fg)mat_fg = new JMat(); + } + int rst = 0; + while(1){ + rst = mat_pic->load(picfile); + //printf("===matpic %d\n",rst); + if(rst)break; + rst = mat_msk->load(mskfile); + //printf("===mat msk %d\n",rst); + if(rst)break; + if(hasfg) rst = mat_fg->load(fgfile); + //printf("===mat fg %d\n",rst); + break; + } + if(rst){ + if(mat_pic) delete mat_pic; + if(mat_msk) delete mat_msk; + if(mat_fg) delete mat_fg; + return rst*10000; + } + //mat_msk->show("abc"); + //cv::waitKey(0); + int arr[4]={box[0],box[1],box[2],box[3]}; + +//dispThread->dispatch([mat_pic,mat_msk,mat_fg,arr,index,this]() { + if((!ai_wenet)|| (!ai_munet) ||(!mat_bg)||(!net_wavmat))return -13; + + // + //JMat* mw = net_wavmat->bnfmat(); + //float* pwenet = ai_wenet->nextbnf(mw,index); + //if(pwenet){ + // JMat afeat(256, 20, pwenet, 1); + //JMat feat = afeat.clone(); + JMat* mat_feat = bnf_cache->inxBuf(index); + if(mat_feat){ + JMat* bgm = mat_bg->refclone(); + if(mat_fg){ + //if(ai_malpha){ + if(1){ + MWorkMat wmat(mat_pic,mat_msk,arr); + wmat.premunet(); + JMat *mpic, *mmsk; + wmat.munet(&mpic,&mmsk); + lock_munet->lock(); + if(ai_munet) ai_munet->domodel(mpic, mmsk, mat_feat); + lock_munet->unlock(); + wmat.finmunet(mat_fg); + + /* + wmat.prealpha(); + JMat *mreal, *mimg, *mpha; + wmat.alpha(&mreal,&mimg,&mpha); + ai_malpha->doModel(mreal,mimg,mpha); + wmat.finalpha(); + */ + }else{ + lock_munet->lock(); + if(ai_munet) ai_munet->fgprocess(mat_pic, arr, mat_feat,mat_fg); + lock_munet->unlock(); + } + MediaData md(mat_fg,mat_msk,bgm); + frameSource->pushVidFrame(&md); + frameSource->pushVidRecyle(mat_pic); + }else{ + //if(ai_malpha){ + if(1){ + MWorkMat wmat(mat_pic,mat_msk,arr); + wmat.premunet(); + JMat *mpic, *mmsk; + wmat.munet(&mpic,&mmsk); + lock_munet->lock(); + if(ai_munet) ai_munet->domodel(mpic, mmsk, mat_feat); + lock_munet->unlock(); + wmat.finmunet(); + /* + wmat.prealpha(); + JMat *mreal, *mimg, *mpha; + wmat.alpha(&mreal,&mimg,&mpha); + ai_malpha->doModel(mreal,mimg,mpha); + wmat.finalpha(); + */ + }else{ + lock_munet->lock(); + if(ai_munet) ai_munet->process(mat_pic, arr, mat_feat); + lock_munet->unlock(); + } + MediaData md(mat_pic,mat_msk,bgm); + frameSource->pushVidFrame(&md); + } + delete mat_feat; + } +//}); + return 0; +} + +int GDigit::netrstpic(const char* picfn,int* box,int index,const char* dumpfn){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>net_wavmat->bnfblocks())return -3; + std::string picfile(picfn); + JMat* mat_pic = NULL;//new JMat(picfile,1); + frameSource->popVidRecyle(&mat_pic); + if(!mat_pic)mat_pic = new JMat(); + int rst = mat_pic->load(picfn); + if(rst){ + delete mat_pic; + return rst*10000; + } + int arr[4]={box[0],box[1],box[2],box[3]}; +dispThread->dispatch([mat_pic,index,arr,this]() { + if(!ai_wenet)return -11; + if(!net_wavmat)return -12; + + // + //JMat* mw = net_wavmat->bnfmat(); + //float* pwenet = ai_wenet->nextbnf(mw,index); + //if(pwenet){ + //JMat afeat(256, 20, pwenet, 1); + //JMat feat = afeat.clone(); + JMat* mat_feat = bnf_cache->inxBuf(index); + if(mat_feat){ + lock_munet->lock(); + if(ai_munet) ai_munet->process(mat_pic, arr, mat_feat); + lock_munet->unlock(); + MediaData md(mat_pic); + frameSource->pushVidFrame(&md); + delete mat_feat; + } +}); + return 0; +} + +int GDigit::drawpic(const char* picfn){ + if(!m_status)return -1000; + std::string picfile(picfn); + JMat* mat_pic = NULL;//new JMat(picfile,1); + frameSource->popVidRecyle(&mat_pic); + if(!mat_pic)mat_pic = new JMat(); + int rst = mat_pic->load(picfn); + if(rst){ + delete mat_pic; + return rst*10000; + } +//dispThread->dispatch([mat_pic,this]() { + MediaData md(mat_pic); + frameSource->pushVidFrame(&md); +//}); + return 0; +} + +int GDigit::newwav(const char* wavfn,const char* dumpfn){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + int len = strlen(wavfn); + if(len<10)return -101; + char* fn = (char*)(wavfn+len-3); + if((fn[0]!='w')||(fn[1]!='a')||(fn[2]!='v'))return -103; + if(net_curl){ + net_curl->cancel(); + asyncCurl(1,net_curl); + net_curl = nullptr; + } + if(net_wavmat){ + KWav* wm = net_wavmat; + asyncNetwav(1,wm); + //net_wavmat = nullptr; + } + net_wavmat = new KWav(wavfn,bnf_cache); + int rst = 0; + if(net_wavmat->duration()>0){ + // + //int rst = ai_wenet->nextwav(wavfn,&mat_wenet); + wenetThread->post(9999,net_wavmat); + for(int k=0;k<30;k++){ + if(net_wavmat->resultcnt()){ + break; + } + usleep(100000); + } + rst = net_wavmat->bnfblocks();//net_curl->checked(); + cnt_wenet = rst; + inx_wenet = 0; + }else{ + rst = 0; + } + return rst; +} + +int GDigit::picrst(const char* picfn,int* box,int index,const char* dumpfn){ + if(!m_status)return -1000; + if(!ai_wenet)return -999; + if(!net_wavmat)return -1; + if(index<0)return -2; + if(index>=cnt_wenet)return -3; + std::string picfile(picfn); + JMat* mat_pic = NULL;//new JMat(picfile,1); + frameSource->popVidRecyle(&mat_pic); + if(!mat_pic)mat_pic = new JMat(); + int rst = mat_pic->load(picfn); + if(rst){ + delete mat_pic; + return rst*10000; + } + int arr[4]={box[0],box[1],box[2],box[3]}; +//dispThread->dispatch([mat_pic,arr,index,this]() { + if(!ai_wenet)return -11; + if(!net_wavmat)return -12; + // + /* + JMat* mw = net_wavmat->bnfmat(); + float* pwenet = ai_wenet->nextbnf(mw,index); + if(pwenet){ + JMat afeat(256, 20, pwenet, 1); + JMat feat = afeat.clone(); + */ + JMat* mat_feat = bnf_cache->inxBuf(index); + if(mat_feat){ + ai_munet->process(mat_pic, arr, mat_feat); + MediaData md(mat_pic); + frameSource->pushVidFrame(&md); + delete mat_feat; + } +//}); + return 0; +} + + +void GDigit::prepare(){ + GRender::prepare(); +} + +void GDigit::start(){ + m_status = 1; + GRender::start(); +} + +void GDigit::recyle(){ +dispThread->dispatch([this]() { + if(ai_munet){ + lock_munet->lock(); + delete ai_munet; + ai_munet = nullptr; + lock_munet->unlock(); + } + if(ai_malpha){ + delete ai_malpha; + ai_malpha = nullptr; + } + if(mat_bg){ + delete mat_bg; + mat_bg = nullptr; + } +}); + if(ai_wenet){ + asyncWenet(1,ai_wenet); + ai_wenet = nullptr; + } + if(net_wavmat){ + asyncNetwav(1,net_wavmat); + net_wavmat = nullptr; + } +} + +void GDigit::clear(){ + if(net_curl){ + net_curl->cancel(); + asyncCurl(1,net_curl); + net_curl = nullptr; + } +} + +void GDigit::stop(){ + m_status = 0; + dispThread->removePending(); + GRender::stop(); + clear(); + usleep(1000); +} + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.h new file mode 100644 index 0000000000000000000000000000000000000000..b54cb88f4602a4ea12dbcc3bb6fd9c1c0688cf94 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GDigit.h @@ -0,0 +1,109 @@ +#ifndef GPLAYER_GDigit_H +#define GPLAYER_GDigit_H + +#include "scrfd.h" +#include "pfpld.h" +#include "munet.h" +#include "wenet.h" +#include "netcurl.h" +#include "netwav.h" +#include "GRender.h" +#include "looper.h" +#include "dispatchqueue.hpp" +#include "malpha.h" +#include "wavcache.h" + +class LoopWenet:public looper{ + private: + Wenet* m_wenet = nullptr; + int calcinx(KWav* wavmat,int index); + int calcall(KWav* wavmat); + public: + virtual void handle(int what, void *obj); + LoopWenet(); + virtual ~LoopWenet(); +}; + +class LoopCurl:public looper{ + public: + virtual void handle(int what, void *obj); + LoopCurl(); + virtual ~LoopCurl(); +}; + +class GDigit :public GRender{ + public: + GDigit(int width,int height, MessageCb *obj); + virtual ~GDigit(); + public: + int config(const char* cfgtxt); + + int initScrfd(char* fnparam,char* fnbin); + int initPfpld(char* fnparam,char* fnbin); + + int initWenet(char* fnwenet); + int initMunet(char* fnparam,char* fnbin,char* fnmsk); + int initMalpha(char* fnparam,char* fnbin); + int initCurl(char* cacertfn,int timeoutms); + + int netwav(const char* url,float duration); + int bgpic(const char* bgfn); + int drawmskpic(const char* picfn,const char* mskfn); + int drawmskbuf(const char* picfn,const char* mskfn,char* dstbuf,char* mskbuf,int size); + int mskrstpic(int index,const char* picfn,int* box,const char* mskfn,const char* fgfn); + int mskrstbuf(int index,const char* picfn,int* box,const char* mskfn,const char* fgfn,char* dstbuf,char* mskbuf,int size); + int drawonebuf(const char* picfn,char* dstbuf,int size); + int onerstbuf(int index,const char* picfn,int* box,char* dstbuf,int size); + + int netrstpic(const char* picfn,int* box,int index,const char* dumpfn); + int drawpic(const char* picfn); + + int newwav(const char* wavfn,const char* dumpfn); + int picrst(const char* picfn,int* box,int index,const char* dumpfn); + + //int mskrst(int index,const char* dumpfn); + int netrst(int index,const char* dumpfn){return -1;}; + //int initModel(const char* modeldir); + int newpic(const char* picfn,const char* dumpbox){return -1;}; + int newrst(int index,const char* dumpfn){return -1;}; + private: + int m_timeoutms = 0; + Scrfd* ai_scrfd = nullptr; + Pfpld* ai_pfpld = nullptr; + + Wenet* ai_wenet = nullptr; + Mobunet* ai_munet = nullptr; + MAlpha* ai_malpha = nullptr; + std::mutex *lock_munet; + + NetCurl* net_curl = nullptr; + KWav* net_wavmat = nullptr; + MBnfCache *bnf_cache = nullptr; + + //JMat* mat_wenet = nullptr; + volatile int cnt_wenet = 0; + volatile int inx_wenet = 0; + + JMat* mat_bg = nullptr; + LoopWenet *wenetThread = nullptr; + void asyncWenet(int act,Wenet* wenet); + void asyncNetwav(int act,KWav* netwav); + LoopCurl *curlThread = nullptr; + void asyncCurl(int act,NetCurl* curl); + DispatchQueue *dispThread = nullptr; + volatile int m_status = 0; + volatile int m_working = 0; + + void clear(); + public: + + virtual void prepare(); + virtual void start(); + virtual void stop(); + virtual void recyle(); + +}; + + +#endif //GPLAYER_GPLAYER_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1d804ad90759a519076222d083e2603b4c3d4467 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.cpp @@ -0,0 +1,254 @@ +#include "GRender.h" +#include "MediaData.h" +#include "LoopThreadHelper.h" +#include +#include +#include + + +#define TAG "tooken" + +GRender::GRender(int width,int height, MessageCb *obj) { + m_width = width; + m_height = height; + messageSource = new MessageSource(); + frameSource = new FrameSource(MAX_BUFFER_FRAME_SIZE, MAX_BUFFER_FRAME_SIZE); + renderHelper = nullptr; + messageHelper = new MessageHelper(messageSource, obj); + audioRenderThread = nullptr; + videoRenderThread = nullptr; + messageThread = nullptr; +} + +GRender::~GRender() { + delete audioRenderThread; + delete videoRenderThread; + delete messageThread; + + delete renderHelper; + delete messageHelper; + delete frameSource; + delete messageSource; + LOGI(TAG, "CoreFlow : GRenderImp destroyed"); +} + +void GRender::setSurface(NativeWindowType window) { + nativeWindow = window; + LOGI(TAG, "setSurface %p", nativeWindow); +} + +void GRender::setAudioTrack(AudioTrack *track) { + audioTrack = track; + LOGI(TAG, "setAudioTrack %p", audioTrack); +} + +void GRender::prepare(){ + playState = -1; + bufferState = -1; + isEof = false; + onPlayStateChanged(STATE_PREPARING, 0); + startMessageLoop(); +} + +void GRender::start() { + LOGI(TAG, "CoreFlow : start playing"); + if (!nativeWindow ) { + messageHelper->notifyObj(MSG_DOMAIN_ERROR, MSG_ERROR_RENDERING, 0, "invalid surface", nullptr); + return; + } + startRendering(); + //上报开始缓冲消息,等缓冲满了再进行播放 + onBufferStateChanged(0); +} + +void GRender::pause() { + onPlayStateChanged(STATE_PAUSED, 0); + pauseThreads( true, true); +} + +void GRender::resume() { + onPlayStateChanged(STATE_STARTED, 0); + resumeThreads( true, true); +} + + +void GRender::stop() { + LOGI(TAG, "CoreFlow : stop playing"); + stopRendering(); + stopMessageLoop(); + + frameSource->flush(); + messageSource->flush(); + + LOGI(TAG, "CoreFlow : player stopped %d %d %d", + frameSource->audioSize(), frameSource->videoSize(), messageSource->size()); + onPlayStateChanged(STATE_STOPPED, 0); +} + +int GRender::setVideoParam(int width,int height){ + m_width = width; + m_height = height; + return 0; +} + +int GRender::getVideoWidth() { + return m_width; +} + +int GRender::getVideoHeight() { + return m_height; +} + + +void GRender::onRenderingChanged(int state) { + LOGI(TAG, "onRenderingChanged %d", state); + if (state == NOTIFY_END) { + if (isEof) { + messageSource->pushMessage(MSG_DOMAIN_COMPLETE, 0, 0); + } + } +} + +void GRender::onBufferStateChanged(int state) { + playerLock.lock(); + if (state == bufferState || playState != STATE_STARTED) { + playerLock.unlock(); + return; + } + LOGI(TAG, "onBufferStateChanged %d-->%d", bufferState, state); + bufferState = state; + messageHelper->notifyObj(MSG_DOMAIN_BUFFER, bufferState, bufferState, nullptr, nullptr); + playerLock.unlock(); +} + +void GRender::onPlayStateChanged(int state, long extra) { + playerLock.lock(); + if (state == playState) { + playerLock.unlock(); + return; + } + LOGI(TAG, "onPlayStateChanged %d-->%d", playState, state); + playState = state; + /* + if (playState == STATE_PREPARED) { + hasAudio = (extra & HAS_AUDIO) == HAS_AUDIO; + hasVideo = (extra & HAS_VIDEO) == HAS_VIDEO; + LOGI(TAG, "hasAudio %d, hasVideo %d", hasAudio, hasVideo); + } + */ + messageHelper->notifyObj(MSG_DOMAIN_STATE, playState, 0, nullptr, nullptr); + playerLock.unlock(); +} + +int GRender::processMessage(int arg1, long arg2) { + Message *message; + if (messageSource->readMessage(&message) > 0) { + if (message->from == MSG_DOMAIN_ERROR) { + messageHelper->handleErrorMessage(message); + } else if (message->from == MSG_DOMAIN_STATE) { + onPlayStateChanged(message->type, message->extra); + } else if (message->from == MSG_DOMAIN_BUFFER) { + onBufferStateChanged(message->type); + } else if (message->from == MSG_DOMAIN_DEMUXING) { + isEof = message->type == MSG_DEMUXING_EOF; + } else if (message->from == MSG_DOMAIN_SEEK) { + //onSeekStateChanged(message->type); + } else { + messageHelper->notifyObj(message->from, message->type, message->extra, nullptr, nullptr); + } + messageSource->popMessage(); + } else { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + return 0; +} + +void GRender::startMessageLoop() { + LOGI(TAG, "startMessageLoop"); + messageThread = LoopThreadHelper::createLoopThread( + std::bind(&GRender::processMessage, this, std::placeholders::_1, std::placeholders::_2)); +} + +void GRender::stopMessageLoop() { + if (messageThread && messageThread->hasStarted()) { + messageThread->stop(); + messageSource->reset(); + messageThread->join(); + delete messageThread; + messageThread = nullptr; + } + LOGI(TAG, "message thread was stopped!"); +} + + +void GRender::startRendering() { + LOGI(TAG, "startRender"); + int mediaCodecFlag = 0; + renderHelper = new RenderHelper(frameSource, messageSource, mediaCodecFlag, hasAudio, hasVideo); + if (hasAudio) { + int sampleRate = 16000; + int channels = 1; + int format = 1; + int bytesPerSample = 16; + renderHelper->setAudioTrack(audioTrack); + renderHelper->setAudioParams(sampleRate, channels, format, bytesPerSample); + audioRenderThread = LoopThreadHelper::createLoopThread( + std::bind(&RenderHelper::initAudioRenderer, renderHelper), + std::bind(&RenderHelper::renderAudio, renderHelper, std::placeholders::_1, std::placeholders::_2), + std::bind(&RenderHelper::releaseAudioRenderer, renderHelper), + std::bind(&GRender::onRenderingChanged, this, std::placeholders::_1)); + } + + if (hasVideo) { + int width = m_width; + int height = m_height; + renderHelper->setNativeWindow(nativeWindow); + renderHelper->setVideoParams(width, height); + videoRenderThread = LoopThreadHelper::createLoopThread( + std::bind(&RenderHelper::initVideoRenderer, renderHelper), + std::bind(&RenderHelper::renderVideo, renderHelper, std::placeholders::_1, std::placeholders::_2), + std::bind(&RenderHelper::releaseVideoRenderer, renderHelper), + std::bind(&GRender::onRenderingChanged, this, std::placeholders::_1)); + } +} + +void GRender::stopRendering() { + if (audioRenderThread && audioRenderThread->hasStarted()) { + audioRenderThread->stop(); + frameSource->reset(); + audioRenderThread->join(); + delete audioRenderThread; + audioRenderThread = nullptr; + } + if (videoRenderThread && videoRenderThread->hasStarted()) { + videoRenderThread->stop(); + frameSource->reset(); + videoRenderThread->join(); + delete videoRenderThread; + videoRenderThread = nullptr; + } + delete renderHelper; + renderHelper = nullptr; + LOGI(TAG, "rendering threads were stopped!"); +} + +void GRender::pauseThreads( bool rendering, bool messaging) { + if (rendering) { + if (hasAudio) audioRenderThread->pause(); + if (hasVideo) videoRenderThread->pause(); + } + if (messaging) { + messageThread->pause(); + } +} + +void GRender::resumeThreads( bool rendering, bool messaging) { + if (rendering) { + if (hasAudio) audioRenderThread->resume(); + if (hasVideo) videoRenderThread->resume(); + } + if (messaging) { + messageThread->resume(); + } +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.h new file mode 100644 index 0000000000000000000000000000000000000000..25f7f7bbc6115511f91505b04e1adb3cad385e8d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/GRender.h @@ -0,0 +1,70 @@ +#ifndef GPLAYER_GRender_H +#define GPLAYER_GRender_H + +#include "CommObj.h" +#include "MessageHelper.h" +#include "LoopThread.h" +#include "FrameSource.h" +#include "MessageSource.h" +#include "RenderHelper.h" + +class GRender { +public: + GRender(int width,int height, MessageCb *obj); + virtual ~GRender(); + +public: + void setSurface(NativeWindowType window); + void setAudioTrack(AudioTrack *track); + + virtual void prepare(); + virtual void start(); + virtual void pause(); + virtual void resume(); + virtual void stop(); + + int getVideoWidth(); + int getVideoHeight(); + int setVideoParam(int width,int height); + + void onRenderingChanged(int state); + void onBufferStateChanged(int state); + void onPlayStateChanged(int state, long extra); +protected: + int processMessage(int arg1, long arg2); + + void startMessageLoop(); + void stopMessageLoop(); + + void startRendering(); + void stopRendering(); + + void pauseThreads( bool rendering, bool messaging); + void resumeThreads( bool rendering, bool messaging); +protected: + NativeWindowType nativeWindow = 0; + AudioTrack *audioTrack = nullptr; + + FrameSource *frameSource; + MessageSource *messageSource; + + RenderHelper *renderHelper; + MessageHelper *messageHelper; + + LoopThread *audioRenderThread; + LoopThread *videoRenderThread; + LoopThread *messageThread; + + int m_width = 0; + int m_height = 0; + int playState = -1; + int bufferState = -1; + bool isEof = false; + bool hasAudio = false; + bool hasVideo = true; + std::mutex playerLock; +}; + + +#endif //GPLAYER_GPLAYER_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/dispatchqueue.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/dispatchqueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f04324b8ca19ee72d904c6794f759dd452e6eca7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/dispatchqueue.cpp @@ -0,0 +1,87 @@ + +#include "dispatchqueue.hpp" + +DispatchQueue::DispatchQueue(std::string name, size_t threadCount) : + name{std::move(name)}, threads(threadCount) { + fp_timeout = std::bind(def_timeout); + for(size_t i = 0; i < threads.size(); i++) + { + threads[i] = std::thread(&DispatchQueue::dispatchThreadHandler, this); + } + } + +DispatchQueue::~DispatchQueue() { + // Signal to dispatch threads that it's time to wrap up + std::unique_lock lock(lockMutex); + quit = true; + lock.unlock(); + condition.notify_all(); + + // Wait for threads to finish before we exit + for(size_t i = 0; i < threads.size(); i++) + { + if(threads[i].joinable()) + { + threads[i].join(); + } + } +} + +void DispatchQueue::removePending() { + std::unique_lock lock(lockMutex); + queue = {}; +} + +void DispatchQueue::dispatchtimeout(const fp_t& op) { + fp_timeout = std::bind(op); +} + +void DispatchQueue::dispatch(const fp_t& op) { + std::unique_lock lock(lockMutex); + queue.push(op); + + // Manual unlocking is done before notifying, to avoid waking up + // the waiting thread only to block again (see notify_one for details) + lock.unlock(); + condition.notify_one(); +} + +void DispatchQueue::dispatch(fp_t&& op) { + std::unique_lock lock(lockMutex); + queue.push(std::move(op)); + + // Manual unlocking is done before notifying, to avoid waking up + // the waiting thread only to block again (see notify_one for details) + lock.unlock(); + condition.notify_one(); +} + +void DispatchQueue::dispatchThreadHandler(void) { + std::unique_lock lock(lockMutex); + do { + //Wait until we have data or a quit signal + //condition.wait(lock, [this]{ + auto r = condition.wait_for(lock, std::chrono::milliseconds(1000),[this]{ + return (queue.size() || quit); + }); + //if (r){ + //std::cout<<"====timeout==="< +#include +#include +#include +#include +#include +#include + +class DispatchQueue { + typedef std::function fp_t; + +public: + DispatchQueue(std::string name, size_t threadCount = 1); + ~DispatchQueue(); + + // dispatch and copy + void dispatch(const fp_t& op); + void dispatchtimeout(const fp_t& op); + // dispatch and move + void dispatch(fp_t&& op); + + void removePending(); + + // Deleted operations + DispatchQueue(const DispatchQueue& rhs) = delete; + DispatchQueue& operator=(const DispatchQueue& rhs) = delete; + DispatchQueue(DispatchQueue&& rhs) = delete; + DispatchQueue& operator=(DispatchQueue&& rhs) = delete; + +private: + std::string name; + std::mutex lockMutex; + std::vector threads; + std::queue queue; + fp_t fp_timeout; + std::condition_variable condition; + bool quit = false; + + void dispatchThreadHandler(void); + static void def_timeout(void){}; +}; + +#endif /* dispatchqueue_hpp */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.c b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.c new file mode 100644 index 0000000000000000000000000000000000000000..62a719641330e17f75cf35c5c88528259387d922 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.c @@ -0,0 +1,201 @@ +#include +#include "grtcfg.h" +#include "cJSON.h" +#include "grefmem.h" +#include "Log.h" + +#define TAG "tookencfg" +static int cjson_nval(cJSON* root,const char* name,int* val){ + if(!root||!val) return -1; + cJSON* jobj=cJSON_GetObjectItem(root,name); + if(!jobj)return -2; + *val = jobj->valueint; + return 0; +} + +static int cjson_sval(cJSON* root,const char* name,char** val){ + if(!root||!val) return -1; + cJSON* jobj=cJSON_GetObjectItem(root,name); + if(!jobj)return -2; + *val = jobj->valuestring; + return 0; +} + +static int cjson_nset(cJSON* root,const char* name,int val){ + if(!root||!name)return 0; + cJSON_DeleteItemFromObject(root,name); + cJSON_AddNumberToObject(root,name,val); + return 0; +} + +static int cjson_sset(cJSON* root,const char* name,char* val){ + if(!root||!name||!val)return 0; + cJSON_DeleteItemFromObject(root,name); + cJSON_AddStringToObject(root,name,val); + return 0; +} + +static int cjson_listsset(cJSON* root,char** name,char** val,int append){ + if(!root||!name||!val)return 0; + char** pp=name; char** vv=val; + char *p=*pp; char *v=*vv; + int cnt=0; + if(append){ + while(p&&vv){ + cJSON* jobj=cJSON_GetObjectItem(root,p); + if(!jobj) cJSON_AddStringToObject(root,p,v); + cnt++; p = *++pp; v = *++vv; + } + }else{ + while(p&&vv){ + cJSON_DeleteItemFromObject(root,p); + cJSON_AddStringToObject(root,p,v); + cnt++; p = *++pp; v = *++vv; + } + } + return cnt; +} + +static int cjson_listnset(cJSON* root,char** name,int* val,int append){ + if(!root||!name||!val)return 0; + char** pp=name; int* vv=val; + char *p=*pp; int v=*vv; + int cnt=0; + if(append){ + while(p&&vv){ + cJSON* jobj=cJSON_GetObjectItem(root,p); + if(!jobj) cJSON_AddNumberToObject(root,p,v); + cnt++; p = *++pp; v = *++vv; + } + }else{ + while(p&&vv){ + cJSON_DeleteItemFromObject(root,p); + cJSON_AddNumberToObject(root,p,v); + cnt++; p = *++pp; v = *++vv; + } + } + return cnt; +} + +static int cjson_listsval(cJSON* root,char** name,char*** val){ + if(!root||!name||!val)return 0; + char** pp=name; char*** vv=val; + char *p=*pp; char **v=*vv; + int cnt=0; + while(p&&v){ + cJSON* jobj=cJSON_GetObjectItem(root,p); + if(jobj) *v = jobj->valuestring; + cnt++; p = *++pp; v = *++vv; + } + return cnt; +} + +static int cjson_listnval(cJSON* root,char** name,int** val){ + if(!root||!name||!val)return 0; + char** pp=name; int** vv=val; + char *p=*pp; int *v=*vv; + int cnt=0; + while(p&&v){ + cJSON* jobj=cJSON_GetObjectItem(root,p); + if(jobj) *v = jobj->valueint; + p=*++pp; v=*++vv; cnt++; + } + return cnt; +} + +static char* g_ncfgname[] = { + "action","videowidth", "videoheight", "timeoutms", + NULL}; + +static char* g_scfgname[] = { + "defdir","wenetfn","unetbin","unetparam", + "unetmsk","alphabin","alphaparam", + "cacertfn","scrfdbin","scrfdparam", + "pfpldbin","pfpldparam", + NULL}; + +static void destroy_rtcfg(void* arg){ + rtcfg_t* cfg = (rtcfg_t*)arg; + if(cfg->base_obj){ + cJSON* root = (cJSON*)cfg->base_obj; + cJSON_Delete(root); + cfg->base_obj = NULL; + } +} + + + +rtcfg_t* make_rtcfgjson(char* str){ + if(!str || !strlen(str))return NULL; + cJSON* root = NULL; + root = cJSON_Parse(str); + if(!root){ + //LOGE(TAG,"===parse json error\n"); + return NULL; + } + rtcfg_t* cfg = NULL; + gjrefobj_alloc(cfg,sizeof(rtcfg_t),destroy_rtcfg); + memset(cfg,0,sizeof(rtcfg_t)); + cfg->base_obj = root; + int* arrval[] = { + &cfg->action, &cfg->videowidth, &cfg->videoheight, + &cfg->timeoutms, + NULL}; + cjson_listnval(root,g_ncfgname,arrval); + char** arrstr[] = { + &cfg->defdir, + &cfg->wenetfn, + &cfg->unetbin, + &cfg->unetparam, + &cfg->unetmsk, + &cfg->alphabin, + &cfg->alphaparam, + &cfg->cacertfn, + &cfg->scrfdbin, + &cfg->scrfdparam, + &cfg->pfpldbin, + &cfg->pfpldparam, + NULL, + }; + cjson_listsval(root,g_scfgname,arrstr); + return cfg; +} + + +int nval_rtcfg(rtcfg_t* cfg,char* name){ + if(!cfg->base_obj)return 0; + cJSON* root = (cJSON*)cfg->base_obj; + int rst = 0; + cjson_nval(root,name,&rst); + return rst; +} + +char* sval_rtcfg(rtcfg_t* cfg,char* name){ + if(!cfg->base_obj)return NULL; + cJSON* root = (cJSON*)cfg->base_obj; + char* val = NULL; + cjson_sval(root,name,&val); + return val; +} + +char* dump_rtcfg(rtcfg_t* cfg){ + //return cJSON_PrintUnformatted((cJSON*)cfg->base_obj); + return cJSON_Print((cJSON*)cfg->base_obj); +} + +int final_rtcfg(rtcfg_t* cfg){ + if(cfg) gjrefobj_unref(cfg); + return 0; +} + +#ifdef RTCFGTEST +#include +int main(int argc,char** argv){ + rtcfg_t* cfg = make_rtcfgpre(1080,0); + char* txt = dump_rtcfg(cfg); + printf("cfg %s\n",txt); + free(txt); + final_rtcfg(cfg); + return 0; +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.h new file mode 100644 index 0000000000000000000000000000000000000000..f8bdfe787c54c26784ff42e5f7e0e150d47468e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/grtcfg.h @@ -0,0 +1,42 @@ +#ifndef _GRTCFG_H__ +#define _GRTCFG_H__ + +#ifdef __cplusplus +extern "C" { +#endif +/* + * {"width":1080,"height":1920,"fps":25,"samplerate":48000,"channels":1,"bitrate":0,"bframe":0,"gopsize":25,"cuda":0,"opus":0,"srcwidth":480,"srcheight":640,"srcformat":0,"srcsample":16000,"srcchannel":1,"maxqueue":200,"maxrecyle":50,"timeout":60000,"nb_samples":1024} + * + * */ + typedef struct rtcfg_s rtcfg_t; + struct rtcfg_s{ + int action; + int videowidth; + int videoheight; + int timeoutms; + char* defdir; + char* wenetfn; + char* unetbin; + char* unetparam; + char* unetmsk; + char* alphabin; + char* alphaparam; + char* cacertfn; + char* scrfdbin; + char* scrfdparam; + char* pfpldbin; + char* pfpldparam; + void *base_obj; + }; + + rtcfg_t* make_rtcfgjson(char* str); + int nval_rtcfg(rtcfg_t* cfg,char* name); + char* sval_rtcfg(rtcfg_t* cfg,char* name); + char* dump_rtcfg(rtcfg_t* cfg); + int final_rtcfg(rtcfg_t* cfg); + +#ifdef __cplusplus +} +#endif +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79922691392dafff20dbe79e0a82ccfe101dea07 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.cpp @@ -0,0 +1,139 @@ + +#include "looper.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// for __android_log_print(ANDROID_LOG_INFO, "YourApp", "formatted message"); +#ifdef __ANDROID +#include +#include +#define TAG "NativeCodec-looper" +#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, TAG, __VA_ARGS__) +#else +#define TAG "NativeCodec-looper" +#define LOGV(...) +#endif + +struct loopermessage; +typedef struct loopermessage loopermessage; + +struct loopermessage { + int what; + void *obj; + loopermessage *next; + bool quit; +}; + +void *looper::trampoline(void *p) { + ((looper *)p)->loop(); + return NULL; +} + +looper::looper() { + sem_init(&headdataavailable, 0, 0); + sem_init(&headwriteprotect, 0, 1); + pthread_attr_t attr; + pthread_attr_init(&attr); + + pthread_create(&worker, &attr, trampoline, this); + running = true; +} + +looper::~looper() { + if (running) { + LOGV( + "Looper deleted while still running. Some messages will not be " + "processed"); + quit(); + } +} + +void looper::post(int what, void *data, bool flush) { + loopermessage *msg = new loopermessage(); + msg->what = what; + msg->obj = data; + msg->next = NULL; + msg->quit = false; + addmsg(msg, flush); +} + +void looper::addmsg(loopermessage *msg, bool flush) { + sem_wait(&headwriteprotect); + loopermessage *h = head; + + if (flush) { + while (h) { + loopermessage *next = h->next; + delete h; + h = next; + } + h = NULL; + } + if (h) { + while (h->next) { + h = h->next; + } + h->next = msg; + } else { + head = msg; + } + LOGV("post msg %d", msg->what); + sem_post(&headwriteprotect); + sem_post(&headdataavailable); +} + +void looper::loop() { + while (true) { + // wait for available message + sem_wait(&headdataavailable); + + // get next available message + sem_wait(&headwriteprotect); + loopermessage *msg = head; + if (msg == NULL) { + LOGV("no msg"); + sem_post(&headwriteprotect); + continue; + } + head = msg->next; + sem_post(&headwriteprotect); + + if (msg->quit) { + LOGV("quitting"); + delete msg; + return; + } + LOGV("processing msg %d", msg->what); + handle(msg->what, msg->obj); + delete msg; + } +} + +void looper::quit() { + LOGV("quit"); + loopermessage *msg = new loopermessage(); + msg->what = 0; + msg->obj = NULL; + msg->next = NULL; + msg->quit = true; + addmsg(msg, false); + void *retval; + pthread_join(worker, &retval); + sem_destroy(&headdataavailable); + sem_destroy(&headwriteprotect); + running = false; +} + +void looper::handle(int what, void *obj) { + LOGV("dropping msg %d %p", what, obj); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.h new file mode 100644 index 0000000000000000000000000000000000000000..453e89dbffae4ad4cefbd07842ad6a5fcf7df727 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/looper.h @@ -0,0 +1,28 @@ +#pragma once +#include +#include + +struct loopermessage; + +class looper { + public: + looper(); + looper& operator=(const looper&) = delete; + looper(looper&) = delete; + virtual ~looper(); + + void post(int what, void* data, bool flush = false); + void quit(); + + virtual void handle(int what, void* data); + + private: + void addmsg(loopermessage* msg, bool flush); + static void* trampoline(void* p); + void loop(); + loopermessage* head = nullptr; + pthread_t worker; + sem_t headwriteprotect; + sem_t headdataavailable; + bool running; +}; diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..855bf24b013632b5f47219c01912ede9cc815a75 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.cpp @@ -0,0 +1,274 @@ +#include "netcurl.h" +#include +#include +#include "face_utils.h" +#include "jlog.h" + + +static int curl_inited = 0; +static char curl_certpath[255]; +int guiji_curl_final(){ + if(curl_inited){ + curl_inited = 0; + curl_global_cleanup(); + } + return 0; +} + +int guiji_curl_init(const char* certpath){ + if(!curl_inited){ + curl_inited = 1; + curl_global_init(CURL_GLOBAL_ALL); + //sprintf(curl_certpath,"%s/cacert.pem",certpath); + sprintf(curl_certpath,"%s",certpath); + //curl_global_init(0); + } + return 0; +} + +static size_t write_data(char *buffer, size_t size, size_t nmemb, void *data) { + NetCurl* pcurl = (NetCurl*)data; + if(pcurl->status())return -1; + int realsize = size * nmemb; + int rst = pcurl->push(buffer,realsize); + return rst; +} + + +NetCurl::NetCurl(const char* url,float duration,KWav* wavmat,looper* loop, int timeoutms){ + m_loop = loop; + //guiji_curl_init(); + m_timeoutms = timeoutms; + m_url = std::string(url); + m_duration = duration; + m_wavmat = wavmat;//new KWav(m_duration); + //post(0,this); + + //int rst = docurl(); + LOGD("====post init\n"); +} + +int NetCurl::docurl(){ + int rst = 0; + CURLcode res = CURLE_OK; + CURL *curl = curl_easy_init(); + if(!curl)return -997; + // + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L); // 跳过证书检查 + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L); + //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // 跳过证书检查 + //curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + curl_easy_setopt(curl, CURLOPT_CAINFO, curl_certpath); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); + + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); + curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, m_timeoutms); + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, m_timeoutms); + curl_easy_setopt(curl, CURLOPT_URL, m_url.c_str()); + curl_easy_setopt(curl, CURLOPT_POST, 0); + //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params); + res = curl_easy_perform(curl); + if(curl) curl_easy_cleanup(curl); + if (res == CURLE_OK) { + // + rst = 0; + if(m_loop) m_loop->post(9999,m_wavmat); + }else{ + m_status = -1; + rst= 0 - res; + } + return rst; +} + +int NetCurl::push(char* data,int len){ + if(m_first){ + //check header + if(len<44)return -1; + wave_pcm_hdr *hdr = (wave_pcm_hdr*)data; + char* riff = hdr->riff; + if((riff[0]!='R')|| + (riff[1]!='I')|| + (riff[2]!='F')|| + (riff[3]!='F'))return -2; + int alllen = hdr->size_8 + 8; + int datasize = hdr->data_size; + char* chck = hdr->data; + int list = 0; + if((chck[0]=='L')|| + (chck[1]=='I')|| + (chck[2]=='S')|| + (chck[3]=='T'))list=1; + if(list){ + m_skiplen = 44+datasize; + int* ddd = (int*)((uint8_t*)data+m_skiplen); + chck = (char*)ddd; + if((chck[0]=='d')|| + (chck[1]=='a')|| + (chck[2]=='t')|| + (chck[3]=='a')){ + datasize = ddd[1]; + m_skiplen += 8; + }else{ + LOGE("none data after LIST %c %c %c %c\n",chck[0],chck[1],chck[2],chck[3]); + return -5; + } + }else{ + m_skiplen = 44; + } + LOGD("===data %d \n",datasize); + LOGD("===len %d skip %d\n",len,m_skiplen); + m_wavlen = alllen - m_skiplen; + if(lenpushpcm((uint8_t*)data+m_skiplen,len-m_skiplen); + m_first = 0; + m_checked = 1; + checkwav(); + return len; + } + if(!m_checked)return -999; + m_wavmat->pushpcm((uint8_t*)data,len); + checkwav(); + return len; +} + +int NetCurl::status(){ + return m_status; +} + +int NetCurl::cancel(){ + m_status = -999; + m_loop = nullptr; + return 0; +} + +int NetCurl::checkwav(){ + int rst = m_wavmat->isready(); + if(rst){ + LOGD("====tooken gogogo %d \n",rst); + if(m_loop) m_loop->post(rst,m_wavmat); + } + return 0; +} +/* +void NetCurl::handle(int what, void *obj){ + //init curl +} + +void NetCurl::setready(int inx){ + m_ready = inx; +} + +int NetCurl::getready(){ + return m_ready; +} +*/ + +int NetCurl::checked(){ + return m_first&&m_checked; +} + +NetCurl::~NetCurl(){ + m_status = -1000; + //if(m_wavmat){ + //delete m_wavmat; + //m_wavmat = nullptr; + //} +} + +/* +int NetCurl::calcall(Wenet* pwenet){ + //printf("===calcall\n"); + int rst =m_wavmat->readyall(); + while(1){ + if(m_status)return -1; + rst = m_wavmat->isready(); + if(!rst)break; + calcinx(pwenet,rst); + } + return 0; +} + +int NetCurl::calcinx(Wenet* pwenet,int index){ + if(m_status)return -1; + float* pwav = NULL; + float* pmfcc = NULL; + float* pbnf = NULL; + int melcnt = 0; + int bnfcnt = 0; + int rst = m_wavmat->calcbuf(index, &pwav,&pmfcc,&pbnf,&melcnt,&bnfcnt); + LOGD("===tooken calcinx %d index %d\n",index,rst); + if(rst == index){ + pwenet->calcmfcc(pwav,pmfcc); + if(m_status)return -1; + pwenet->calcbnf(pmfcc,melcnt,pbnf,bnfcnt); + //dumpfloat(pbnf,10); + m_wavmat->finishone(index); + m_calccnt = index; + } + return 0; +} +*/ + +int NetCurl::test(int index){ + return 0; +} + + +//#define _NETMAIN_ +#ifdef _NETMAIN_ + +#include "utils/wavreader.h" +int main(int argc,char** argv){ + guiji_curl_init("../model"); + Wenet wenet("../model","wenet"); + init_wenetloop(&wenet); +if(argc>1){ + const char* wavfile = "http://127.0.0.1:8000/1.wav"; + //float duration = 25*60+19; + //const char* wavfile = "https://digital-public.obs.cn-east-3.myhuaweicloud.com/yunwei_update/wsl/953883.wav"; + //float duration = 11.869; + float duration = 11.869; + KWav wavmat(duration); + NetCurl* curl = new NetCurl(wavfile,duration,&wavmat); + for(int k=0;k<10;k++){ + if(curl->checked())break; + usleep(100000); + } + LOGD("===netwav %d\n",wavmat.bnfblocks()); + wavmat.debug(); + getchar(); + delete curl; +}else{ + const char* wavfile = "../mybin/1.wav"; + JMat* mat = nullptr; + wenet.nextwav(wavfile,&mat); + + //mat->tobin("bbb.bin"); + dumpfloat(mat->fdata(),10); +} + return 0; + /* + const char* wavfile = "../mybin/1.wav"; + FILE* fp = fopen(wavfile,"rb"); // + wave_pcm_hdr* hdr = (wave_pcm_hdr*)malloc(sizeof(wave_pcm_hdr)); + memset(hdr,0,sizeof(wave_pcm_hdr)); + int size = fread(hdr,1,sizeof(wave_pcm_hdr),fp); + char* riff = hdr->riff; + printf("===sheader %d %c %c %c %c\n",size,riff[0],riff[1],riff[2],riff[3]); + printf("===hdr size8 %d data size %d\n",hdr->size_8,hdr->data_size); + fclose(fp); + int format, channels, sr, bits_per_sample; + unsigned int data_length; + void* fhnd = wav_read_open(wavfile); + if(!fhnd)return -1; + int res = wav_get_header(fhnd, &format, &channels, &sr, &bits_per_sample, &data_length); + if(data_length<1) return -2; + printf("====data len %u\n",data_length); + wav_read_close(fhnd); + return 0; + */ +} +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.h new file mode 100644 index 0000000000000000000000000000000000000000..41d588a9bf8477c8eb2bce750421b39183c0ef09 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netcurl.h @@ -0,0 +1,71 @@ +#pragma once +#include "curl/curl.h" +#include "looper.h" +#include "wenet.h" +#include "netwav.h" + +extern "C"{ +#pragma pack(push) +#pragma pack(4) + + typedef struct _wave_pcm_hdr { + char riff[4]; + int size_8; + char wave[4]; + char fmt[4]; + int fmt_size; + short int format_tag; + short int channels; + int samples_per_sec; + int avg_bytes_per_sec; + short int block_align; + short int bits_per_sample; + char data[4]; + unsigned int data_size; + } wave_pcm_hdr; + + struct _chunk_t { + char ID[4]; + unsigned long size; + }; + +#pragma pack(pop) +} + + +class NetCurl{ + private: + std::string m_url; + int m_timeoutms = 6000; + float m_duration = 0; + int m_wavlen = 0; + int m_skiplen = 0; + + volatile int m_first = 1; + volatile int m_checked = 0; + //volatile int m_calccnt = 0; + //volatile int m_ready = 0; + + + int m_status = 0; + KWav *m_wavmat = nullptr; + int checkwav(); + looper *m_loop = nullptr; + public: + int docurl(); + int push(char* data,int len); + int checked(); + //void setready(int inx); + //int getready(); + int calcinx(Wenet* pwenet,int index); + int calcall(Wenet* pwenet); + int cancel(); + int status(); + NetCurl(const char* url,float duration,KWav* wavmat,looper* loop,int timeoutms = 10000); + ~NetCurl(); + int test(int index); +}; + +int guiji_curl_final(); +int guiji_curl_init(const char* certpath); + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15d133e744388f4ccfbf73f46eaafc24fbe8a564 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.cpp @@ -0,0 +1,271 @@ +#include "netwav.h" +#include "face_utils.h" +#include "jlog.h" +#include "wavreader.h" + + +int KWav::initbuf(int pcmsample){ + m_pcmsample = pcmsample; + m_wavsample = pcmsample + 2*MFCC_OFFSET; + + m_seca = m_wavsample / MFCC_WAVCHUNK; + m_secb = m_wavsample % MFCC_WAVCHUNK; + + m_mellast = m_secb?(m_secb /160 +1):0; + m_bnflast = m_secb?((m_mellast*0.25f)-0.75f):0; + + m_wavsize = m_seca*MFCC_WAVCHUNK + m_secb; + + m_melsize = m_seca*MFCC_MELBASE+m_mellast; + m_bnfsize = m_seca*MFCC_BNFBASE+m_bnflast; + + //m_calcsize = m_seca+m_secb?1:0; + m_calcsize = m_seca+(m_secb?1:0); + + m_wavmat = new KMat(MFCC_WAVCHUNK,m_calcsize,1); + m_wavmat->zeros(); + m_melmat = new KMat(MFCC_MELCHUNK*MFCC_MELBASE,m_calcsize,1); + m_melmat->zeros(); + //m_bnfmat = new KMat(MFCC_BNFCHUNK*MFCC_BNFBASE,m_calcsize,1); + //m_bnfmat->zeros(); + m_bnfblock = m_duration*MFCC_FPS; + if(m_bnfblock>(m_bnfsize-10))m_bnfblock = m_bnfsize-10; + LOGD("==seca %d secb %d\n",m_seca,m_secb); + LOGD("==melsize %d bnfsize %d\n",m_melsize,m_bnfsize); + + return 0; +} + +int KWav::initinx(){ + m_curwav = m_wavmat->fdata() + MFCC_OFFSET; + m_leftsample = m_pcmsample; + m_waitsample = MFCC_OFFSET; + + /* + int* arr = m_bnfmat->tagarr(); + arr[0] = m_pcmsample*2; + arr[1] = m_pcmsample; + arr[2] = m_seca; + arr[3] = m_secb; + arr[4] = m_melsize; + arr[5] = m_bnfsize; + */ + float secs = m_pcmsample*1.0f/ MFCC_RATE; + int bnfblock = secs*MFCC_FPS; + if(bnfblock>(m_bnfsize-10))bnfblock = m_bnfsize-10; + //arr[6] = bnfblock;//m_bnfblock; + // + //LOGD("my==bnfblock %d arr6 %d",bnfblock,arr[6]); + //LOGD("myarr %d %d %d %d %d %d %d",arr[0],arr[1],arr[2],arr[3],arr[4],arr[5],arr[6]); + return 0; +} + +int KWav::incsample(int sample){ + if(sample<1)return 0; + m_leftsample -= sample; + m_waitsample += sample; + //LOGD("===incsample %d left %d wait %d\n",sample,m_leftsample,m_waitsample); + while(m_waitsample>MFCC_WAVCHUNK){ + m_waitsample -= MFCC_WAVCHUNK; + m_waitcnt += 1; + LOGD("===tooken calc %d waitcnt %d calc %d\n",m_calcsize,m_waitcnt,m_calccnt); + LOGD("===tooken m_ldftsample %d\n",m_leftsample); + } + if(m_leftsample<=0){ + m_waitcnt = m_calcsize; + LOGD("===tooken m_ldftsample %d\n",m_leftsample); + LOGD("===tooken calc %d waitcnt %d\n",m_calcsize,m_waitcnt); + } + return 0; +} + +int KWav::pushpcm(uint8_t* pcm,int size){ + uint8_t* pstart = pcm; + int psize = size; + if(m_alonecnt){ + pstart++; + psize--; + m_alonearr[1]=*pcm; + float* ps = (float*)m_alonearr; + *m_curwav++ = (float)(*ps++/32767.f); + incsample(1); + m_alonecnt = 0; + } + int sample = psize / 2; + //LOGD("push pcm %d left_sample %d\n",sample,m_leftsample); + int left = psize % 2; + if(sample>m_leftsample){ + sample = m_leftsample; + left = 0; + } + + short* ps = (short*)pstart; + float* pf = m_curwav; + for(int k=0;kdata(),data_length); + // + short* ps = (short*)pcmbuf->data(); + float* pd = (float*)m_wavmat->data(); + float* pf = pd+MFCC_OFFSET; + for(int k=0;ktagarr(); + + float secs = index*MFCC_WAVCHUNK *1.0f/ MFCC_RATE; + if(m_resultcnt==m_calccnt){ + secs = m_pcmsample*1.0f/ MFCC_RATE; + }else{ + secs = index*MFCC_WAVCHUNK *1.0f/ MFCC_RATE; + } + int bnfblock = secs*MFCC_FPS; + if(bnfblock>(m_bnfsize-10))bnfblock = m_bnfsize-10; + //arr[7] = bnfblock; + + return 0; +} + +int KWav::isfinish(){ + if((m_waitcnt == m_calcsize)&&(m_calcsize== m_calccnt)){ + return m_resultcnt==m_calccnt; + }else{ + return 0; + } +} + +int KWav::readyall(){ + m_waitcnt=m_calcsize; + return 0; +} + +int KWav::isready(){ + if(m_waitcnt>m_calccnt){ + return ++m_calccnt; + }else{ + return 0; + } +} + + +int KWav::calcbuf(int calcinx,float** ppwav,float** ppmfcc,float** ppbnf,int* pmel,int* pbnf){ + if(calcinx>m_calcsize)return -1; + if(calcinx<1)return -2; + int index = calcinx -1; + //LOGD("===tooken calcbuf %d\n",index); + *ppwav = m_wavmat->frow(index); + *ppmfcc = m_melmat->frow(index); + //*ppbnf = m_bnfmat->frow(index); + *ppbnf = m_bnfcache->secBuf(index)->fdata(); + if(calcinx==m_calcsize){ + *pmel = m_mellast; + *pbnf = m_bnflast; + }else{ + *pmel = MFCC_MELBASE; + *pbnf = MFCC_BNFBASE; + } + return calcinx; +} + +float KWav::duration(){ + return m_duration; +} + +int KWav::resultcnt(){ + return m_resultcnt; +} + +int KWav::debug(){ + //dumpfloat(m_bnfmat->fdata(),10); + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.h new file mode 100644 index 0000000000000000000000000000000000000000..c13b6d8467c4f18c307f42a9a485126f4617922c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/digit/netwav.h @@ -0,0 +1,56 @@ +#pragma once +#include "kmat.h" +#include "aicommon.h" +#include "wavcache.h" + + +class KWav{ + private: + float m_duration = 0; + int m_pcmsample = 0;; + int m_wavsample = 0;; + int m_seca = 0; + int m_secb = 0; + int m_mellast = 0; + int m_bnflast = 0; + int m_wavsize = 0; + int m_melsize = 0; + int m_bnfsize = 0; + int m_calcsize = 0; + int m_bnfblock = 0; + uint8_t m_alonearr[2] ; + int m_alonecnt = 0; + int m_leftsample = 0; + float *m_curwav = nullptr; + int m_waitsample = 0; + + int m_waitcnt = 0; + int m_calccnt = 0; + int m_resultcnt = 0; + + int incsample(int sample); + + KMat *m_wavmat = nullptr; + KMat *m_melmat = nullptr; + //KMat *m_bnfmat = nullptr; + MBnfCache *m_bnfcache = nullptr; + int initbuf(int pcmsample); + int initinx(); + public: + KWav(float duration,MBnfCache* bnfcache); + KWav(const char* filename,MBnfCache* bnfcache); + //KWav(const char* wavfn); + ~KWav(); + int pushpcm(uint8_t* pcm,int size); + int isready(); + int readyall(); + int isfinish(); + int finishone(int index); + int bnfblocks(); + float duration(); + int resultcnt(); + //JMat* bnfmat(); + int calcbuf(int calcinx,float** ppwav,float** ppmfcc,float** ppbnf,int* pmel,int* pbnf); + int debug(); +}; + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bb97932a8b2d077679188cc2f70a1f9c3091e305 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp.hpp @@ -0,0 +1,74 @@ +/// @section Description +/// A Templatized Header Only C++ Implementation of the Python Numpy Library +/// +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// +/// @section License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// @section Testing +/// **C++ Standards:** +/// C++14 +/// C++17 +/// C++20 +/// +/// **Compilers:** +/// Visual Studio: 2017, 2019 +/// GNU: 6.5, 7.5, 8.4, 9.3, 10.1 +/// Clang: 6, 7, 8, 9, 10 +/// +/// **Boost Versions:** +/// 1.68, 1.70, 1.72, and 1.73 +/// +#pragma once + +#include "NumCpp/Coordinates.hpp" +#include "NumCpp/Core.hpp" +#include "NumCpp/DateTime.hpp" +#include "NumCpp/Filter.hpp" +#include "NumCpp/Functions.hpp" +#include "NumCpp/ImageProcessing.hpp" +#include "NumCpp/Integrate.hpp" +#include "NumCpp/Linalg.hpp" +#include "NumCpp/Logging.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Polynomial.hpp" +#include "NumCpp/PythonInterface.hpp" +#include "NumCpp/Random.hpp" +#include "NumCpp/Roots.hpp" +#include "NumCpp/Rotations.hpp" +#include "NumCpp/Special.hpp" +#include "NumCpp/Utils.hpp" +#include "NumCpp/Vector.hpp" + +/// \example GaussNewtonNlls.cpp +/// Example for using the linalg::gaussNewtonNlls function +/// +/// \example InterfaceWithEigen.cpp +/// Example for interfaceing with Eigen Matrix +/// +/// \example InterfaceWithOpenCV.cpp +/// Example for interfaceing with OpenCV Mat +/// +/// \example ReadMe.cpp +/// Examples from the Quick Start Guide in README.md at [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates.hpp new file mode 100644 index 0000000000000000000000000000000000000000..34fb1e330f7ff480c2a171c87df38f41218ee7b9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for holding and working with coordinates +/// +#pragma once + +#include "NumCpp/Coordinates/Cartesian.hpp" +#include "NumCpp/Coordinates/Euler.hpp" +#include "NumCpp/Coordinates/Orientation.hpp" +#include "NumCpp/Coordinates/ReferenceFrames.hpp" +#include "NumCpp/Coordinates/Transforms.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Cartesian.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Cartesian.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3ece635fcba69f1c8af5b342f6373c529f456186 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Cartesian.hpp @@ -0,0 +1,322 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Cartesian Object +/// +#pragma once + +#include +#include + +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Vector/Vec2.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates +{ + /** + * @brief Cartensian coordinates + */ + class Cartesian + { + public: + double x{ 0. }; + double y{ 0. }; + double z{ 0. }; + + /** + * @brief Default Constructor + */ + Cartesian() noexcept = default; + + /** + * @brief Constructor + * + * @param inX: the x component + * @param inY: the y component + * @param inZ: the z component + */ + constexpr Cartesian(double inX, double inY, double inZ = 0.) noexcept : + x(inX), + y(inY), + z(inZ) + { + } + + /** + * @brief Default Constructor + * + * @param inCartesianVector + */ + Cartesian(const Vec2& inCartesianVector) : + x(inCartesianVector.x), + y(inCartesianVector.y) + { + } + + /** + * @brief Default Constructor + * + * @param inCartesianVector + */ + Cartesian(const Vec3& inCartesianVector) : + x(inCartesianVector.x), + y(inCartesianVector.y), + z(inCartesianVector.z) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inCartesianVector + /// + Cartesian(const NdArray& inCartesianVector) + { + if (inCartesianVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("NdArray input must be of length 3."); + } + + x = inCartesianVector[0]; + y = inCartesianVector[1]; + z = inCartesianVector[2]; + } + + /** + * @brief Copy Constructor + * + * @param other: the other Cartesian instance + */ + Cartesian(const Cartesian& other) noexcept = default; + + /** + * @brief Move Constructor + * + * @param other: the other Cartesian instance + */ + Cartesian(Cartesian&& other) noexcept = default; + + /** + * @brief Destructor + */ + virtual ~Cartesian() = default; + + /** + * @brief Copy Assignement Operator + * + * @param other: the other Cartesian instance + */ + Cartesian& operator=(const Cartesian& other) noexcept = default; + + /** + * @brief Move Assignement Operator + * + * @param other: the other Cartesian instance + */ + Cartesian& operator=(Cartesian&& other) noexcept = default; + + /** + * @brief x Unit Vector + * + * @return unit vector in x direction + */ + [[nodiscard]] static Cartesian xHat() noexcept + { + return { 1., 0., 0. }; + } + + /** + * @brief y Unit Vector + * + * @return unit vector in y direction + */ + [[nodiscard]] static Cartesian yHat() noexcept + { + return { 0., 1., 0. }; + } + + /** + * @brief z Unit Vector + * + * @return unit vector in z direction + */ + [[nodiscard]] static Cartesian zHat() noexcept + { + return { 0., 0., 1. }; + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const Cartesian& other) const noexcept + { + return utils::essentiallyEqual(x, other.x) && utils::essentiallyEqual(y, other.y) && + utils::essentiallyEqual(z, other.z); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const Cartesian& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Addition of two cartesian points + * + * @param lhs: the left hand side object + * @param rhs: the right hand side object + */ + [[nodiscard]] inline Cartesian operator+(const Cartesian& lhs, const Cartesian& rhs) noexcept + { + return { lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z }; + } + + /** + * @brief Subtraction of two cartesian points + * + * @param lhs: the left hand side object + * @param rhs: the right hand side object + */ + [[nodiscard]] inline Cartesian operator-(const Cartesian& lhs, const Cartesian& rhs) noexcept + { + return { lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z }; + } + + /** + * @brief Dot product of two cartesian points + * + * @param lhs: the left hand side object + * @param rhs: the right hand side object + */ + [[nodiscard]] inline double operator*(const Cartesian& lhs, const Cartesian& rhs) noexcept + { + return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; + } + + /** + * @brief Vector scalar multiplication + * + * @param scalar: the the scalar value + * @param vec: the cartesian vector + */ + [[nodiscard]] inline Cartesian operator*(double scalar, const Cartesian& vec) noexcept + { + return { vec.x * scalar, vec.y * scalar, vec.z * scalar }; + } + + /** + * @brief Vector scalar multiplication + * + * @param vec: the cartesian vector + * @param scalar: the the scalar value + */ + [[nodiscard]] inline Cartesian operator*(const Cartesian& vec, double scalar) noexcept + { + return scalar * vec; + } + + /** + * @brief Scalar Division a cartesian point + * + * @param vec: the cartesian vector + * @param denominator: the the scalar value + */ + [[nodiscard]] inline Cartesian operator/(const Cartesian& vec, double denominator) noexcept + { + return vec * (1.0 / denominator); + } + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param vec: the cartesian vector + */ + inline std::ostream& operator<<(std::ostream& os, const Cartesian& vec) + { + os << "Cartesian(x=" << vec.x << ", y=" << vec.y << ", z=" << vec.z << ")\n"; + return os; + } + + /** + * @brief Vector cross product + * + * @param vec1: cartesian vector + * @param vec2: cartesian vector + * @return: the vector cross product + */ + [[nodiscard]] inline Cartesian cross(const Cartesian& vec1, const Cartesian& vec2) noexcept + { + return { vec1.y * vec2.z - vec1.z * vec2.y, + -(vec1.x * vec2.z - vec1.z * vec2.x), + vec1.x * vec2.y - vec1.y * vec2.x }; + } + + /** + * @brief Vector norm + * + * @param vec: the cartesian vector + * @return: the vector norm + */ + [[nodiscard]] inline double norm(const Cartesian& vec) noexcept + { + return std::hypot(vec.x, vec.y, vec.z); + } + + /** + * @brief normalize the input vector + * + * @param vec: the cartesian vector + * @return: normalized vector + */ + [[nodiscard]] inline Cartesian normalize(const Cartesian& vec) noexcept + { + return vec / norm(vec); + } + + /** + * @brief angle between the two vectors + * + * @param vec1: cartesian vector + * @param vec2: cartesian vector + * @return unit vector in x direction + */ + [[nodiscard]] inline double angle(const Cartesian& vec1, const Cartesian& vec2) noexcept + { + return std::acos(normalize(vec1) * normalize(vec2)); + } +} // namespace nc::coordinates diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Euler.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Euler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..df2c19ee5de49fb5977a524a694cf165103c5758 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Euler.hpp @@ -0,0 +1,133 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Euler +/// +#pragma once + +#include + +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::coordinates +{ + /** + * @brief Euler + */ + class Euler + { + public: + double psi{ 0. }; + double theta{ 0. }; + double phi{ 0. }; + + /** + * @brief Default Constructor + */ + Euler() noexcept = default; + + /** + * @brief Constructor + * + * @param inPsi: the psi component + * @param inTheta: the theta component + * @param inPhi: the phi component + */ + constexpr Euler(double inPsi, double inTheta, double inPhi) noexcept : + psi(inPsi), + theta(inTheta), + phi(inPhi) + { + } + + /** + * @brief Copy Constructor + * + * @param other: the other Euler instance + */ + Euler(const Euler& other) noexcept = default; + + /** + * @brief Move Euler + * + * @param other: the other Euler instance + */ + Euler(Euler&& other) noexcept = default; + + /** + * @brief Destructor + */ + virtual ~Euler() = default; + + /** + * @brief Copy Assignement Operator + * + * @param other: the other Euler instance + */ + Euler& operator=(const Euler& other) noexcept = default; + + /** + * @brief Move Assignement Operator + * + * @param other: the other Euler instance + */ + Euler& operator=(Euler&& other) noexcept = default; + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const Euler& other) const noexcept + { + return utils::essentiallyEqual(psi, other.psi) && utils::essentiallyEqual(theta, other.theta) && + utils::essentiallyEqual(phi, other.phi); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const Euler& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param Euler: the euler angles + */ + inline std::ostream& operator<<(std::ostream& os, const Euler& Euler) + { + os << "Euler(psi=" << Euler.psi << ", theta=" << Euler.theta << ", phi=" << Euler.phi << ")\n"; + return os; + } +} // namespace nc::coordinates diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Orientation.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Orientation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fb8114f4d0f6ce7147d3297727454f6e63043a44 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Orientation.hpp @@ -0,0 +1,134 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Orientation +/// +#pragma once + +#include + +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::coordinates +{ + /** + * @brief Orientation + */ + class Orientation + { + public: + double roll{ 0. }; + double pitch{ 0. }; + double yaw{ 0. }; + + /** + * @brief Default Constructor + */ + Orientation() noexcept = default; + + /** + * @brief Constructor + * + * @param inRoll: the roll component + * @param inPitch: the pitch component + * @param inYaw: the yaw component + */ + constexpr Orientation(double inRoll, double inPitch, double inYaw) noexcept : + roll(inRoll), + pitch(inPitch), + yaw(inYaw) + { + } + + /** + * @brief Copy Constructor + * + * @param other: the other Orientation instance + */ + Orientation(const Orientation& other) noexcept = default; + + /** + * @brief Move Orientation + * + * @param other: the other Orientation instance + */ + Orientation(Orientation&& other) noexcept = default; + + /** + * @brief Destructor + */ + virtual ~Orientation() = default; + + /** + * @brief Copy Assignement Operator + * + * @param other: the other Orientation instance + */ + Orientation& operator=(const Orientation& other) noexcept = default; + + /** + * @brief Move Assignement Operator + * + * @param other: the other Orientation instance + */ + Orientation& operator=(Orientation&& other) noexcept = default; + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const Orientation& other) const noexcept + { + return utils::essentiallyEqual(roll, other.roll) && utils::essentiallyEqual(pitch, other.pitch) && + utils::essentiallyEqual(yaw, other.yaw); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const Orientation& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param orientation: the roll/pitch/yaw angles + */ + inline std::ostream& operator<<(std::ostream& os, const Orientation& orientation) + { + os << "Orientation(roll=" << orientation.roll << ", pitch=" << orientation.pitch << ", yaw=" << orientation.yaw + << ")\n"; + return os; + } +} // namespace nc::coordinates diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames.hpp new file mode 100644 index 0000000000000000000000000000000000000000..084a37d9259accd6f8be4bf81fffe5d560fc900a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames.hpp @@ -0,0 +1,37 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate reference frame functions +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/Celestial.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/AER.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/AER.hpp new file mode 100644 index 0000000000000000000000000000000000000000..90af76f249f7eb906fc8ec4d2e3e93ab4b9d6ee3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/AER.hpp @@ -0,0 +1,103 @@ + +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// AER Object +/// +#pragma once + +#include + +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief Az, El, Range coordinates + */ + + class AER + { + public: + double az{ 0. }; // radians + double el{ 0. }; // radians + double range{ 0. }; // meters + + /** + * @brief Default Constructor + */ + AER() = default; + + /** + * @brief Constructor + * @param inAz: az value in radians + * @param inEl: el value in radians + * @param inRange: the range in meters + */ + // NOTLINTNEXTLINE(bugprone-easily-swappable-parameters) + constexpr AER(double inAz, double inEl, double inRange = 1.) noexcept : + az(inAz), + el(inEl), + range(inRange) + { + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const AER& other) const noexcept + { + return utils::essentiallyEqual(az, other.az) && utils::essentiallyEqual(el, other.el) && + utils::essentiallyEqual(range, other.range); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const AER& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param point: the AER point + */ + inline std::ostream& operator<<(std::ostream& os, const AER& point) + { + os << "AER(az=" << point.az << ", el=" << point.el << ", range=" << point.range << ")\n"; + return os; + } + +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Celestial.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Celestial.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6a114c4d53cce5dc022ebc4728507c254eae9ba0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Celestial.hpp @@ -0,0 +1,736 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Celestial Object +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Coordinates/Cartesian.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates::reference_frames +{ + //================================================================================ + /// Holds a right ascension object + class RA + { + public: + //============================================================================ + /// Default Constructor + /// + RA() = default; + + //============================================================================ + /// Constructor + /// + /// @param inDegrees + /// + explicit RA(double inDegrees) : + degrees_(inDegrees), + radians_(deg2rad(inDegrees)) + { + if (inDegrees < 0 || inDegrees >= 360) + { + THROW_INVALID_ARGUMENT_ERROR("input degrees must be of the range [0, 360)"); + } + + hours_ = static_cast(std::floor(degrees_ / 15.)); + const double decMinutes = (degrees_ - static_cast(hours_) * 15.) * 4.; + minutes_ = static_cast(std::floor(decMinutes)); + seconds_ = static_cast((decMinutes - static_cast(minutes_)) * 60.); + } + + //============================================================================ + /// Constructor + /// + /// @param inHours + /// @param inMinutes + /// @param inSeconds + /// + RA(uint8 inHours, uint8 inMinutes, double inSeconds) + noexcept : + hours_(inHours), + minutes_(inMinutes), + seconds_(inSeconds) + { + degrees_ = static_cast(hours_) * 15. + static_cast(minutes_) / 4. + seconds_ / 240.; + radians_ = deg2rad(degrees_); + } + + //============================================================================ + /// Get the radians value + /// + /// @return radians + /// + [[nodiscard]] double radians() const noexcept + { + return radians_; + } + + //============================================================================ + /// Get the degrees value + /// + /// @return degrees + /// + [[nodiscard]] double degrees() const noexcept + { + return degrees_; + } + + //============================================================================ + /// Get the hour value + /// + /// @return hours + /// + [[nodiscard]] uint8 hours() const noexcept + { + return hours_; + } + + //============================================================================ + /// Get the minute value + /// + /// @return minutes + /// + [[nodiscard]] uint8 minutes() const noexcept + { + return minutes_; + } + + //============================================================================ + /// Get the seconds value + /// + /// @return seconds + /// + [[nodiscard]] double seconds() const noexcept + { + return seconds_; + } + + //============================================================================ + /// Return the RA object as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = + "RA hms: " + utils::num2str(hours_) + " hours, " + utils::num2str(minutes_) + " minutes, "; + out += utils::num2str(seconds_) + " seconds\nRA degrees: " + utils::num2str(degrees_) + '\n'; + return out; + } + + //============================================================================ + /// Prints the RA object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const RA& inRhs) const noexcept + { + return utils::essentiallyEqual(degrees_, inRhs.degrees_); + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const RA& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inRa + /// + friend std::ostream& operator<<(std::ostream& inStream, const RA& inRa) + { + inStream << inRa.str(); + return inStream; + } + + private: + //====================================Attributes============================== + uint8 hours_{ 0 }; + uint8 minutes_{ 0 }; + double seconds_{ 0. }; + double degrees_{ 0. }; + double radians_{ 0. }; + }; + + //================================================================================ + /// Holds a Declination object + class Dec + { + public: + //================================================================================ + /// Struct Enum for positive or negative Dec angle + enum class Sign + { + NEGATIVE = 0, + POSITIVE + }; + + //============================================================================ + /// Default Constructor + /// + Dec() = default; + + //============================================================================ + /// Constructor + /// + /// @param inDegrees + /// + explicit Dec(double inDegrees) : + degrees_(inDegrees), + radians_(deg2rad(inDegrees)) + { + if (inDegrees < -90 || inDegrees > 90) + { + THROW_INVALID_ARGUMENT_ERROR("input degrees must be of the range [-90, 90]"); + } + + sign_ = degrees_ < 0 ? Sign::NEGATIVE : Sign::POSITIVE; + const double absDegrees = std::abs(degrees_); + degreesWhole_ = static_cast(std::floor(absDegrees)); + + const double decMinutes = (absDegrees - static_cast(degreesWhole_)) * 60.; + minutes_ = static_cast(std::floor(decMinutes)); + seconds_ = (decMinutes - static_cast(minutes_)) * 60.; + } + + //============================================================================ + /// Constructor + /// + /// @param inSign + /// @param inDegrees + /// @param inMinutes + /// @param inSeconds + /// + Dec(Sign inSign, uint8 inDegrees, uint8 inMinutes, double inSeconds) noexcept : + sign_(inSign), + degreesWhole_(inDegrees), + minutes_(inMinutes), + seconds_(inSeconds) + { + degrees_ = static_cast(degreesWhole_) + static_cast(minutes_) / 60. + seconds_ / 3600.; + degrees_ *= sign_ == Sign::NEGATIVE ? -1 : 1; + + radians_ = deg2rad(degrees_); + } + + //============================================================================ + /// Get the sign of the degrees (positive or negative) + /// + /// @return Sign + /// + [[nodiscard]] Sign sign() const noexcept + { + return sign_; + } + + //============================================================================ + /// Get the degrees value + /// + /// @return degrees + /// + [[nodiscard]] double degrees() const noexcept + { + return degrees_; + } + + //============================================================================ + /// Get the radians value + /// + /// @return minutes + /// + [[nodiscard]] double radians() const noexcept + { + return radians_; + } + + //============================================================================ + /// Get the whole degrees value + /// + /// @return whole degrees + /// + [[nodiscard]] uint8 degreesWhole() const noexcept + { + return degreesWhole_; + } + + //============================================================================ + /// Get the minute value + /// + /// @return minutes + /// + [[nodiscard]] uint8 minutes() const noexcept + { + return minutes_; + } + + //============================================================================ + /// Get the seconds value + /// + /// @return seconds + /// + [[nodiscard]] double seconds() const noexcept + { + return seconds_; + } + + //============================================================================ + /// Return the dec object as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string strSign = sign_ == Sign::NEGATIVE ? "-" : "+"; + std::string out = "Dec dms: " + strSign + utils::num2str(degreesWhole_) + " degrees, " + + utils::num2str(minutes_) + " minutes, "; + out += utils::num2str(seconds_) + " seconds\nDec degrees = " + utils::num2str(degrees_) + '\n'; + return out; + } + + //============================================================================ + /// Prints the Dec object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const Dec& inRhs) const noexcept + { + return utils::essentiallyEqual(degrees_, inRhs.degrees_); + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const Dec& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inDec + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Dec& inDec) + { + inStream << inDec.str(); + return inStream; + } + + private: + //====================================Attributes============================== + Sign sign_{ Sign::POSITIVE }; + uint8 degreesWhole_{ 0 }; + uint8 minutes_{ 0 }; + double seconds_{ 0. }; + double degrees_{ 0. }; + double radians_{ 0. }; + }; + + //================================================================================ + /// Holds a full celestial Celestial object + class Celestial + { + public: + //============================================================================ + /// Default Constructor + /// + Celestial() = default; + + //============================================================================ + /// Constructor + /// + /// @param inRaDegrees + /// @param inDecDegrees + /// + Celestial(double inRaDegrees, double inDecDegrees) : + ra_(inRaDegrees), + dec_(inDecDegrees) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inRaHours + /// @param inRaMinutes + /// @param inRaSeconds + /// @param inSign + /// @param inDecDegreesWhole + /// @param inDecMinutes + /// @param inDecSeconds + /// + Celestial(uint8 inRaHours, + uint8 inRaMinutes, + double inRaSeconds, + Dec::Sign inSign, + uint8 inDecDegreesWhole, + uint8 inDecMinutes, + double inDecSeconds) : + ra_(inRaHours, inRaMinutes, inRaSeconds), + dec_(inSign, inDecDegreesWhole, inDecMinutes, inDecSeconds) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inRA + /// @param inDec + /// + Celestial(const RA& inRA, const Dec& inDec) noexcept : + ra_(inRA), + dec_(inDec) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inX + /// @param inY + /// @param inZ + /// + Celestial(double inX, double inY, double inZ) : + x_(inX), + y_(inY), + z_(inZ) + { + cartesianToPolar(); + } + + //============================================================================ + /// Constructor + /// + /// @param inCartesianVector + /// + Celestial(const Cartesian& inCartesianVector) : + x_(inCartesianVector.x), + y_(inCartesianVector.y), + z_(inCartesianVector.z) + { + cartesianToPolar(); + } + + //============================================================================ + /// Constructor + /// + /// @param inCartesianVector + /// + Celestial(const Vec3& inCartesianVector) : + x_(inCartesianVector.x), + y_(inCartesianVector.y), + z_(inCartesianVector.z) + { + cartesianToPolar(); + } + + //============================================================================ + /// Constructor + /// + /// @param inCartesianVector + /// + Celestial(const NdArray& inCartesianVector) + { + if (inCartesianVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("NdArray input must be of length 3."); + } + + x_ = inCartesianVector[0]; + y_ = inCartesianVector[1]; + z_ = inCartesianVector[2]; + + cartesianToPolar(); + } + + //============================================================================ + /// Returns the Dec object + /// + /// @return Dec + /// + [[nodiscard]] const Dec& dec() const noexcept + { + return dec_; + } + + //============================================================================ + /// Returns the RA object + /// + /// @return RA + /// + [[nodiscard]] const RA& ra() const noexcept + { + return ra_; + } + + //============================================================================ + /// Returns the cartesian x value + /// + /// @return x + /// + [[nodiscard]] double x() const noexcept + { + return x_; + } + + //============================================================================ + /// Returns the cartesian y value + /// + /// @return y + /// + [[nodiscard]] double y() const noexcept + { + return y_; + } + + //============================================================================ + /// Returns the cartesian z value + /// + /// @return z + /// + [[nodiscard]] double z() const noexcept + { + return z_; + } + + //============================================================================ + /// Returns the cartesian xyz triplet as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray xyz() const + { + NdArray out = { x_, y_, z_ }; + return out; + } + + //============================================================================ + /// Returns the degree seperation between the two Celestials + /// + /// @param inOtherCelestial + /// + /// @return degrees + /// + [[nodiscard]] double degreeSeperation(const Celestial& inOtherCelestial) const + { + return rad2deg(radianSeperation(inOtherCelestial)); + } + + //============================================================================ + /// Returns the degree seperation between the Celestial + /// and the input vector + /// + /// @param inVector + /// + /// @return degrees + /// + [[nodiscard]] double degreeSeperation(const NdArray& inVector) const + { + return rad2deg(radianSeperation(inVector)); + } + + //============================================================================ + /// Returns the radian seperation between the two Celestials + /// + /// @param inOtherCelestial + /// + /// @return radians + /// + [[nodiscard]] double radianSeperation(const Celestial& inOtherCelestial) const + { + return std::acos(dot(xyz(), inOtherCelestial.xyz()).item()); + } + + //============================================================================ + /// Returns the radian seperation between the Celestial + /// and the input vector + /// + /// @param inVector + /// + /// @return radians + /// + [[nodiscard]] double radianSeperation(const NdArray& inVector) const + { + if (inVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be of length 3."); + } + + return std::acos(dot(xyz(), inVector.flatten()).item()); + } + + //============================================================================ + /// Returns Celestial as a string representation + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + std::string returnStr; + returnStr = ra_.str(); + returnStr += dec_.str(); + returnStr += "Cartesian = " + xyz().str(); + return returnStr; + } + + //============================================================================ + /// Prints the Celestial object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const Celestial& inRhs) const noexcept + { + return ra_ == inRhs.ra_ && dec_ == inRhs.dec_; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const Celestial& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inCoord + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Celestial& inCoord) + { + inStream << inCoord.str(); + return inStream; + } + + private: + //====================================Attributes============================== + RA ra_{}; + Dec dec_{}; + double x_{ 1. }; + double y_{ 0. }; + double z_{ 0. }; + + //============================================================================ + /// Converts polar Celestials to cartesian Celestials + /// + void cartesianToPolar() + { + double degreesRa = rad2deg(std::atan2(y_, x_)); + if (degreesRa < 0) + { + degreesRa += 360; + } + ra_ = RA(degreesRa); + + const double r = std::sqrt(utils::sqr(x_) + utils::sqr(y_) + utils::sqr(z_)); + const double degreesDec = rad2deg(std::asin(z_ / r)); + dec_ = Dec(degreesDec); + } + + //============================================================================ + /// Converts polar Celestials to cartesian Celestials + /// + void polarToCartesian() noexcept + { + const double raRadians = deg2rad(ra_.degrees()); + const double decRadians = deg2rad(dec_.degrees()); + + x_ = std::cos(raRadians) * std::cos(decRadians); + y_ = std::sin(raRadians) * std::cos(decRadians); + z_ = std::sin(decRadians); + } + }; +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Constants.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Constants.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8c199638f98a098ece4892c22816016fb67ae246 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Constants.hpp @@ -0,0 +1,35 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Constants +/// +#pragma once + +namespace nc::coordinates::reference_frames::constants +{ + // WSG-84 + constexpr double EARTH_POLAR_RADIUS = 6'356'752.3142; + constexpr double EARTH_EQUATORIAL_RADIUS = 6'378'137.0; +} // namespace nc::coordinates::reference_frames::constants \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fc000b83ffae6b063614d337141fe10cd4c95c6b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ECEF.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// ECEF Object +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/Cartesian.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief ECEF coordinates + */ + class ECEF final : public Cartesian + { + public: + using Cartesian::Cartesian; + + /** + * @brief Constructor + * @param cartesian: cartesian vector + */ + constexpr ECEF(const Cartesian& cartesian) noexcept : + Cartesian(cartesian) + { + } + }; +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ENU.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ENU.hpp new file mode 100644 index 0000000000000000000000000000000000000000..84b6737274e2293f0d5734fb8fb0d6f170142b3d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/ENU.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// ENU Object +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/Cartesian.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief East North Up coordinates + */ + class ENU final : public Cartesian + { + public: + using Cartesian::Cartesian; + + /** + * @brief Constructor + * @param cartesian: cartesian vector + */ + constexpr ENU(const Cartesian& cartesian) noexcept : + Cartesian(cartesian) + { + } + + /** + * @brief Constructor + * @param east: east value + * @param north: north value + * @param up: up value + */ + // NOTLINTNEXTLINE(bugprone-easily-swappable-parameters) + constexpr ENU(double east, double north, double up) noexcept : + Cartesian(east, north, up) + { + } + + /** + * @brief east getter + * + * @return east + */ + [[nodiscard]] double east() const noexcept + { + return x; + } + + /** + * @brief east setter + * + * @param east: east value + */ + void setEast(double east) noexcept + { + x = east; + } + + /** + * @brief north getter + * + * @return double + */ + [[nodiscard]] double north() const noexcept + { + return y; + } + + /** + * @brief north setter + * + * @param north: north value + */ + void setNorth(double north) noexcept + { + y = north; + } + + /** + * @brief up getter + * + * @return up + */ + [[nodiscard]] double up() const noexcept + { + return z; + } + + /** + * @brief up setter + * + * @param up: up value + */ + void setUp(double up) noexcept + { + z = up; + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param point: the ENU point + */ + inline std::ostream& operator<<(std::ostream& os, const ENU& point) + { + os << "ENU(east=" << point.east() << ", north=" << point.north() << ", up=" << point.up() << ")\n"; + return os; + } +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp new file mode 100644 index 0000000000000000000000000000000000000000..41f0ec080a78f7fe794d02fe9377715ddd8402e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Geocentric Object +/// +#pragma once + +#include + +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief Geocentric coordinates + */ + class Geocentric + { + public: + double latitude{ 0. }; // radians + double longitude{ 0. }; // radians + double radius{ 0. }; // meters + + /** + * @brief Default Constructor + */ + Geocentric() = default; + + /** + * @brief Constructor + * @param inLatitude: latitude value in radians + * @param inLongitude: longitude value in radians + * @param inRadius: radius value in meters + */ + // NOTLINTNEXTLINE(bugprone-easily-swappable-parameters) + constexpr Geocentric(double inLatitude, double inLongitude, double inRadius = 0.) noexcept : + latitude(inLatitude), + longitude(inLongitude), + radius(inRadius) + { + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const Geocentric& other) const noexcept + { + return utils::essentiallyEqual(latitude, other.latitude) && + utils::essentiallyEqual(longitude, other.longitude) && utils::essentiallyEqual(radius, other.radius); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const Geocentric& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param point: the Geocentric point + */ + inline std::ostream& operator<<(std::ostream& os, const Geocentric& point) + { + os << "Geocentric(latitude=" << point.latitude << ", longitude=" << point.longitude + << ", radius=" << point.radius << ")\n"; + return os; + } +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/LLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/LLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e242a9fe40dc11a3e2727f92901def65e31824df --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/LLA.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// LLA Object +/// +#pragma once + +#include + +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief Geodetic coordinates + */ + class LLA + { + public: + double latitude{ 0. }; // radians + double longitude{ 0. }; // radians + double altitude{ 0. }; // meters + + /** + * @brief Default Constructor + */ + LLA() = default; + + /** + * @brief Constructor + * @param inLatitude: latitude value in radians + * @param inLongitude: longitude value in radians + * @param inAltitude: altitude value in meters + */ + // NOTLINTNEXTLINE(bugprone-easily-swappable-parameters) + constexpr LLA(double inLatitude, double inLongitude, double inAltitude = 0.) noexcept : + latitude(inLatitude), + longitude(inLongitude), + altitude(inAltitude) + { + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator==(const LLA& other) const noexcept + { + return utils::essentiallyEqual(latitude, other.latitude) && + utils::essentiallyEqual(longitude, other.longitude) && + utils::essentiallyEqual(altitude, other.altitude); + } + + /** + * @brief Non-Equality Operator + * + * @param other: other object + * @return bool true if not equal equal + */ + bool operator!=(const LLA& other) const noexcept + { + return !(*this == other); + } + }; + + /** + * @brief Stream operator + * + * @param os: the output stream + * @param point: the LLA point + */ + inline std::ostream& operator<<(std::ostream& os, const LLA& point) + { + os << "LLA(latitude=" << point.latitude << ", longitude=" << point.longitude << ", altitude=" << point.altitude + << ")\n"; + return os; + } +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/NED.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/NED.hpp new file mode 100644 index 0000000000000000000000000000000000000000..25d7bb9c82ad07f0e13ede99a309f073561c450b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/ReferenceFrames/NED.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NED Object +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/Cartesian.hpp" + +namespace nc::coordinates::reference_frames +{ + /** + * @brief North east down coordinates + */ + class NED final : public Cartesian + { + public: + using Cartesian::Cartesian; + + /** + * @brief Constructor + * @param cartesian: cartesian vector + */ + constexpr NED(const Cartesian& cartesian) noexcept : + Cartesian(cartesian) + { + } + + /** + * @brief Constructor + * @param north: north value + * @param east: east value + * @param down: down value + */ + // NOTLINTNEXTLINE(bugprone-easily-swappable-parameters) + constexpr NED(double north, double east, double down) noexcept : + Cartesian(north, east, down) + { + } + + /** + * @brief north getter + * + * @return north + */ + [[nodiscard]] double north() const noexcept + { + return x; + } + + /** + * @brief north setter + * + * @param north: north value + */ + void setNorth(double north) noexcept + { + x = north; + } + + /** + * @brief east getter + * + * @return double + */ + [[nodiscard]] double east() const noexcept + { + return y; + } + + /** + * @brief east setter + * + * @param east: east value + */ + void setEast(double east) noexcept + { + y = east; + } + + /** + * @brief down getter + * + * @return down + */ + [[nodiscard]] double down() const noexcept + { + return z; + } + + /** + * @brief down setter + * + * @param down: down value + */ + void setDown(double down) noexcept + { + z = down; + } + }; +} // namespace nc::coordinates::reference_frames diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c5447852377e5320e928382634a0854c4d9a05ab --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinates transformation functions +/// +#pragma once + +#include "NumCpp/Coordinates/Transforms/AERtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFEulerToENURollPitchYaw.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFEulerToNEDRollPitchYaw.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoAER.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/ENURollPitchYawToECEFEuler.hpp" +#include "NumCpp/Coordinates/Transforms/ENUUnitVecsInECEF.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoAER.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoAER.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoGeocentric.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/NEDRollPitchYawToECEFEuler.hpp" +#include "NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoAER.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/geocentricRadius.hpp" +#include "NumCpp/Coordinates/Transforms/geocentricToLLA.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f4bad26b5300231dbb110b71778e582aa509ac51 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoECEF.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (ENU). + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param target: the target position + * @param referencePoint: the reference position + * @return ECEF + */ + [[nodiscard]] inline reference_frames::ECEF AERtoECEF(const reference_frames::AER target, + const reference_frames::ECEF& referencePoint) noexcept + { + return NEDtoECEF(AERtoNED(target), referencePoint); + } + + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (ENU). + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param target: the target position + * @param referencePoint: the reference position + * @return ECEF + */ + [[nodiscard]] inline reference_frames::ECEF AERtoECEF(const reference_frames::AER target, + const reference_frames::LLA& referencePoint) noexcept + { + return AERtoECEF(target, LLAtoECEF(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoENU.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoENU.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6089bd8423b8197085d0d5a269f0d4c5956b8911 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoENU.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoENU.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (ENU). + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param aer 2D Inertial azimuth and elevation + * @return ENU + */ + [[nodiscard]] inline reference_frames::ENU AERtoENU(const reference_frames::AER aer) noexcept + { + return NEDtoENU(AERtoNED(aer)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoLLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoLLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2f842a1aab1b7fde8a122648b32ee32d572b8e9e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoLLA.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/AERtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (ENU). + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param target: the target position + * @param referencePoint: the reference position + * @return LLA + */ + [[nodiscard]] inline reference_frames::LLA AERtoLLA(const reference_frames::AER target, + const reference_frames::ECEF& referencePoint) noexcept + { + return ECEFtoLLA(AERtoECEF(target, referencePoint)); + } + + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (ENU). + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param target: the target position + * @param referencePoint: the reference position + * @return LLA + */ + [[nodiscard]] inline reference_frames::LLA AERtoLLA(const reference_frames::AER target, + const reference_frames::LLA& referencePoint) noexcept + { + return ECEFtoLLA(AERtoECEF(target, referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoNED.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoNED.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a9446d5351e20b2cd8aa45fd603e9429498e5457 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/AERtoNED.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the spherical inertial coordinates (NED) to Cartesian XYZ (NED). + * NOTE: positive elevation is defined as the negative z (up) direction + * + * @param aer: 2D Inertial azimuth and elevation + * @return NED + */ + [[nodiscard]] inline reference_frames::NED AERtoNED(const reference_frames::AER aer) noexcept + { + const auto north = aer.range * std::cos(aer.el) * std::cos(aer.az); + const auto east = aer.range * std::cos(aer.el) * std::sin(aer.az); + const auto down = aer.range * std::sin(-aer.el); + return { north, east, down }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToENURollPitchYaw.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToENURollPitchYaw.hpp new file mode 100644 index 0000000000000000000000000000000000000000..524e0363e404256ce52a531696fb022eaf0cb0fb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToENURollPitchYaw.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/Euler.hpp" +#include "NumCpp/Coordinates/Orientation.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFEulerToNEDRollPitchYaw.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts ECEF euler angles to body roll/pitch/yaw + * + * @param location: the ecef location + * @param orientation: ecef euler angles + * @return ENU Orientation + */ + [[nodiscard]] inline Orientation ECEFEulerToENURollPitchYaw(const reference_frames::ECEF& location, + const Euler& orientation) noexcept + { + const auto nedOrientation = ECEFEulerToNEDRollPitchYaw(location, orientation); + return { nedOrientation.pitch, nedOrientation.roll, -nedOrientation.yaw }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToNEDRollPitchYaw.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToNEDRollPitchYaw.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5c60f704654dc226964a53a687e0ac2a00a4835a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFEulerToNEDRollPitchYaw.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/Euler.hpp" +#include "NumCpp/Coordinates/Orientation.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp" +#include "NumCpp/Functions/wrap.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts ECEF euler angles to body roll/pitch/yaw + * + * @param location: the ecef location + * @param orientation: ecef euler angles + * @return NED Orientation + */ + [[nodiscard]] inline Orientation ECEFEulerToNEDRollPitchYaw(const reference_frames::ECEF& location, + const Euler& orientation) noexcept + { + const auto x0 = Vec3::right(); + const auto y0 = Vec3::up(); + const auto z0 = Vec3::forward(); + + // first rotation array, z0 by psi + const auto quatPsi = rotations::Quaternion{ z0, orientation.psi }; + + // rotate + const auto x1 = quatPsi * x0; + const auto y1 = quatPsi * y0; + + // second rotation array, y1 by theta + const auto quatTheta = rotations::Quaternion{ y1, orientation.theta }; + + // rotate + const auto x2 = quatTheta * x1; + const auto y2 = quatTheta * y1; + + // third rotation array, x2 by phi + const auto quatPhi = rotations::Quaternion{ x2, orientation.phi }; + + // rotate + const auto x3 = quatPhi * x2; + const auto y3 = quatPhi * y2; + + // get the local NED unit vectors wrt the ECEF coordinate system + const auto& [xHat0, yHat0, zHat0] = NEDUnitVecsInECEF(location); + + // calculate yaw and pitch + const auto yaw = std::atan2(x3.dot(yHat0), x3.dot(xHat0)); + const auto pitch = std::atan(-x3.dot(zHat0) / std::hypot(x3.dot(xHat0), x3.dot(yHat0))); + + // calculate roll + const auto yHat2 = (rotations::Quaternion{ zHat0, yaw } * yHat0); + const auto zHat2 = (rotations::Quaternion{ yHat2, pitch } * zHat0); + const auto roll = std::atan2(y3.dot(zHat2), y3.dot(yHat2)); + + return { wrap(roll), pitch, wrap(yaw) }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoAER.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoAER.hpp new file mode 100644 index 0000000000000000000000000000000000000000..28c4366be908fb970eedd0007da6cbb61c2ff9ee --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoAER.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Functions/wrap2Pi.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the LLA coordinates to Az El with geodedic up + * https://geospace-code.github.io/matmap3d/enu2aer.html + * + * @param target: the target of interest + * @param referencePoint: the referencePoint + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER ECEFtoAER(const reference_frames::ECEF& target, + const reference_frames::LLA& referencePoint) noexcept + { + const auto targetENU = ECEFtoENU(target, referencePoint); + const auto targetENUnormalizedCart = + normalize(Cartesian{ targetENU.east(), targetENU.north(), targetENU.up() }); + const auto& east = targetENUnormalizedCart.x; + const auto& north = targetENUnormalizedCart.y; + const auto& up = targetENUnormalizedCart.z; + + const auto referencePointECEF = LLAtoECEF(referencePoint); + const auto range = norm(target - referencePointECEF); + + return { wrap2Pi(std::atan2(east, north)), std::asin(up), range }; + } + + /** + * @brief Converts the LLA coordinates to Az El with geodedic up + * https://geospace-code.github.io/matmap3d/enu2aer.html + * + * @param target: the target of interest + * @param referencePoint: the referencePoint + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER ECEFtoAER(const reference_frames::ECEF& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return ECEFtoAER(target, ECEFtoLLA(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoENU.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoENU.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f2a3942b11dcd93c05e8d55050b7d63548bc75c6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoENU.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ECEF coordinates to ENU + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the reference point + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ENU ECEFtoENU(const reference_frames::ECEF& target, + const reference_frames::LLA& referencePoint) noexcept + { + const auto sinLat = std::sin(referencePoint.latitude); + const auto cosLat = std::cos(referencePoint.latitude); + const auto sinLon = std::sin(referencePoint.longitude); + const auto cosLon = std::cos(referencePoint.longitude); + + const auto referencePointECEF = LLAtoECEF(referencePoint); + + const auto x = target.x - referencePointECEF.x; + const auto y = target.y - referencePointECEF.y; + const auto z = target.z - referencePointECEF.z; + + return { -sinLon * x + cosLon * y, + -sinLat * cosLon * x - sinLat * sinLon * y + cosLat * z, + cosLat * cosLon * x + cosLat * sinLon * y + sinLat * z }; + } + + /** + * @brief Converts the ECEF coordinates to ENU + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the reference point + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ENU ECEFtoENU(const reference_frames::ECEF& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return ECEFtoENU(target, ECEFtoLLA(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..98a16591ee1d8c151339bc67f616f3126891c1ca --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp @@ -0,0 +1,86 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/sign.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts ECEF coordinates to LLA + * https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_ECEF_to_geodetic_coordinates + * + * @param ecef the point of interest + * @param tol Tolerance for the convergence of altitude (overriden if 10 iterations are processed) + * @return LLA + */ + [[nodiscard]] inline reference_frames::LLA ECEFtoLLA(const reference_frames::ECEF& ecef, double tol = 1e-8) noexcept + { + constexpr int MAX_ITER = 10; + constexpr auto E_SQR = 1. - utils::sqr(reference_frames::constants::EARTH_POLAR_RADIUS / + reference_frames::constants::EARTH_EQUATORIAL_RADIUS); + + const auto p = std::hypot(ecef.x, ecef.y); + const auto lon = std::atan2(ecef.y, ecef.x); + + double alt = 0.0; + double lat = 0.0; + + if (p < tol) + { + lat = sign(ecef.z) * constants::pi / 2.; + alt = std::abs(ecef.z) - reference_frames::constants::EARTH_POLAR_RADIUS; + } + else + { + // Iteratively update latitude and altitude. + // This is expected to converge in ~4 iterations, but apply a maximum number of iterations incase tol is + // too small + double err = 1.0; + int iter = 0; + while (err > tol && iter < MAX_ITER) + { + double N = reference_frames::constants::EARTH_EQUATORIAL_RADIUS / + std::sqrt(1 - E_SQR * utils::sqr(std::sin(lat))); + lat = std::atan((ecef.z / p) / (1 - (N * E_SQR / (N + alt)))); + double newAlt = (p / std::cos(lat)) - N; + err = std::abs(alt - newAlt); + alt = newAlt; + iter++; + } + } + return { lat, lon, alt }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoNED.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoNED.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6c80e5322a48e1aa4eb6ff5ad3411d1a569d54dd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ECEFtoNED.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoENU.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoNED.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ECEF coordinates to NED + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::NED ECEFtoNED(const reference_frames::ECEF& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ENUtoNED(ECEFtoENU(target, referencePoint)); + } + + /** + * @brief Converts the ECEF coordinates to NED + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::NED ECEFtoNED(const reference_frames::ECEF& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return ENUtoNED(ECEFtoENU(target, referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENURollPitchYawToECEFEuler.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENURollPitchYawToECEFEuler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7e1df8a68de98db9d7f4019bea7cb629c270070f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENURollPitchYawToECEFEuler.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/Euler.hpp" +#include "NumCpp/Coordinates/Orientation.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDRollPitchYawToECEFEuler.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts ENU body roll/pitch/yaw to ECEF euler angles + * + * @param location: the ecef location + * @param orientation: ned euler angles + * @return Orientation + */ + [[nodiscard]] inline Euler ENURollPitchYawToECEFEuler(const reference_frames::ECEF& location, + const Orientation& orientation) noexcept + { + const auto nedOrientation = Orientation{ orientation.pitch, orientation.roll, -orientation.yaw }; + const auto nedEuler = NEDRollPitchYawToECEFEuler(location, nedOrientation); + return { nedEuler.theta, nedEuler.psi, -nedEuler.phi }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUUnitVecsInECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUUnitVecsInECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..322ba1f7de451cea113fcbec26847f825e24ce4b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUUnitVecsInECEF.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief get the local ENU unit vectors wrt the ECEF coordinate system + * // https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates + * + * @param location: the ECEF location + * @return std::array + */ + [[nodiscard]] inline std::array ENUUnitVecsInECEF(const reference_frames::ECEF& location) noexcept + { + const auto& [xHat, yHat, zHat] = NEDUnitVecsInECEF(location); + return { yHat, xHat, -zHat }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoAER.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoAER.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c5341bf75b307586b67a18de439dfaf36f2d1375 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoAER.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoAER.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ENU coordinates to 2d speherical inertial coordinates. + * Range is not used. + * NOTE: positive elevation is defined as the positive z (up) direction + * + * @param target: coordinates to convert + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER ENUtoAER(const reference_frames::ENU& target) noexcept + { + return NEDtoAER(ENUtoNED(target)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2174a57bcc5f2479698b0c2abd7319eb9732751f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoECEF.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ENU coordinates to ECEF + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ECEF ENUtoECEF(const reference_frames::ENU& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return NEDtoECEF(ENUtoNED(target), referencePoint); + } + + /** + * @brief Converts the ENU coordinates to ECEF + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ECEF ENUtoECEF(const reference_frames::ENU& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ENUtoECEF(target, LLAtoECEF(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoLLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoLLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5d5e600ce72f5a6f5b99811f3791fd0163047076 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoLLA.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ENUtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoLLA.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ENU coordinates to LLA + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns ENU + */ + [[nodiscard]] inline reference_frames::LLA ENUtoLLA(const reference_frames::ENU& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return NEDtoLLA(ENUtoNED(target), referencePoint); + } + + /** + * @brief Converts the ENU coordinates to LLA + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns ENU + */ + [[nodiscard]] inline reference_frames::LLA ENUtoLLA(const reference_frames::ENU& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ENUtoLLA(target, LLAtoECEF(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoNED.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoNED.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1a8d6cfdf2db382a9b8315fa87116e4b4456b39b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/ENUtoNED.hpp @@ -0,0 +1,45 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts ENU to NED + * + * @param point: the ENU coordinates + * @returns NED + */ + [[nodiscard]] inline reference_frames::NED ENUtoNED(const reference_frames::ENU& point) noexcept + { + return { point.north(), point.east(), -point.up() }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoAER.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoAER.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e677dcc26a610fd86f050938f70e702035be4584 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoAER.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoAER.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the LLA coordinates to Az El with geodedic up + * https://geospace-code.github.io/matmap3d/enu2aer.html + * + * @param target: the target of interest + * @param referencePoint: the referencePoint + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER LLAtoAER(const reference_frames::LLA& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ECEFtoAER(LLAtoECEF(target), referencePoint); + } + + /** + * @brief Converts the LLA coordinates to Az El with geodedic up + * https://geospace-code.github.io/matmap3d/enu2aer.html + * + * @param target: the target of interest + * @param referencePoint: the referencePoint + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER LLAtoAER(const reference_frames::LLA& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return LLAtoAER(target, ECEFtoLLA(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..73984151eddbc82ae44b4d425f4b695429d4cd91 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoECEF.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the LLA coordinates to ECEF + * https://en.wikipedia.org/wiki/Geographic_coordinate_conversion#From_geodetic_to_ECEF_coordinates + * + * @param point: the point of interest + * @returns Cartesian + */ + [[nodiscard]] inline reference_frames::ECEF LLAtoECEF(const reference_frames::LLA& point) noexcept + { + constexpr auto B2_DIV_A2 = utils::sqr(reference_frames::constants::EARTH_POLAR_RADIUS / + reference_frames::constants::EARTH_EQUATORIAL_RADIUS); + constexpr auto E_SQR = 1. - B2_DIV_A2; + + const auto sinLat = std::sin(point.latitude); + const auto cosLat = std::cos(point.latitude); + const auto sinLon = std::sin(point.longitude); + const auto cosLon = std::cos(point.longitude); + + const auto primeVerticalMeridian = + reference_frames::constants::EARTH_EQUATORIAL_RADIUS / std::sqrt(1. - E_SQR * utils::sqr(sinLat)); + + return reference_frames::ECEF{ (primeVerticalMeridian + point.altitude) * cosLat * cosLon, + (primeVerticalMeridian + point.altitude) * cosLat * sinLon, + (B2_DIV_A2 * primeVerticalMeridian + point.altitude) * sinLat }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoENU.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoENU.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b95a59a84e6f075546980729b3878629a1a7977f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoENU.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoENU.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the ECEF coordinates to ENU + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the reference point + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ENU LLAtoENU(const reference_frames::LLA& target, + const reference_frames::LLA& referencePoint) noexcept + { + return NEDtoENU(LLAtoNED(target, referencePoint)); + } + + /** + * @brief Converts the ECEF coordinates to ENU + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the reference point + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ENU LLAtoENU(const reference_frames::LLA& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return LLAtoENU(target, ECEFtoLLA(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoGeocentric.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoGeocentric.hpp new file mode 100644 index 0000000000000000000000000000000000000000..748fe1f02a8f641c9ca7f111277a296090e4b825 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoGeocentric.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/geocentricRadius.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts from geodetic to geocentric + * + * @param point: the point of interest + * @returns geocentric + */ + [[nodiscard]] inline reference_frames::Geocentric LLAtoGeocentric(const reference_frames::LLA& point) noexcept + { + constexpr auto flatteningFactor = + (reference_frames::constants::EARTH_EQUATORIAL_RADIUS - reference_frames::constants::EARTH_POLAR_RADIUS) / + reference_frames::constants::EARTH_EQUATORIAL_RADIUS; + const auto geocentricLatitude = atan(utils::sqr(1. - flatteningFactor) * std::tan(point.latitude)); + return reference_frames::Geocentric{ geocentricLatitude, point.longitude, geocentricRadius(point) }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoNED.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoNED.hpp new file mode 100644 index 0000000000000000000000000000000000000000..028758ead75ddad624b9b9a8d039c0e34a9e9a8b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/LLAtoNED.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoNED.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the LLA coordinates to NED + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::NED LLAtoNED(const reference_frames::LLA& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ECEFtoNED(LLAtoECEF(target), referencePoint); + } + + /** + * @brief Converts the LLA coordinates to NED + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::NED LLAtoNED(const reference_frames::LLA& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return LLAtoNED(target, ECEFtoLLA(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDRollPitchYawToECEFEuler.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDRollPitchYawToECEFEuler.hpp new file mode 100644 index 0000000000000000000000000000000000000000..481721bfe46582e12f8e0c721b78617857e80f0d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDRollPitchYawToECEFEuler.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/Euler.hpp" +#include "NumCpp/Coordinates/Orientation.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp" +#include "NumCpp/Functions/wrap.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts NED body roll/pitch/yaw to ECEF euler angles + * + * @param location: the ecef location + * @param orientation: ned euler angles + * @return Orientation + */ + [[nodiscard]] inline Euler NEDRollPitchYawToECEFEuler(const reference_frames::ECEF& location, + const Orientation& orientation) noexcept + { + // get the local NED unit vectors wrt the ECEF coordinate system + const auto& [x0, y0, z0] = NEDUnitVecsInECEF(location); + + // first rotation array, z0 by yaw + const auto quatYaw = rotations::Quaternion{ z0, orientation.yaw }; + + // rotate + const auto x1 = quatYaw * x0; + const auto y1 = quatYaw * y0; + + // second rotation array, y1 by pitch + const auto quatPitch = rotations::Quaternion{ y1, orientation.pitch }; + + // rotate + const auto x2 = quatPitch * x1; + const auto y2 = quatPitch * y1; + + // third rotation array, x2 by roll + const auto quatRoll = rotations::Quaternion{ x2, orientation.roll }; + + // rotate + const auto x3 = quatRoll * x2; + const auto y3 = quatRoll * y2; + + // calculate phi and theta + const auto xHat0 = Vec3::right(); + const auto yHat0 = Vec3::up(); + const auto zHat0 = Vec3::forward(); + + const auto psi = std::atan2(x3.dot(yHat0), x3.dot(xHat0)); + const auto theta = std::atan(-x3.dot(zHat0) / std::hypot(x3.dot(xHat0), x3.dot(yHat0))); + + // calculate phi + const auto yHat2 = (rotations::Quaternion{ zHat0, psi } * yHat0); + const auto zHat2 = (rotations::Quaternion{ yHat2, theta } * zHat0); + const auto phi = std::atan2(y3.dot(zHat2), y3.dot(yHat2)); + + return { wrap(psi), theta, wrap(phi) }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e97cec185944275f412ffbf00dde5518266ff82b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDUnitVecsInECEF.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief get the local NED unit vectors wrt the ECEF coordinate system + * https://gssc.esa.int/navipedia/index.php/Transformations_between_ECEF_and_ENU_coordinates + * + * @param location: the ECEF location + * @return std::array + */ + [[nodiscard]] inline std::array NEDUnitVecsInECEF(const reference_frames::ECEF& location) noexcept + { + const auto lla = ECEFtoLLA(location); + + const auto sinLat = std::sin(lla.latitude); + const auto cosLat = std::cos(lla.latitude); + const auto sinLon = std::sin(lla.longitude); + const auto cosLon = std::cos(lla.longitude); + + const auto xHat = Vec3{ -cosLon * sinLat, -sinLon * sinLat, cosLat }; + const auto yHat = Vec3{ -sinLon, cosLon, 0. }; + const auto zHat = Vec3{ -cosLon * cosLat, -sinLon * cosLat, -sinLat }; + + return { xHat, yHat, zHat }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoAER.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoAER.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3341db69887e19e5da16ae787b531530cde3ec33 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoAER.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/AER.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" +#include "NumCpp/Functions/wrap2Pi.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the Cartesian XYZ (NED) coordinates to 2d speherical inertial coordinates. + * Range is not used. + * NOTE: positive elevation is defined as the negative z (up) direction + * + * @param target: coordinates to convert + * @returns AER + */ + [[nodiscard]] inline reference_frames::AER NEDtoAER(const reference_frames::NED& target) noexcept + { + const auto hypotXy = std::hypot(target.x, target.y); + const auto el = -std::atan2(target.z, hypotXy); + const auto az = wrap2Pi(std::atan2(target.y, target.x)); + const auto r = std::hypot(target.x, target.y); + const auto range = std::hypot(r, target.z); + return { az, el, range }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoECEF.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoECEF.hpp new file mode 100644 index 0000000000000000000000000000000000000000..91dd47a1bfb6c1c8bb3b2a6f9c75dd686b292a8d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoECEF.hpp @@ -0,0 +1,103 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/LLAtoECEF.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoECEF.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the NED coordinates to ECEF + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::ECEF NEDtoECEF(const reference_frames::NED& target, + const reference_frames::ECEF& referencePoint) noexcept + { + const auto referencePointLLA = ECEFtoLLA(referencePoint); + + const auto sinLat = std::sin(referencePointLLA.latitude); + const auto cosLat = std::cos(referencePointLLA.latitude); + const auto sinLon = std::sin(referencePointLLA.longitude); + const auto cosLon = std::cos(referencePointLLA.longitude); + + auto rotationMatrix = NdArray(3, 3); + rotationMatrix(0, 0) = -sinLat * cosLon; + rotationMatrix(1, 0) = -sinLat * sinLon; + rotationMatrix(2, 0) = cosLat; + rotationMatrix(0, 1) = -sinLon; + rotationMatrix(1, 1) = cosLon; + rotationMatrix(2, 1) = 0.; + rotationMatrix(0, 2) = -cosLat * cosLon; + rotationMatrix(1, 2) = -cosLat * sinLon; + rotationMatrix(2, 2) = -sinLat; + + auto targetVec = NdArray(3, 1); + targetVec[0] = target.north(); + targetVec[1] = target.east(); + targetVec[2] = target.down(); + + auto referencePointVec = NdArray(3, 1); + referencePointVec[0] = referencePoint.x; + referencePointVec[1] = referencePoint.y; + referencePointVec[2] = referencePoint.z; + + const auto targetECEFVec = dot(rotationMatrix, targetVec) + referencePointVec; + return { targetECEFVec[0], targetECEFVec[1], targetECEFVec[2] }; + } + + /** + * @brief Converts the NED coordinates to ECEF + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::ECEF NEDtoECEF(const reference_frames::NED& target, + const reference_frames::LLA& referencePoint) noexcept + { + return NEDtoECEF(target, LLAtoECEF(referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoENU.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoENU.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b1bce75951ba7edc7161a2844d884c1c915b2368 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoENU.hpp @@ -0,0 +1,45 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ENU.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts NED to ENU + * + * @param point: the NED coordinates + * @returns ENU + */ + [[nodiscard]] inline reference_frames::ENU NEDtoENU(const reference_frames::NED& point) noexcept + { + return { point.east(), point.north(), -point.down() }; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoLLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoLLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fdac3fb5a376775569a6ec0c3df78aee4d184001 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/NEDtoLLA.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include "NumCpp/Coordinates/ReferenceFrames/ECEF.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/NED.hpp" +#include "NumCpp/Coordinates/Transforms/ECEFtoLLA.hpp" +#include "NumCpp/Coordinates/Transforms/NEDtoECEF.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts the NED coordinates to LLA + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::LLA NEDtoLLA(const reference_frames::NED& target, + const reference_frames::ECEF& referencePoint) noexcept + { + return ECEFtoLLA(NEDtoECEF(target, referencePoint)); + } + + /** + * @brief Converts the NED coordinates to LLA + * https://apps.dtic.mil/sti/pdfs/AD1170763.pdf + * Figure 11 https://apps.dtic.mil/sti/pdfs/AD1170763.pdf for a helpful diagram + * https://en.wikipedia.org/wiki/Local_tangent_plane_coordinates + * + * @param target: the target of interest + * @param referencePoint: the referencePoint location + * @returns NED + */ + [[nodiscard]] inline reference_frames::LLA NEDtoLLA(const reference_frames::NED& target, + const reference_frames::LLA& referencePoint) noexcept + { + return ECEFtoLLA(NEDtoECEF(target, referencePoint)); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricRadius.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricRadius.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e91d0f9593fcdcd400823c9a046f9ed5f0bbe1b6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricRadius.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Returns the geocentric radius + * + * @param point: the point of interest + * @returns radius + */ + [[nodiscard]] inline double geocentricRadius(const reference_frames::LLA& point) noexcept + { + const auto cosLat = std::cos(point.latitude); + const auto sinLat = std::sin(point.latitude); + return std::sqrt((utils::sqr(utils::sqr(reference_frames::constants::EARTH_EQUATORIAL_RADIUS) * cosLat) + + utils::sqr(utils::sqr(reference_frames::constants::EARTH_POLAR_RADIUS) * sinLat)) / + (utils::sqr(reference_frames::constants::EARTH_EQUATORIAL_RADIUS * cosLat) + + utils::sqr(reference_frames::constants::EARTH_POLAR_RADIUS * sinLat))); + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricToLLA.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricToLLA.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6b24204ca692c454a247dc8890cccaeff83fcf47 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Coordinates/Transforms/geocentricToLLA.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Transforms +/// +#pragma once + +#include + +#include "NumCpp/Coordinates/ReferenceFrames/Constants.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/Geocentric.hpp" +#include "NumCpp/Coordinates/ReferenceFrames/LLA.hpp" +#include "NumCpp/Coordinates/Transforms/geocentricRadius.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates::transforms +{ + /** + * @brief Converts from geocentric to geodetic + * + * @param point: the point of interest + * @returns geodetic + */ + [[nodiscard]] inline reference_frames::LLA geocentricToLLA(const reference_frames::Geocentric& point) noexcept + { + constexpr auto flatteningFactor = + (reference_frames::constants::EARTH_EQUATORIAL_RADIUS - reference_frames::constants::EARTH_POLAR_RADIUS) / + reference_frames::constants::EARTH_EQUATORIAL_RADIUS; + + const auto geodeticLatitude = std::atan((1. / utils::sqr(1. - flatteningFactor)) * std::tan(point.latitude)); + auto geodetic = reference_frames::LLA{ geodeticLatitude, point.longitude, 0. }; + geodetic.altitude = point.radius - geocentricRadius(geodetic); + return geodetic; + } +} // namespace nc::coordinates::transforms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5ecd64b4690c58bfe6f085ec91ee6099420d8109 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core.hpp @@ -0,0 +1,37 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NumCpp Core classes, functions, and typedefs +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/DataCube.hpp" +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Version.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Timer.hpp" +#include "NumCpp/Core/Types.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Constants.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Constants.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a3736ca606d1c7cce84355d5f4e0742f549dcd2c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Constants.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds usefull constants +/// +#pragma once + +#include +#include +#include + +namespace nc::constants +{ + constexpr double c = 3.e8; ///< speed of light + constexpr double e = 2.718281828459045; ///< eulers number + constexpr double inf = std::numeric_limits::infinity(); ///< infinity + constexpr double pi = 3.141592653589793238462643383279502884; ///< Pi + constexpr double twoPi = 2. * pi; ///< 2Pi + const double nan = std::nan("1"); ///< NaN + constexpr auto j = std::complex(0, 1); // sqrt(-1) unit imaginary number + + constexpr double DAYS_PER_WEEK = 7; ///< Number of days in a week + constexpr double MINUTES_PER_HOUR = 60; ///< Number of minutes in an hour + constexpr double SECONDS_PER_MINUTE = 60; ///< Number of seconds in a minute + constexpr double MILLISECONDS_PER_SECOND = 1000; ///< Number of milliseconds in a second + constexpr double SECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE; ///< Number of seconds in an hour + constexpr double HOURS_PER_DAY = 24; ///< Number of hours in a day + constexpr double MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR; ///< Number of minutes in a day + constexpr double SECONDS_PER_DAY = MINUTES_PER_DAY * SECONDS_PER_MINUTE; ///< Number of seconds in a day + constexpr double MILLISECONDS_PER_DAY = + SECONDS_PER_DAY * MILLISECONDS_PER_SECOND; ///< Number of milliseconds in a day + constexpr double SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK; ///< Number of seconds in a week +} // namespace nc::constants diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DataCube.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DataCube.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9520c9d460c05779b2d9e285a0ce92dd3599d41f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DataCube.hpp @@ -0,0 +1,827 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Convience container for holding a uniform array of NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //================================================================================ + /// Convenience container for holding a uniform array of NdArrays + template + class DataCube + { + public: + //================================Typedefs================================== + using iterator = typename std::deque>::iterator; + using const_iterator = typename std::deque>::const_iterator; + + //============================================================================ + /// Default Constructor + /// + DataCube() = default; + + //============================================================================ + /// Constructor, preallocates to the input size + /// + /// @param inSize + /// + explicit DataCube(uint32 inSize) + { + cube_.reserve(inSize); + } + + //============================================================================ + /// Access method, with bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + NdArray& at(uint32 inIndex) + { + return cube_.at(inIndex); + } + + //============================================================================ + /// Const access method, with bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + [[nodiscard]] const NdArray& at(uint32 inIndex) const + { + return cube_.at(inIndex); + } + + //============================================================================ + /// Returns a reference to the last 2d "slice" of the cube in the z-axis + /// + /// @return NdArray& + /// + NdArray& back() noexcept + { + return cube_.back(); + } + + //============================================================================ + /// Returns an iterator to the first 2d z "slice" of the cube. + /// + /// @return iterator + /// + [[nodiscard]] iterator begin() noexcept + { + return cube_.begin(); + } + + //============================================================================ + /// Returns an const_iterator to the first 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return cube_.cbegin(); + } + + //============================================================================ + /// Returns an const_iterator to the first 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin() const noexcept + { + return cube_.cbegin(); + } + + //============================================================================ + /// Outputs the DataCube as a .bin file + /// + /// @param inFilename + /// + void dump(const std::string& inFilename) const + { + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("bin"); + } + + std::ofstream ofile(f.c_str(), std::ios::binary); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Could not open the input file:\n\t" + inFilename); + } + + for (auto& ndarray : cube_) + { + ofile.write(reinterpret_cast(ndarray.data()), ndarray.size() * sizeof(dtype)); + } + + ofile.close(); + } + + //============================================================================ + /// Tests whether or not the container is empty + /// + /// @return bool + /// + bool isempty() noexcept + { + return cube_.empty(); + } + + //============================================================================ + /// Returns an iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return iterator + /// + [[nodiscard]] iterator end() noexcept + { + return cube_.end(); + } + + //============================================================================ + /// Returns an const_iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return cube_.cend(); + } + + //============================================================================ + /// Returns an const_iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend() const noexcept + { + return cube_.cend(); + } + + //============================================================================ + /// Returns a reference to the front 2d "slice" of the cube in the z-axis + /// + /// @return NdArray& + /// + NdArray& front() noexcept + { + return cube_.front(); + } + + //============================================================================ + /// Returns the x/y shape of the cube + /// + /// @return Shape + /// + [[nodiscard]] const Shape& shape() const noexcept + { + return elementShape_; + } + + //============================================================================ + /// Returns the size of the z-axis of the cube + /// + /// @return size + /// + [[nodiscard]] uint32 sizeZ() const noexcept + { + return static_cast(cube_.size()); + } + + //============================================================================ + /// Removes the last z "slice" of the cube + /// + void pop_back() noexcept + { + cube_.pop_back(); + } + + //============================================================================ + /// Adds a new z "slice" to the end of the cube + /// + /// @param inArray + /// + void push_back(const NdArray& inArray) + { + const Shape inputShape = inArray.shape(); + + if (elementShape_.rows == 0 && elementShape_.cols == 0) + { + // initialize to the first input array size + elementShape_.rows = inputShape.rows; + elementShape_.cols = inputShape.cols; + } + + if (inputShape != elementShape_) + { + THROW_INVALID_ARGUMENT_ERROR("element arrays must all be the same shape"); + } + + cube_.push_back(inArray); + } + + //============================================================================ + /// Slices the z dimension of the cube + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inIndex) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + NdArray returnArray(1, sizeZ()); + + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray[i] = cube_[i][inIndex]; + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inIndex, Slice inSliceZ) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + NdArray returnArray(1, inSliceZ.numElements(sizeZ())); + + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray[idx++] = cube_[i][inIndex]; + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inRow, int32 inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(1, sizeZ()); + + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray[i] = cube_[i](inRow, inCol); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inRow, int32 inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(1, inSliceZ.numElements(sizeZ())); + + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray[idx++] = cube_[i](inRow, inCol); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(Slice inRow, int32 inCol) const + { + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(inRow.numElements(elementShape_.rows), sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray.put(returnArray.rSlice(), i, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(Slice inRow, int32 inCol, Slice inSliceZ) const + { + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(inRow.numElements(elementShape_.rows), inSliceZ.numElements(sizeZ())); + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray.put(returnArray.rSlice(), idx++, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inRow, Slice inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + NdArray returnArray(inCol.numElements(elementShape_.cols), sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray.put(returnArray.rSlice(), i, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inRow, Slice inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + NdArray returnArray(inCol.numElements(elementShape_.cols), inSliceZ.numElements(sizeZ())); + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray.put(returnArray.rSlice(), idx++, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return DataCube + /// + DataCube sliceZAll(Slice inRow, Slice inCol) const + { + DataCube returnCube(sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnCube.push_back(cube_[i](inRow, inCol)); + } + + return returnCube; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return DataCube + /// + DataCube sliceZ(Slice inRow, Slice inCol, Slice inSliceZ) const + { + DataCube returnCube(inSliceZ.numElements(sizeZ())); + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnCube.push_back(cube_[i](inRow, inCol)); + } + + return returnCube; + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inIndex) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + if (static_cast(inIndex) >= elementShape_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + return sliceZAll(inIndex); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inIndex, Slice inSliceZ) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + if (static_cast(inIndex) >= elementShape_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + return sliceZ(inIndex, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inRow, int32 inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inRow, int32 inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(Slice inRow, int32 inCol) const + { + auto numRows = inRow.numElements(elementShape_.rows); + if (numRows > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(Slice inRow, int32 inCol, Slice inSliceZ) const + { + auto numRows = inRow.numElements(elementShape_.rows); + if (numRows > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inRow, Slice inCol) const + { + auto numCols = inCol.numElements(elementShape_.cols); + if (numCols > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inRow, Slice inCol, Slice inSliceZ) const + { + auto numCols = inCol.numElements(elementShape_.cols); + if (numCols > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return DataCube + /// + DataCube sliceZAllat(Slice inRow, Slice inCol) const + { + if (inRow.numElements(elementShape_.rows) > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol.numElements(elementShape_.cols) > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return DataCube + /// + DataCube sliceZat(Slice inRow, Slice inCol, Slice inSliceZ) const + { + if (inRow.numElements(elementShape_.rows) > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol.numElements(elementShape_.cols) > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Access operator, no bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + NdArray& operator[](uint32 inIndex) noexcept + { + return cube_[inIndex]; + } + + //============================================================================ + /// Const access operator, no bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + const NdArray& operator[](uint32 inIndex) const noexcept + { + return cube_[inIndex]; + } + + private: + //================================Attributes================================== + std::vector> cube_{}; + Shape elementShape_{ 0, 0 }; + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DtypeInfo.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DtypeInfo.hpp new file mode 100644 index 0000000000000000000000000000000000000000..05e4116c926cde557fca4b09d9c7d0f67bfd41f3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/DtypeInfo.hpp @@ -0,0 +1,198 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds info about the dtype +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc +{ + //================================================================================ + /// Holds info about the dtype + template + class DtypeInfo + { + public: + //============================================================================ + /// For integer types: number of non-sign bits in the representation. + /// For floating types : number of digits(in radix base) in the mantissa + /// + /// @return number of bits + /// + static constexpr int bits() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::digits; + } + + //============================================================================ + /// Machine epsilon (the difference between 1 and the least + /// value greater than 1 that is representable). + /// + /// @return dtype + /// + static constexpr dtype epsilon() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::epsilon(); + } + + //============================================================================ + /// True if type is integer. + /// + /// @return bool + /// + static constexpr bool isInteger() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_integer; + } + + //============================================================================ + /// True if type is signed. + /// + /// @return bool + /// + static constexpr bool isSigned() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_signed; + } + + //============================================================================ + /// Returns the minimum value of the dtype + /// + /// @return min value + /// + static constexpr dtype min() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::min(); + } + + //============================================================================ + /// Returns the maximum value of the dtype + /// + /// @return max value + /// + static constexpr dtype max() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::max(); + } + }; + + //================================================================================ + /// Holds info about the std::complex + template + class DtypeInfo> + { + public: + //============================================================================ + /// For integer types: number of non-sign bits in the representation. + /// For floating types : number of digits(in radix base) in the mantissa + /// + /// @return number of bits + /// + static constexpr int bits() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::digits; + } + + //============================================================================ + /// Machine epsilon (the difference between 1 and the least + /// value greater than 1 that is representable). + /// + /// @return dtype + /// + static constexpr std::complex epsilon() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::epsilon(), DtypeInfo::epsilon() }; + } + + //============================================================================ + /// True if type is integer. + /// + /// @return bool + /// + static constexpr bool isInteger() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_integer; + } + + //============================================================================ + /// True if type is signed. + /// + /// @return bool + /// + static constexpr bool isSigned() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_signed; + } + + //============================================================================ + /// Returns the minimum value of the dtype + /// + /// @return min value + /// + static constexpr std::complex min() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::min(), DtypeInfo::min() }; + } + + //============================================================================ + /// Returns the maximum value of the dtype + /// + /// @return max value + /// + static constexpr std::complex max() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::max(), DtypeInfo::max() }; + } + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Endian.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Endian.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c3727697ab398dc63cb4409f38ab91f002c7ccbc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Endian.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for determining and swaping endianess +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::endian +{ + //============================================================================ + // Function Description: + /// Determines the endianess of the system + /// + /// @return bool true if the system is little endian + /// + inline bool isLittleEndian() noexcept + { + union + { + uint32 i{}; + std::array c; + } fourBytes = { 0x01020304 }; // NOLINT(cppcoreguidelines-avoid-magic-numbers) + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + return fourBytes.c[0] == 4; + } + + //============================================================================ + // Function Description: + /// Swaps the bytes of the input value + /// + /// @param value + /// @return byte swapped value + /// + template + dtype byteSwap(dtype value) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + static_assert(CHAR_BIT == 8, "CHAR_BIT != 8"); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + + union + { + dtype value; + std::array value8; + } source, dest; + + source.value = value; + + for (std::size_t k = 0; k < sizeof(dtype); ++k) + { + dest.value8[k] = source.value8[sizeof(dtype) - k - 1]; + } + + return dest.value; + } +} // namespace nc::endian diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Error.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Error.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ff9e7cea85bfb952758336c43f20020380829c76 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Error.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Standard NumCpp errors +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define THROW_INVALID_ARGUMENT_ERROR(msg) \ + nc::error::throwError(__FILE__, __func__, __LINE__, msg) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define THROW_RUNTIME_ERROR(msg) nc::error::throwError(__FILE__, __func__, __LINE__, msg) + +namespace nc::error +{ + //============================================================================ + /// Makes the full error message string + /// + /// @param file: the file + /// @param function: the function + /// @param line: the line of the file + /// @param msg: the message to throw (default "") + /// + template + void throwError(const std::string& file, const std::string& function, uint32 line, const std::string& msg = "") + { + std::string errMsg = + "File: " + file + "\n\tFunction: " + function + "\n\tLine: " + std::to_string(line) + "\n\tError: " + msg; + std::cerr << errMsg; + throw ErrorType(errMsg); + } +} // namespace nc::error diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp new file mode 100644 index 0000000000000000000000000000000000000000..94177d2b9c49a8804e2ab87f03549fe43c1b99a2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Some helper routines for checking types +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_VALID_DTYPE(dtype) \ + static_assert(nc::is_valid_dtype_v, "Template type is not a valid dtype for NdArray") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_ARITHMETIC(dtype) \ + static_assert(std::is_arithmetic_v, "Can only be used with arithmetic types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_INTEGER(dtype) static_assert(std::is_integral_v, "Can only be used with integer types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_UNSIGNED_INTEGER(dtype) \ + static_assert(std::is_integral_v && std::is_unsigned_v, "Can only be used with integer types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_FLOAT(dtype) static_assert(std::is_floating_point_v, "Can only be used with float types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_COMPLEX(dtype) static_assert(nc::is_complex_v, "Can only be used with std::complex types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype) \ + static_assert(std::is_arithmetic_v || nc::is_complex_v, \ + "Can only be used with arithmetic types or std::complex types") diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0b3eec4080684f570f49ba5699301abad5e0793c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp @@ -0,0 +1,117 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Additional operator for std::complex +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Less than operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs < rhs + /// + template + bool operator<(const std::complex& lhs, const std::complex& rhs) noexcept + { + if (!utils::essentiallyEqual(lhs.real(), rhs.real())) + { + return lhs.real() < rhs.real(); + } + + return lhs.imag() < rhs.imag(); + } + + //============================================================================ + // Method Description: + /// Less than or equal operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs <= rhs + /// + template + bool operator<=(const std::complex& lhs, const std::complex& rhs) noexcept + { + if (!utils::essentiallyEqual(lhs.real(), rhs.real())) + { + return lhs.real() <= rhs.real(); + } + + return lhs.imag() <= rhs.imag(); + } + + //============================================================================ + // Method Description: + /// Greater than operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs > rhs + /// + template + bool operator>(const std::complex& lhs, const std::complex& rhs) noexcept + { + return !(lhs <= rhs); + } + + //============================================================================ + // Method Description: + /// Greater than or equal operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs >= rhs + /// + template + bool operator>=(const std::complex& lhs, const std::complex& rhs) noexcept + { + return !(lhs < rhs); + } + + //============================================================================ + // Method Description: + /// Greater than or equal operator for std::complex + /// + /// @param value + /// @return std::complex + /// + template + std::complex complex_cast(const std::complex& value) noexcept + { + STATIC_ASSERT_ARITHMETIC(Out); + + return std::complex(static_cast(value.real()), static_cast(value.imag())); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp new file mode 100644 index 0000000000000000000000000000000000000000..944dac9737f342349c2dde4b47c5ece2a6ada772 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp @@ -0,0 +1,857 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Macro to define whether or not c++17 parallel algorithm policies are supported +/// +#pragma once + +#include +#include +#include +#include + +#if defined(__cpp_lib_parallel_algorithm) && defined(NUMCPP_USE_MULTITHREAD) +#define PARALLEL_ALGORITHMS_SUPPORTED +#define CONDITIONAL_NO_EXCEPT +#include +#else +#define CONDITIONAL_NO_EXCEPT noexcept +#endif + +namespace nc::stl_algorithms +{ + //============================================================================ + // Method Description: + /// Tests if all of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool all_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::all_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Tests if any of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool any_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::any_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Copies from one container to another + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @return OutputIt + /// + template + OutputIt copy(InputIt first, InputIt last, OutputIt destination) CONDITIONAL_NO_EXCEPT + { + return std::copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination); + } + + //============================================================================ + // Method Description: + /// Counts the values in the range + /// + /// @param first: the first iterator of container + /// @param last: the last iterator of container + /// @param value: the initial value + /// @return count + /// + template + typename std::iterator_traits::difference_type + count(InputIt first, InputIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::count( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Test if two ranges are equal + /// + /// @param first1: the first iterator of first container + /// @param last1: the last iterator of first container + /// @param first2: the first iterator of second container + /// @return bool + /// + template + bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2) CONDITIONAL_NO_EXCEPT + { + return std::equal( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2); + } + + //============================================================================ + // Method Description: + /// Test if two ranges are equal + /// + /// @param first1: the first iterator of first container + /// @param last1: the last iterator of first container + /// @param first2: the first iterator of second container + /// @param p: binary predicate to compare the elements + /// @return bool + /// + template + bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::equal( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + p); + } + + //============================================================================ + // Method Description: + /// Fills the range with the value + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param value: the function to apply to the input iterators + /// + template + void fill(ForwardIt first, ForwardIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::fill( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Returns the first element in the range [first, last) + /// that satisfies specific criteria: + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param value: the value to find + /// @return InputIt + /// + template + InputIt find(InputIt first, InputIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::find( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Runs the function on each element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param f: the function to apply to the input iterators + /// + template + void for_each(InputIt first, InputIt last, UnaryFunction f) + { + std::for_each( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + f); + } + + //============================================================================ + // Method Description: + /// Returns true if the array is sorted + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return bool true if sorted + /// + template + bool is_sorted(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::is_sorted( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns true if the array is sorted + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: comparitor function + /// @return bool true if sorted + /// + template + bool is_sorted(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::is_sorted( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Returns the maximum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return ForwordIt + /// + template + ForwardIt max_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::max_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns the maximum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return ForwordIt + /// + template + ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::max_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Returns the minimum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return ForwardIt + template + ForwardIt min_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::min_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns the minimum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return ForwordIt + /// + template + ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::min_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Runs the minimum and maximum elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return std::pair + /// + template + std::pair minmax_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::minmax_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Runs the minimum and maximum elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return std::pair + /// + template + std::pair minmax_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::minmax_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Tests if none of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool none_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::none_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Sorts up to the nth element + /// + /// @param first: the first iterator of the range + /// @param nth: the element that should be sorted + /// @param last: the last iterator of the range + /// + template + void nth_element(RandomIt first, RandomIt nth, RandomIt last) CONDITIONAL_NO_EXCEPT + { + std::nth_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + nth, + last); + } + + //============================================================================ + // Method Description: + /// Sorts up to the nth element + /// + /// @param first: the first iterator of the range + /// @param nth: the element that should be sorted + /// @param last: the last iterator of the range + /// @param comp: the comparitor function + /// + template + void nth_element(RandomIt first, RandomIt nth, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + std::nth_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + nth, + last, + comp); + } + + //============================================================================ + // Method Description: + /// replaces a value in the range with another value + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param oldValue: the value to replace + /// @param newValue: the replacement value + /// + template + void replace(ForwardIt first, ForwardIt last, const T& oldValue, const T& newValue) CONDITIONAL_NO_EXCEPT + { + std::replace( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + oldValue, + newValue); + } + + //============================================================================ + // Method Description: + /// reverses the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void reverse(BidirIt first, BidirIt last) CONDITIONAL_NO_EXCEPT + { + std::reverse( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Rotates the elements of a range + /// + /// @param first: the first iterator of the range + /// @param firstN: the element that should appear at the beginning of the rotated range + /// @param last: the last iterator of the range + /// + template + void rotate(ForwardIt first, ForwardIt firstN, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + std::rotate( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + firstN, + last); + } + + //============================================================================ + // Method Description: + /// finds the difference of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_difference(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + { + return std::set_difference( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the difference of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt set_difference(InputIt1 first1, + InputIt1 last1, + InputIt2 first2, + InputIt2 last2, + OutputIt destination, + Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::set_difference( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// finds the intersection of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + CONDITIONAL_NO_EXCEPT + { + return std::set_intersection( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the intersection of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt set_intersection(InputIt1 first1, + InputIt1 last1, + InputIt2 first2, + InputIt2 last2, + OutputIt destination, + Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::set_intersection( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// finds the union of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + CONDITIONAL_NO_EXCEPT + { + return std::set_union( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the union of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt + set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination, Compare comp) + CONDITIONAL_NO_EXCEPT + { + return std::set_union( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// Sorts the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void sort(RandomIt first, RandomIt last) CONDITIONAL_NO_EXCEPT + { + return std::sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Sorts the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// + template + void sort(RandomIt first, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Sorts the range preserving order + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void stable_sort(RandomIt first, RandomIt last) CONDITIONAL_NO_EXCEPT + { + std::stable_sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Sorts the range preserving order + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// + template + void stable_sort(RandomIt first, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + std::stable_sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Transforms the elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @param unaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt transform(InputIt first, InputIt last, OutputIt destination, UnaryOperation unaryFunction) + { + return std::transform( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination, + unaryFunction); + } + + //============================================================================ + // Method Description: + /// Transforms the elements of the range + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param destination: the first iterator of the destination + /// @param unaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt + transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt destination, BinaryOperation unaryFunction) + { + return std::transform( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + destination, + unaryFunction); + } + + //============================================================================ + // Method Description: + /// Copies the unique elements of a range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @return OutputIt + /// + template + constexpr OutputIt unique_copy(InputIt first, InputIt last, OutputIt destination) CONDITIONAL_NO_EXCEPT + { + return std::unique_copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination); + } + + //============================================================================ + // Method Description: + /// Copies the unique elements of a range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @param binaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + constexpr OutputIt unique_copy(InputIt first, InputIt last, OutputIt destination, BinaryPredicate binaryFunction) + CONDITIONAL_NO_EXCEPT + { + return std::unique_copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination, + binaryFunction); + } +} // namespace nc::stl_algorithms diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b0a59e7ed1f618bf143845d8cfb18479d1a7e8cd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp @@ -0,0 +1,206 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Some helper routines for checking types +/// +#pragma once + +#include +#include + +namespace nc +{ + //============================================================================ + // Class Description: + /// Template class for determining if all of the types are arithmetic + /// + template + struct all_arithmetic; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are arithmetic + /// + template + struct all_arithmetic + { + static constexpr bool value = std::is_arithmetic::value && all_arithmetic::value; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are arithmetic + /// + template + struct all_arithmetic + { + static constexpr bool value = std::is_arithmetic::value; + }; + + //============================================================================ + // Class Description: + /// all_arithmetic helper + /// + template + constexpr bool all_arithmetic_v = all_arithmetic::value; + + //============================================================================ + // Class Description: + /// Template class for determining if all of the types are the same as another type + /// + template + struct all_same; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are the same as another type + /// + template + struct all_same + { + static constexpr bool value = std::is_same::value && all_same::value; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are the same as another type + /// + template + struct all_same + { + static constexpr bool value = std::is_same::value; + }; + + //============================================================================ + // Class Description: + /// all_same helper + /// + template + constexpr bool all_same_v = all_same::value; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid dtype for NdArray + /// + template + struct is_valid_dtype + { + static constexpr bool value = + std::is_default_constructible::value && std::is_nothrow_copy_constructible::value && + std::is_nothrow_move_constructible::value && std::is_nothrow_copy_assignable::value && + std::is_nothrow_move_assignable::value && std::is_nothrow_destructible::value && + !std::is_void::value && !std::is_pointer::value && !std::is_array::value && + !std::is_union::value && !std::is_function::value && !std::is_abstract::value; + }; + + //============================================================================ + // Class Description: + /// is_valid_dtype helper + /// + template + constexpr bool is_valid_dtype_v = is_valid_dtype::value; + + // Forward declare + template + class NdArray; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index type for NdArray + /// + template + struct is_ndarray_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index typefor NdArray + /// + + template + struct is_ndarray_int> + { + static constexpr bool value = std::is_integral_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_int_v = is_ndarray_int::value; + + //============================================================================ + // Class Description: + /// is_ndarray_int + /// + template + using ndarray_int_concept = std::enable_if_t, int>; + + //============================================================================ + // Class Description: + /// Template class for determining if type is std::complex<> + /// + template + struct is_complex + { + static constexpr bool value = false; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if type is std::complex<> + /// + template + struct is_complex> + { + static constexpr bool value = true; + }; + + //============================================================================ + // Class Description: + /// is_complex helper + /// + template + constexpr bool is_complex_v = is_complex::value; + + //============================================================================ + // Class Description: + /// type trait to test if one value is larger than another at compile time + /// + template + struct greaterThan + { + static constexpr bool value = Value1 > Value2; + }; + + //============================================================================ + // Class Description: + /// greaterThan helper + /// + template + constexpr bool greaterThan_v = greaterThan::value; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Version.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Version.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9593633200f8c3de8bfa847bf0b8d24e13583a2d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Internal/Version.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Library version +/// +#pragma once + +namespace nc +{ + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + constexpr char VERSION[] = "2.11.0"; ///< Current NumCpp version number +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Shape.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Shape.hpp new file mode 100644 index 0000000000000000000000000000000000000000..032f93282d0bc44b0b79f55e3382238f81242f19 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Shape.hpp @@ -0,0 +1,163 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A Shape Class for NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + //================================================================================ + /// A Shape Class for NdArrays + class Shape + { + public: + //====================================Attributes============================== + uint32 rows{ 0 }; + uint32 cols{ 0 }; + + //============================================================================ + /// Constructor + /// + constexpr Shape() = default; + + //============================================================================ + /// Constructor + /// + /// @param inSquareSize + /// + constexpr explicit Shape(uint32 inSquareSize) noexcept : + rows(inSquareSize), + cols(inSquareSize) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inRows + /// @param inCols + /// + constexpr Shape(uint32 inRows, uint32 inCols) noexcept : + rows(inRows), + cols(inCols) + { + } + + //============================================================================ + /// Equality operator + /// + /// @param inOtherShape + /// + /// @return bool + /// + bool operator==(const Shape& inOtherShape) const noexcept + { + return rows == inOtherShape.rows && cols == inOtherShape.cols; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inOtherShape + /// + /// @return bool + /// + bool operator!=(const Shape& inOtherShape) const noexcept + { + return !(*this == inOtherShape); + } + + //============================================================================ + /// Returns the size of the shape + /// + /// @return size + /// + [[nodiscard]] uint32 size() const noexcept + { + return rows * cols; + } + + //============================================================================ + /// Returns whether the shape is null (constructed with the + /// default constructor). + /// + /// @return bool + /// + [[nodiscard]] bool isnull() const noexcept + { + return rows == 0 && cols == 0; + } + + //============================================================================ + /// Returns whether the shape is square or not. + /// + /// @return bool + /// + [[nodiscard]] bool issquare() const noexcept + { + return rows == cols; + } + + //============================================================================ + /// Returns the shape as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "[" + utils::num2str(rows) + ", " + utils::num2str(cols) + "]\n"; + return out; + } + + //============================================================================ + /// Prints the shape to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// IO operator for the Shape class + /// + /// @param inOStream + /// @param inShape + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Shape& inShape) + { + inOStream << inShape.str(); + return inOStream; + } + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Slice.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Slice.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a4f7a80c3d530f1c4f9856a9241776433522b8bd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Slice.hpp @@ -0,0 +1,239 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A Class for slicing into NdArrays +/// + +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + //================================================================================ + /// A Class for slicing into NdArrays + class Slice + { + public: + //====================================Attributes============================== + int32 start{ 0 }; + int32 stop{ 1 }; + int32 step{ 1 }; + + //============================================================================ + /// Constructor + /// + constexpr Slice() = default; + + //============================================================================ + /// Constructor + /// + /// @param inStop (index not included) + /// + constexpr explicit Slice(int32 inStop) noexcept : + stop(inStop) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inStart + /// @param inStop (index not included) + /// + constexpr Slice(int32 inStart, int32 inStop) noexcept : + start(inStart), + stop(inStop) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inStart + /// @param inStop (not included) + /// @param inStep + /// + constexpr Slice(int32 inStart, int32 inStop, int32 inStep) noexcept : + start(inStart), + stop(inStop), + step(inStep) + { + } + + //============================================================================ + /// Equality operator + /// + /// @param inOtherSlice + /// + /// @return bool + /// + bool operator==(const Slice& inOtherSlice) const noexcept + { + return start == inOtherSlice.start && stop == inOtherSlice.stop && step == inOtherSlice.step; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inOtherSlice + /// + /// @return bool + /// + bool operator!=(const Slice& inOtherSlice) const noexcept + { + return !(*this == inOtherSlice); + } + + //============================================================================ + /// Prints the shape to the console + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = + "[" + utils::num2str(start) + ":" + utils::num2str(stop) + ":" + utils::num2str(step) + "]\n"; + return out; + } + + //============================================================================ + /// Prints the shape to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Make the slice all positive and does some error checking + /// + /// @param inArraySize + /// + void makePositiveAndValidate(uint32 inArraySize) + { + /// convert the start value + if (start < 0) + { + start += static_cast(inArraySize); + } + if (start > static_cast(inArraySize - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid start value for array of size " + utils::num2str(inArraySize)); + } + + /// convert the stop value + if (stop < 0) + { + stop += static_cast(inArraySize); + } + if (stop > static_cast(inArraySize)) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid stop value for array of size " + utils::num2str(inArraySize)); + } + + /// do some error checking + if (start < stop) + { + if (step < 0) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid slice values [" + utils::num2str(start) + ", " + + utils::num2str(stop) + ", " + utils::num2str(step) + ']'); + } + } + + if (stop < start) + { + if (step > 0) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid slice values [" + utils::num2str(start) + ", " + + utils::num2str(stop) + ", " + utils::num2str(step) + ']'); + } + + /// otherwise flip things around for my own sanity + std::swap(start, stop); + step *= -1; + } + } + + //============================================================================ + /// Returns the number of elements that the slice contains. + /// be aware that this method will also make the slice all + /// positive! + /// + /// @param inArraySize + /// + uint32 numElements(uint32 inArraySize) + { + makePositiveAndValidate(inArraySize); + + uint32 num = 0; + for (int32 i = start; i < stop; i += step) + { + ++num; + } + return num; + } + + //============================================================================ + /// Returns the indices that coorespond to the slice + /// be aware that this method will also make the slice all + /// positive! + /// + /// @param inArrayDimSize: the size of the dimension that is being sliced + /// + std::vector toIndices(uint32 inArrayDimSize) + { + std::vector indices; + indices.reserve(numElements(inArrayDimSize)); + for (int32 i = start; i < stop; i += step) + { + indices.push_back(static_cast(i)); + } + return indices; + } + + //============================================================================ + /// IO operator for the Slice class + /// + /// @param inOStream + /// @param inSlice + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Slice& inSlice) + { + inOStream << inSlice.str(); + return inOStream; + } + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Timer.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Timer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e09c546a70b001f2d0d2122a5658acd9a03d88b7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Timer.hpp @@ -0,0 +1,162 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A timer class for timing code execution +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc +{ + //================================================================================ + /// A timer class for timing code execution + template + class Timer + { + public: + //==============================Typedefs====================================== + using ChronoClock = std::chrono::high_resolution_clock; + using TimePoint = std::chrono::time_point; + + //============================================================================ + // Method Description: + /// Constructor + /// + Timer() : + start_(ChronoClock::now()) + { + setUnits(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inName + /// + explicit Timer(const std::string& inName) : + name_(inName + " "), + start_(ChronoClock::now()) + { + setUnits(); + } + + //============================================================================ + // Method Description: + /// Sets/changes the timer name + /// + /// @param inName + /// + void setName(const std::string& inName) + { + name_ = inName + " "; + } + + //============================================================================ + // Method Description: + /// Sleeps the current thread + /// + /// @param length: the length of time to sleep + /// + void sleep(uint32 length) + { + std::this_thread::sleep_for(TimeUnit(length)); + } + + //============================================================================ + // Method Description: + /// Starts the timer + /// + void tic() noexcept + { + start_ = ChronoClock::now(); + } + + //============================================================================ + // Method Description: + /// Stops the timer + /// + /// @param printElapsedTime: bool whether or not to print the elapsed time to + /// the console + /// @return ellapsed time in specified time units + /// + TimeUnit toc(bool printElapsedTime = true) + { + const auto duration = std::chrono::duration_cast(ChronoClock::now() - start_); + + if (printElapsedTime) + { + std::cout << name_ << "Elapsed Time = " << duration.count() << unit_ << std::endl; + } + + return duration; + } + + private: + //==============================Attributes==================================== + std::string name_{ "" }; + std::string unit_{ "" }; + TimePoint start_{}; + + void setUnits() + { + if constexpr (std::is_same_v) + { + unit_ = " hours"; + } + else if constexpr (std::is_same_v) + { + unit_ = " minutes"; + } + else if constexpr (std::is_same_v) + { + unit_ = " seconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " milliseconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " microseconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " nanoseconds"; + } + else + { + unit_ = " time units of some sort"; + } + } + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Types.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Types.hpp new file mode 100644 index 0000000000000000000000000000000000000000..25d43be4305e9d7711195e66b0cf0f56dc3d067e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Core/Types.hpp @@ -0,0 +1,61 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Usefull types +/// +#pragma once + +#include + +namespace nc +{ + //====================================Typedefs==================================== + using int64 = std::int64_t; + using int32 = std::int32_t; + using int16 = std::int16_t; + using int8 = std::int8_t; + using uint64 = std::uint64_t; + using uint32 = std::uint32_t; + using uint16 = std::uint16_t; + using uint8 = std::uint8_t; + + //================================================================================ + /// Enum To describe an axis + enum class Axis + { + NONE = 0, + ROW, + COL + }; + + //================================================================================ + /// Enum for endianess + enum class Endian + { + NATIVE = 0, + BIG, + LITTLE + }; +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a0f09683c6a4849e1b54595c329b4b1b8db71b31 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NumCpp DateTime module +/// +#pragma once + +#include "NumCpp/DateTime/Clock.hpp" +#include "NumCpp/DateTime/DateTime.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/Clock.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/Clock.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9d9069a69012d01c8db5bb661169d8fd71a5708a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/Clock.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +namespace nc +{ + /** + * @brief Clock Type + */ + using Clock = std::chrono::system_clock; + + /** + * @brief Duration Type + */ + using Duration = std::chrono::nanoseconds; + + /** + * @brief TimePoint Type + */ + using TimePoint = std::chrono::time_point; + + /** + * @brief Output stream operator for the Duration type + * + * @param os: the output stream + * @param duration: the Duration + * @returns std::ostream + */ + inline std::ostream& operator<<(std::ostream& os, Duration duration) + { + os << duration.count() << " nanoseconds"; + return os; + } + + /** + * @brief Output stream operator for the TimePoint type + * + * @param os: the output stream + * @param timepoint: the TimePoint + * @returns std::ostream + */ + inline std::ostream& operator<<(std::ostream& os, const TimePoint& timepoint) + { + os << timepoint.time_since_epoch() << " nanoseconds since epoch"; + return os; + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/DateTime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/DateTime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..064c7200dc6465f5d0235734068ecd1242463634 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/DateTime/DateTime.hpp @@ -0,0 +1,578 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// DateTime module +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "boost/date_time/posix_time/posix_time.hpp" + +#include "NumCpp/DateTime/Clock.hpp" + +namespace nc +{ + //================================================================================ + // Class Description: + /// Date Time class for working with iso formatted date times + class DateTime + { + public: + static constexpr int MAX_MONTH = 12; + static constexpr int MAX_DAY = 31; + static constexpr int MAX_HOUR = 23; + static constexpr int MAX_MINUTE = 59; + static constexpr int MAX_SECOND = 59; + + //============================================================================ + // Method Description: + /// Constructor + /// + DateTime() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param tp: a timepoint object + /// + explicit DateTime(const TimePoint& tp) + { + auto tpSubSeconds = std::chrono::duration_cast(tp.time_since_epoch()); + auto fractionalSecond = static_cast(tpSubSeconds.count() % Duration::period::den) / + static_cast(Duration::period::den); + auto time = Clock::to_time_t(std::chrono::time_point_cast(tp)); + std::tm tm{}; +#ifdef _MSC_VER + gmtime_s(&tm, &time); +#else + gmtime_r(&time, &tm); +#endif + + setYear(tm.tm_year + TM_EPOCH_YEAR); + setMonth(tm.tm_mon + 1); + setDay(tm.tm_mday); + setHour(tm.tm_hour); + setMinute(tm.tm_min); + setSecond(tm.tm_sec); + setFractionalSecond(fractionalSecond); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param timestamp: an iso formatted datetime string (0001-01-01T00:00:00.00000Z) + /// + explicit DateTime(const std::string& timestamp) : + DateTime(strToTimepoint(timestamp)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + ///@param year: year value + ///@param month: month value + ///@param day: day value + ///@param hour: hour value + ///@param minute: minute value + ///@param second: second value + ///@param fractionalSecond: fractionalSecond value + /// + DateTime(int year, int month, int day, int hour, int minute, int second, double fractionalSecond = 0.0) noexcept + : + year_(year), + month_(month), + day_(day), + hour_(hour), + minute_(minute), + second_(second), + fractionalSecond_(fractionalSecond) + { + } + + //============================================================================ + // Method Description: + ///@brief year getter + /// + ///@return int + /// + [[nodiscard]] int year() const noexcept + { + return year_; + } + + //============================================================================ + // Method Description: + ///@brief year setter + /// + ///@param year: year value + /// + void setYear(int year) + { + if (year < 0) + { + throw std::invalid_argument("input year must be greater than zero"); + } + year_ = year; + } + + //============================================================================ + // Method Description: + ///@brief month getter + /// + ///@return int + /// + [[nodiscard]] int month() const noexcept + { + return month_; + } + + //============================================================================ + // Method Description: + ///@brief month setter + /// + ///@param month: month value + /// + void setMonth(int month) + { + if (month < 1) + { + throw std::invalid_argument("input month must be greater than one"); + } + if (month > MAX_MONTH) + { + throw std::invalid_argument("input month must be less than DateTime::MAX_MONTH"); + } + month_ = month; + } + + //============================================================================ + // Method Description: + ///@brief day getter + /// + ///@return int + /// + [[nodiscard]] int day() const noexcept + { + return day_; + } + + //============================================================================ + // Method Description: + ///@brief day setter + /// + ///@param day: day value + /// + void setDay(int day) + { + if (day < 1) + { + throw std::invalid_argument("input day must be greater than one"); + } + if (day > MAX_DAY) + { + throw std::invalid_argument("input day must be less than DateTime::MAX_DAY"); + } + day_ = day; + } + + //============================================================================ + // Method Description: + ///@brief hour getter + /// + ///@return int + /// + [[nodiscard]] int hour() const noexcept + { + return hour_; + } + + //============================================================================ + // Method Description: + ///@brief hour setter + /// + ///@param hour: hour value + /// + void setHour(int hour) + { + if (hour < 0) + { + throw std::invalid_argument("input hour must be greater than zero"); + } + if (hour > MAX_HOUR) + { + throw std::invalid_argument("input hour must be less than DateTime::MAX_HOUR"); + } + hour_ = hour; + } + + //============================================================================ + // Method Description: + ///@brief minute getter + /// + ///@return int + /// + [[nodiscard]] int minute() const noexcept + { + return minute_; + } + + //============================================================================ + // Method Description: + ///@brief minute setter + /// + ///@param minute: minute value + /// + void setMinute(int minute) + { + if (minute < 0) + { + throw std::invalid_argument("input minute must be greater than zero"); + } + if (minute > MAX_MINUTE) + { + throw std::invalid_argument("input minute must be less than DateTime::MAX_MINUTE"); + } + minute_ = minute; + } + + //============================================================================ + // Method Description: + ///@brief second getter + /// + ///@return int + /// + [[nodiscard]] int second() const noexcept + { + return second_; + } + + //============================================================================ + // Method Description: + ///@brief second setter + /// + ///@param second: second value + /// + void setSecond(int second) + { + if (second < 0) + { + throw std::invalid_argument("input second must be greater than zero"); + } + if (second > MAX_SECOND) + { + throw std::invalid_argument("input second must be less than DateTime::MAX_SECOND"); + } + second_ = second; + } + + //============================================================================ + // Method Description: + ///@brief fractionalSecond getter + /// + ///@return double + /// + [[nodiscard]] double fractionalSecond() const noexcept + { + return fractionalSecond_; + } + + //============================================================================ + // Method Description: + ///@brief fractionalSecond setter + /// + ///@param fractionalSecond: fractionalSecond value + /// + void setFractionalSecond(double fractionalSecond) + { + if (fractionalSecond < 0. || fractionalSecond >= 1.) + { + throw std::invalid_argument("input fractionalSecond must be in the range [0, 1)"); + } + fractionalSecond_ = fractionalSecond; + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to a TimePoint + /// + ///@returns TimePoint + /// + [[nodiscard]] TimePoint toTimePoint() const + { + std::tm t{}; + t.tm_year = year_ - TM_EPOCH_YEAR; + t.tm_mon = month_ - 1; // tm is 0 based months + t.tm_mday = day_; + t.tm_hour = hour_; + t.tm_min = minute_; + t.tm_sec = second_; + auto timePoint = Clock::from_time_t( +#ifdef _MSC_VER + _mkgmtime +#else + timegm +#endif + (&t)); + return std::chrono::time_point_cast(timePoint) + + std::chrono::nanoseconds(static_cast(fractionalSecond_ * SECONDS_TO_NANOSECONDS)); + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to an iso string + /// + ///@returns std::string + /// + [[nodiscard]] std::string toStr() const + { + const auto timePoint = toTimePoint(); + const auto timeSinceEpoch = timePoint.time_since_epoch().count(); + time_t secondsFromEpoch = timeSinceEpoch / Duration::period::den; + const auto fractionalSeconds = static_cast(timeSinceEpoch % Duration::period::den) / + static_cast(Duration::period::den); + + std::tm tm{}; +#ifdef _MSC_VER + gmtime_s(&tm, &secondsFromEpoch); +#else + gmtime_r(&secondsFromEpoch, &tm); +#endif + + std::stringstream ss; + if (fractionalSeconds > 0) + { + const auto format = "%Y-%m-%dT%H:%M:%S.%msZ"; + std::stringstream ssFractionalSecond; + ssFractionalSecond.precision(NANO_SECOND_PRECESION); + ssFractionalSecond << std::fixed << fractionalSeconds; + auto fractionalSecondStr = ssFractionalSecond.str(); + // strip of the preceding "0." and any trailing zeros + fractionalSecondStr = fractionalSecondStr.substr(2, fractionalSecondStr.size()); + fractionalSecondStr = fractionalSecondStr.substr(0, fractionalSecondStr.find_last_not_of('0') + 1); + const auto fractionalSecondsFormat = std::regex_replace(format, std::regex("%ms"), fractionalSecondStr); + ss << std::put_time(&tm, fractionalSecondsFormat.c_str()); + } + else + { + const auto format = "%Y-%m-%dT%H:%M:%SZ"; + ss << std::put_time(&tm, format); + } + + return ss.str(); + } + + //============================================================================ + // Method Description: + ///@brief Factory static method for returning a DateTime object + /// cooresponding to the system clock now. + /// + ///@returns DateTime + /// + [[nodiscard]] static DateTime now() noexcept + { + return DateTime(Clock::now()); + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to an iso string + ///@param timestamp: an iso formatted datetime string (0001-01-01T00:00:00.00000Z) + ///@returns Timepoint + /// + static TimePoint strToTimepoint(const std::string& timestamp) + { + const std::regex regexIsoTime{ R"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?Z)" }; + if (!std::regex_match(timestamp, regexIsoTime)) + { + throw std::invalid_argument("Invalid iso timestamp format"); + } + + auto convertedTime = boost::posix_time::ptime{}; + try + { + convertedTime = boost::posix_time::from_iso_extended_string(timestamp.substr(0, timestamp.size() - 1)); + } + catch (...) + { + throw std::invalid_argument("Invalid iso timestamp format"); + } + + const auto fromEpoch = convertedTime - POSIX_EPOCH; + return TimePoint{ Duration{ fromEpoch.total_nanoseconds() } }; + } + + private: + static constexpr int TM_EPOCH_YEAR = 1900; + static constexpr int POSIX_EPOCH_YEAR = 1970; + static inline const std::string POSIX_EPOCH_STR{ "1970-01-01T00:00:00" }; + static inline const boost::posix_time::ptime POSIX_EPOCH{ boost::posix_time::from_iso_extended_string( + POSIX_EPOCH_STR) }; + static constexpr double SECONDS_TO_NANOSECONDS = 1e9; + static constexpr int NANO_SECOND_PRECESION = 9; + + /// years since 1 + int year_{ POSIX_EPOCH_YEAR }; + /// [1, 12] + int month_{ 1 }; + /// [1, 31] + int day_{ 1 }; + /// [0, 23] + int hour_{ 0 }; + /// [0, 59] + int minute_{ 0 }; + /// [0, 59] + int second_{ 0 }; + /// [0, 1) + double fractionalSecond_{ 0.0 }; + }; + + //============================================================================ + // Method Description: + ///@brief Equality operator for DateTime + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator==(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() == rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Non Equality operator for DateTime + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator!=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return !(lhs == rhs); + } + + //============================================================================ + // Method Description: + ///@brief Less than operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator<(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() < rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Less than or equal operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator<=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() <= rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Greater than operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator>(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() > rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Greater than or equal operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator>=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() >= rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Subtraction operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline Duration operator-(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() - rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + /// @brief Stream operator + /// + /// @param os: the output stream + /// @param datetime: the datetime object + /// @returns ostream + /// + inline std::ostream& operator<<(std::ostream& os, const DateTime& datetime) noexcept + { + os << "DateTime:\n"; + os << "\tyear: " << datetime.year() << '\n'; + os << "\tmonth: " << datetime.month() << '\n'; + os << "\tday: " << datetime.day() << '\n'; + os << "\thour: " << datetime.hour() << '\n'; + os << "\tminute: " << datetime.minute() << '\n'; + os << "\tsecond: " << datetime.second() << '\n'; + os << "\tfractionalSecond: " << datetime.fractionalSecond() << '\n'; + return os; + } +} // namespace nc + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8c9cb0aa0f739b17f79d373426cc9ce8b8f7a489 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Image and signal filtering module +/// +#pragma once + +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/convolve1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/laplace.hpp" +#include "NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/medianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/rankFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..97bd140c8d847a88ed01e680c1e5ba01df93c735 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundaryType + /// @param inKernalSize + /// @param inConstantValue (default 0) + /// @return NdArray + /// + template + NdArray addBoundary1d(const NdArray& inImage, + Boundary inBoundaryType, + uint32 inKernalSize, + dtype inConstantValue = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inKernalSize % 2 == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input kernal size must be an odd value."); + } + + const uint32 boundarySize = inKernalSize / 2; // integer division + + switch (inBoundaryType) + { + case Boundary::REFLECT: + { + return reflect1d(inImage, boundarySize); + } + case Boundary::CONSTANT: + { + return constant1d(inImage, boundarySize, inConstantValue); + } + case Boundary::NEAREST: + { + return nearest1d(inImage, boundarySize); + } + case Boundary::MIRROR: + { + return mirror1d(inImage, boundarySize); + } + case Boundary::WRAP: + { + return wrap1d(inImage, boundarySize); + } + default: + { + // This can't actually happen but just adding to get rid of compiler warning + THROW_INVALID_ARGUMENT_ERROR("ERROR!"); + } + } + + return NdArray(); // get rid of compiler warning + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d9354273c2bdff66bf87d445fca32bbd80d92a4f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Constant boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Constant boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @param inConstantValue + /// @return NdArray + /// + template + NdArray constant1d(const NdArray& inImage, uint32 inBoundarySize, dtype inConstantValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inConstantValue); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inConstantValue); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e23c1829b9672858c63eea3d482471f7b98b5c50 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Mirror boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Mirror boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray mirror1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), fliplr(inImage[Slice(1, inBoundarySize + 1)])); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), + fliplr(inImage[Slice(-static_cast(inBoundarySize) - 1, -1)])); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5a5d1b7e493a964583ddd22306402fc0e0997652 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Nearest boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Nearest boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray nearest1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inImage.front()); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inImage.back()); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..54224577891c8ffde9761d0e54125833afadcb6f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Reflects the boundaries +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Reflects the boundaries + /// + /// @param inImage + /// @param inBoundarySize + /// + /// @return NdArray + /// + template + NdArray reflect1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), fliplr(inImage[Slice(0, inBoundarySize)])); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), + fliplr(inImage[Slice(-static_cast(inBoundarySize), inImage.size())])); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4e89d8c4058759136c559569f0857a5327f91628 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// trims the boundary off to make the image back to the original size +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// trims the boundary off to make the image back to the original size + /// + /// @param inImageWithBoundary + /// @param inSize + /// @return NdArray + /// + template + NdArray trimBoundary1d(const NdArray& inImageWithBoundary, uint32 inSize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + uint32 boundarySize = inSize / 2; // integer division + uint32 imageSize = inImageWithBoundary.size() - boundarySize * 2; + + return inImageWithBoundary[Slice(boundarySize, boundarySize + imageSize)]; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..183b4116076c7ba84b821e0b90b47ecf9f2becae --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp @@ -0,0 +1,63 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray wrap1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inImage[Slice(inImage.size() - inBoundarySize, inImage.size())]); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inImage[Slice(0, inBoundarySize)]); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1a5734caa87ff6a5cc243b7dc1e82ea7e3f4f39f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundaryType + /// @param inKernalSize + /// @param inConstantValue (default 0) + /// @return NdArray + /// + template + NdArray addBoundary2d(const NdArray& inImage, + Boundary inBoundaryType, + uint32 inKernalSize, + dtype inConstantValue = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inKernalSize % 2 == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input kernal size must be an odd value."); + } + + const uint32 boundarySize = inKernalSize / 2; // integer division + + switch (inBoundaryType) + { + case Boundary::REFLECT: + { + return reflect2d(inImage, boundarySize); + } + case Boundary::CONSTANT: + { + return constant2d(inImage, boundarySize, inConstantValue); + } + case Boundary::NEAREST: + { + return nearest2d(inImage, boundarySize); + } + case Boundary::MIRROR: + { + return mirror2d(inImage, boundarySize); + } + case Boundary::WRAP: + { + return wrap2d(inImage, boundarySize); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c1b95dfc1dc5072db75f8e484d714916290a327e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Constant boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Constant boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @param inConstantValue + /// @return NdArray + /// + template + NdArray constant2d(const NdArray& inImage, uint32 inBoundarySize, dtype inConstantValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + fillCorners(outArray, inBoundarySize, inConstantValue); + + outArray.put(Slice(0, inBoundarySize), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inConstantValue); /// bottom + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inConstantValue); /// top + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(0, inBoundarySize), + inConstantValue); /// left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + inConstantValue); /// right + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp new file mode 100644 index 0000000000000000000000000000000000000000..80775296bd47193779b359334e5b5e40009fff32 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// extends the corner values +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// extends the corner values + /// + /// @param inArray + /// @param inBorderWidth + /// + template + void fillCorners(NdArray& inArray, uint32 inBorderWidth) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + const auto numRows = static_cast(inShape.rows); + const auto numCols = static_cast(inShape.cols); + + // top left + inArray.put(Slice(0, inBorderWidth), Slice(0, inBorderWidth), inArray(inBorderWidth, inBorderWidth)); + + // top right + inArray.put(Slice(0, inBorderWidth), + Slice(numCols - inBorderWidth, numCols), + inArray(inBorderWidth, numCols - inBorderWidth - 1)); + + // bottom left + inArray.put(Slice(numRows - inBorderWidth, numRows), + Slice(0, inBorderWidth), + inArray(numRows - inBorderWidth - 1, inBorderWidth)); + + // bottom right + inArray.put(Slice(numRows - inBorderWidth, numRows), + Slice(numCols - inBorderWidth, numCols), + inArray(numRows - inBorderWidth - 1, numCols - inBorderWidth - 1)); + } + + //============================================================================ + // Method Description: + /// extends the corner values + /// + /// @param inArray + /// @param inBorderWidth + /// @param inFillValue + /// + template + void fillCorners(NdArray& inArray, uint32 inBorderWidth, dtype inFillValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + const auto numRows = static_cast(inShape.rows); + const auto numCols = static_cast(inShape.cols); + + // top left + inArray.put(Slice(0, inBorderWidth), Slice(0, inBorderWidth), inFillValue); + + // top right + inArray.put(Slice(0, inBorderWidth), Slice(numCols - inBorderWidth, numCols), inFillValue); + + // bottom left + inArray.put(Slice(numRows - inBorderWidth, numRows), Slice(0, inBorderWidth), inFillValue); + + // bottom right + inArray.put(Slice(numRows - inBorderWidth, numRows), Slice(numCols - inBorderWidth, numCols), inFillValue); + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..09131090d8e1c46d2963747d3318263b3bc88891 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp @@ -0,0 +1,109 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Mirror boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Mirror boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray mirror2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inBoundarySize - row, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - row - 2, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col, + inImage(Slice(0, inShape.rows), inBoundarySize - col)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - col - 2)); + } + + // now fill in the corners + NdArray lowerLeft = + flipud(outArray(Slice(inBoundarySize + 1, 2 * inBoundarySize + 1), Slice(0, inBoundarySize))); + NdArray lowerRight = flipud(outArray(Slice(inBoundarySize + 1, 2 * inBoundarySize + 1), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize - 1; + NdArray upperLeft = + flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize))); + NdArray upperRight = flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), lowerRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + upperRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cb9437bc4da4b419ef70dd61239674a563fda859 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Nearest boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Nearest boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray nearest2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + fillCorners(outArray, inBoundarySize); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, Slice(inBoundarySize, inBoundarySize + inShape.cols), inImage(0, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - 1, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), col, inImage(Slice(0, inShape.rows), 0)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - 1)); + } + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6d49f7bb694648becfa9bd6762cf9d90aed9f5fc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp @@ -0,0 +1,110 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Reflects the boundaries +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Reflects the boundaries + /// + /// @param inImage + /// @param inBoundarySize + /// + /// @return NdArray + /// + template + NdArray reflect2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inBoundarySize - row - 1, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - row - 1, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col, + inImage(Slice(0, inShape.rows), inBoundarySize - col - 1)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - col - 1)); + } + + // now fill in the corners + NdArray lowerLeft = + flipud(outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(0, inBoundarySize))); + NdArray lowerRight = flipud( + outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols))); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize; + NdArray upperLeft = + flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize))); + NdArray upperRight = flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), lowerRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + upperRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9091253e79015a739b7f5466b137bb25df991b91 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// trims the boundary off to make the image back to the original size +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// trims the boundary off to make the image back to the original size + /// + /// @param inImageWithBoundary + /// @param inSize + /// @return NdArray + /// + template + NdArray trimBoundary2d(const NdArray& inImageWithBoundary, uint32 inSize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + Shape inShape = inImageWithBoundary.shape(); + uint32 boundarySize = inSize / 2; /// integer division + + inShape.rows -= boundarySize * 2; + inShape.cols -= boundarySize * 2; + + return inImageWithBoundary(Slice(boundarySize, boundarySize + inShape.rows), + Slice(boundarySize, boundarySize + inShape.cols)); + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bf50dfcef40a50af5b872ad1d504cafce4cc4a65 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray wrap2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + // bottom + outArray.put(Slice(0, inBoundarySize), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(Slice(inShape.rows - inBoundarySize, inShape.rows), Slice(0, inShape.cols))); + + // top + outArray.put(Slice(inShape.rows + inBoundarySize, outShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(Slice(0, inBoundarySize), Slice(0, inShape.cols))); + + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(0, inBoundarySize), + inImage(Slice(0, inShape.rows), Slice(inShape.cols - inBoundarySize, inShape.cols))); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inShape.cols + inBoundarySize, outShape.cols), + inImage(Slice(0, inShape.rows), Slice(0, inBoundarySize))); + + // now fill in the corners + NdArray lowerLeft = outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(0, inBoundarySize)); + NdArray lowerRight = + outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols)); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize; + NdArray upperLeft = + outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize)); + NdArray upperRight = outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols)); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), upperRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + lowerRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d376c22bbcfcb69a02a333d71bb879947e1717e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp @@ -0,0 +1,43 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Boundary condition to apply to the image filter +/// +#pragma once + +namespace nc::filter +{ + //================================================================================ + // Enum Description: + /// Boundary condition to apply to the image filter + enum class Boundary + { + REFLECT = 0, + CONSTANT, + NEAREST, + MIRROR, + WRAP + }; +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..73501bcb86d0c22d277910980843df0cd7ae6c6e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate a one-dimensional complemenatry median filter. +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate a one-dimensional complemenatry median filter. + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray complementaryMedianFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray inImageArrayCopy(inImageArray); + inImageArrayCopy -= medianFilter1d(inImageArray, inSize, inBoundaryType, inConstantValue); + + return inImageArrayCopy; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..10b880e1812c4a5e855a7e41b80a795e45e26d2a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional kernel convolution. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional kernel convolution. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve1d.html#scipy.ndimage.convolve1d + /// + /// @param inImageArray + /// @param inWeights + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray convolve1d(const NdArray& inImageArray, + const NdArray& inWeights, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + const uint32 boundarySize = inWeights.size() / 2; // integer division + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inWeights.size(), inConstantValue); + NdArray output(1, inImageArray.size()); + + NdArray weightsFlat = fliplr(inWeights.flatten()); + + const uint32 endPointRow = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPointRow; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)].flatten(); + + output[i - boundarySize] = dot(window, weightsFlat).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..42ea1aba2cfab1a7b504598552e212a2343f360a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate a one-dimensional gaussian filter. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/convolve1d.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/gaussian1d.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate a one-dimensional gaussian filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generic_filter1d.html#scipy.ndimage.generic_filter1d + /// + /// @param inImageArray + /// @param inSigma: Standard deviation for Gaussian kernel + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray gaussianFilter1d(const NdArray& inImageArray, + double inSigma, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero."); + } + + // calculate the kernel size based off of the input sigma value + constexpr uint32 MIN_KERNEL_SIZE = 5; + uint32 kernelSize = + std::max(static_cast(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations + if (kernelSize % 2 == 0) + { + ++kernelSize; // make sure the kernel is an odd size + } + + const auto kernalHalfSize = static_cast(kernelSize / 2); // integer division + + // calculate the gaussian kernel + NdArray kernel(1, kernelSize); + for (double i = 0; i < kernelSize; ++i) + { + kernel[static_cast(i)] = utils::gaussian1d(i - kernalHalfSize, 0., inSigma); + } + + // normalize the kernel + kernel /= kernel.sum().item(); + + // perform the convolution + NdArray output = + convolve1d(inImageArray.template astype(), kernel, inBoundaryType, inConstantValue) + .template astype(); + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f2a97e7dc20e6bb33b891c7f31cbae49a1e0fd99 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional maximum filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional maximum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.maximum_filter1d.html#scipy.ndimage.maximum_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray maximumFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.max().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2c98894b98cc703a15847b01467c2b1e6cf9ee2c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional median filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional median filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray medianFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.median().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..07589856f49057b82941b6c27688808a14d657ae --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional minumum filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional minumum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.minimum_filter1d.html#scipy.ndimage.minimum_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray minumumFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.min().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a7b355813a5a331cfeff1d63a0e2d01759ec66b0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional percentile filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional percentile filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.percentile_filter.html#scipy.ndimage.percentile_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inPercentile: percentile [0, 100] + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray percentileFilter1d(const NdArray& inImageArray, + uint32 inSize, + double inPercentile, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = percentile(window, inPercentile).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3f60da55179fad6ef4b200db138938a1b47885e0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional rank filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional rank filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rank_filter.html#scipy.ndimage.rank_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inRank: ([0, inSize^2 - 1]) + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray rankFilter1d(const NdArray& inImageArray, + uint32 inSize, + uint8 inRank, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = sort(window)[inRank]; + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b8f7f6c2625a98c6050a03c186afbe5be7542f4b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional uniform filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional uniform filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter1d.html#scipy.ndimage.uniform_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray uniformFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = mean(window).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b6693dd709c5cee7e252074e8970f805f89cbcd7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional complemenatry median filter. +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters2d/medianFilter.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional complemenatry median filter. + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray complementaryMedianFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray inImageArrayCopy(inImageArray); + inImageArrayCopy -= medianFilter(inImageArray, inSize, inBoundaryType, inConstantValue); + + return inImageArrayCopy; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d4f15089fbdf88e46cc8c0cbe19665ea5c8cbd2a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional kernel convolution. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/rot90.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional kernel convolution. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inWeights + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray convolve(const NdArray& inImageArray, + uint32 inSize, + const NdArray& inWeights, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inWeights.size() != utils::sqr(inSize)) + { + THROW_INVALID_ARGUMENT_ERROR("input weights do no match input kernal size."); + } + + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + NdArray weightsFlat = rot90(inWeights, 2).flatten(); + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)) + .flatten(); + + output(row - boundarySize, col - boundarySize) = dot(window, weightsFlat).item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a931a155c60845aa97f035b575537073f0ef07ad --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional gaussian filter. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/gaussian.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional gaussian filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter.html#scipy.ndimage.gaussian_filter + /// + /// @param inImageArray + /// @param inSigma: Standard deviation for Gaussian kernel + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray gaussianFilter(const NdArray& inImageArray, + double inSigma, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero."); + } + + // calculate the kernel size based off of the input sigma value + constexpr uint32 MIN_KERNEL_SIZE = 5; + uint32 kernelSize = + std::max(static_cast(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations + if (kernelSize % 2 == 0) + { + ++kernelSize; // make sure the kernel is an odd size + } + + const auto kernalHalfSize = static_cast(kernelSize / 2); // integer division + + // calculate the gaussian kernel + NdArray kernel(kernelSize); + for (double row = 0; row < kernelSize; ++row) + { + for (double col = 0; col < kernelSize; ++col) + { + kernel(static_cast(row), static_cast(col)) = + utils::gaussian(row - kernalHalfSize, col - kernalHalfSize, inSigma); + } + } + + // normalize the kernel + kernel /= kernel.sum().item(); + + // perform the convolution + NdArray output = + convolve(inImageArray.template astype(), kernelSize, kernel, inBoundaryType, inConstantValue) + .template astype(); + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cb1f330b751d70053da4be5dac3ec99f9ce85051 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate the 2D laplace filter. +/// +#pragma once + +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate the 2D laplace filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.laplace.html#scipy.ndimage.laplace + /// + /// @param inImageArray + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray laplace(const NdArray& inImageArray, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray kernel = { { 0, 1, 0 }, { 1, -4, 1 }, { 0, 1, 0 } }; + return convolve(inImageArray, 3, kernel, inBoundaryType, inConstantValue); + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d62c3668079b54e8f318d4852e03bea8008e5682 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional maximum filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional maximum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.maximum_filter.html#scipy.ndimage.maximum_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray maximumFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.max().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..71e67b26045ed6e8cf8a7e8a2df0b059b570f663 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional median filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional median filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray medianFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.median().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2407a74b80ed7939b331bdf3b644ce395e833b47 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional minimum filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional minimum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.minimum_filter.html#scipy.ndimage.minimum_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray minimumFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.min().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..10ab9549b49993cce669985ef6b25ab04722caaf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional percentile filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional percentile filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.percentile_filter.html#scipy.ndimage.percentile_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inPercentile: percentile [0, 100] + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray percentileFilter(const NdArray& inImageArray, + uint32 inSize, + double inPercentile, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = + percentile(window, inPercentile, Axis::NONE, "nearest").item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..768913399b6f033a55c8d26e9196369e438a9835 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp @@ -0,0 +1,90 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional rank filter. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional rank filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rank_filter.html#scipy.ndimage.rank_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inRank: ([0, inSize^2 - 1]) + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray rankFilter(const NdArray& inImageArray, + uint32 inSize, + uint32 inRank, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inRank >= utils::sqr(inSize)) + { + THROW_INVALID_ARGUMENT_ERROR("rank not within filter footprint size."); + } + + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = sort(window)[inRank]; + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7c4293a70db8884d2e0c8dc6b19054b3ccca0900 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional uniform filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional uniform filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter.html#scipy.ndimage.uniform_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray uniformFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = mean(window).item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions.hpp new file mode 100644 index 0000000000000000000000000000000000000000..85e4ba4212a7fccf014e1118f413e55b559de7fe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions.hpp @@ -0,0 +1,291 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Methods for interacting with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/abs.hpp" +#include "NumCpp/Functions/add.hpp" +#include "NumCpp/Functions/alen.hpp" +#include "NumCpp/Functions/all.hpp" +#include "NumCpp/Functions/allclose.hpp" +#include "NumCpp/Functions/amax.hpp" +#include "NumCpp/Functions/amin.hpp" +#include "NumCpp/Functions/angle.hpp" +#include "NumCpp/Functions/any.hpp" +#include "NumCpp/Functions/append.hpp" +#include "NumCpp/Functions/applyFunction.hpp" +#include "NumCpp/Functions/applyPoly1d.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/Functions/arccos.hpp" +#include "NumCpp/Functions/arccosh.hpp" +#include "NumCpp/Functions/arcsin.hpp" +#include "NumCpp/Functions/arcsinh.hpp" +#include "NumCpp/Functions/arctan.hpp" +#include "NumCpp/Functions/arctan2.hpp" +#include "NumCpp/Functions/arctanh.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/argsort.hpp" +#include "NumCpp/Functions/argwhere.hpp" +#include "NumCpp/Functions/around.hpp" +#include "NumCpp/Functions/array_equal.hpp" +#include "NumCpp/Functions/array_equiv.hpp" +#include "NumCpp/Functions/asarray.hpp" +#include "NumCpp/Functions/astype.hpp" +#include "NumCpp/Functions/average.hpp" +#include "NumCpp/Functions/bartlett.hpp" +#include "NumCpp/Functions/binaryRepr.hpp" +#include "NumCpp/Functions/bincount.hpp" +#include "NumCpp/Functions/bit_count.hpp" +#include "NumCpp/Functions/bitwise_and.hpp" +#include "NumCpp/Functions/bitwise_not.hpp" +#include "NumCpp/Functions/bitwise_or.hpp" +#include "NumCpp/Functions/bitwise_xor.hpp" +#include "NumCpp/Functions/blackman.hpp" +#include "NumCpp/Functions/byteswap.hpp" +#include "NumCpp/Functions/cbrt.hpp" +#include "NumCpp/Functions/ceil.hpp" +#include "NumCpp/Functions/centerOfMass.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/complex.hpp" +#include "NumCpp/Functions/concatenate.hpp" +#include "NumCpp/Functions/conj.hpp" +#include "NumCpp/Functions/contains.hpp" +#include "NumCpp/Functions/copy.hpp" +#include "NumCpp/Functions/copySign.hpp" +#include "NumCpp/Functions/copyto.hpp" +#include "NumCpp/Functions/corrcoef.hpp" +#include "NumCpp/Functions/cos.hpp" +#include "NumCpp/Functions/cosh.hpp" +#include "NumCpp/Functions/count_nonzero.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Functions/cov_inv.hpp" +#include "NumCpp/Functions/cross.hpp" +#include "NumCpp/Functions/cube.hpp" +#include "NumCpp/Functions/cumprod.hpp" +#include "NumCpp/Functions/cumsum.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Functions/degrees.hpp" +#include "NumCpp/Functions/deleteIndices.hpp" +#include "NumCpp/Functions/diag.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Functions/diagonal.hpp" +#include "NumCpp/Functions/diff.hpp" +#include "NumCpp/Functions/digitize.hpp" +#include "NumCpp/Functions/divide.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/dump.hpp" +#include "NumCpp/Functions/empty.hpp" +#include "NumCpp/Functions/empty_like.hpp" +#include "NumCpp/Functions/endianess.hpp" +#include "NumCpp/Functions/equal.hpp" +#include "NumCpp/Functions/exp.hpp" +#include "NumCpp/Functions/exp2.hpp" +#include "NumCpp/Functions/expm1.hpp" +#include "NumCpp/Functions/extract.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/fillDiagnol.hpp" +#include "NumCpp/Functions/find.hpp" +#include "NumCpp/Functions/fix.hpp" +#include "NumCpp/Functions/flatnonzero.hpp" +#include "NumCpp/Functions/flatten.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/Functions/floor.hpp" +#include "NumCpp/Functions/floor_divide.hpp" +#include "NumCpp/Functions/fmax.hpp" +#include "NumCpp/Functions/fmin.hpp" +#include "NumCpp/Functions/fmod.hpp" +#include "NumCpp/Functions/frombuffer.hpp" +#include "NumCpp/Functions/fromfile.hpp" +#include "NumCpp/Functions/fromfunction.hpp" +#include "NumCpp/Functions/fromiter.hpp" +#include "NumCpp/Functions/fromstring.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/Functions/full_like.hpp" +#include "NumCpp/Functions/gcd.hpp" +#include "NumCpp/Functions/geomspace.hpp" +#include "NumCpp/Functions/gradient.hpp" +#include "NumCpp/Functions/greater.hpp" +#include "NumCpp/Functions/greater_equal.hpp" +#include "NumCpp/Functions/hamming.hpp" +#include "NumCpp/Functions/hammingEncode.hpp" +#include "NumCpp/Functions/hanning.hpp" +#include "NumCpp/Functions/histogram.hpp" +#include "NumCpp/Functions/hsplit.hpp" +#include "NumCpp/Functions/hstack.hpp" +#include "NumCpp/Functions/hypot.hpp" +#include "NumCpp/Functions/identity.hpp" +#include "NumCpp/Functions/imag.hpp" +#include "NumCpp/Functions/inner.hpp" +#include "NumCpp/Functions/insert.hpp" +#include "NumCpp/Functions/interp.hpp" +#include "NumCpp/Functions/intersect1d.hpp" +#include "NumCpp/Functions/invert.hpp" +#include "NumCpp/Functions/isclose.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/Functions/isneginf.hpp" +#include "NumCpp/Functions/isposinf.hpp" +#include "NumCpp/Functions/kaiser.hpp" +#include "NumCpp/Functions/lcm.hpp" +#include "NumCpp/Functions/ldexp.hpp" +#include "NumCpp/Functions/left_shift.hpp" +#include "NumCpp/Functions/less.hpp" +#include "NumCpp/Functions/less_equal.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/Functions/load.hpp" +#include "NumCpp/Functions/log.hpp" +#include "NumCpp/Functions/log10.hpp" +#include "NumCpp/Functions/log1p.hpp" +#include "NumCpp/Functions/log2.hpp" +#include "NumCpp/Functions/logaddexp.hpp" +#include "NumCpp/Functions/logaddexp2.hpp" +#include "NumCpp/Functions/logb.hpp" +#include "NumCpp/Functions/logical_and.hpp" +#include "NumCpp/Functions/logical_not.hpp" +#include "NumCpp/Functions/logical_or.hpp" +#include "NumCpp/Functions/logical_xor.hpp" +#include "NumCpp/Functions/logspace.hpp" +#include "NumCpp/Functions/matmul.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/Functions/maximum.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/Functions/median.hpp" +#include "NumCpp/Functions/meshgrid.hpp" +#include "NumCpp/Functions/min.hpp" +#include "NumCpp/Functions/minimum.hpp" +#include "NumCpp/Functions/mod.hpp" +#include "NumCpp/Functions/multiply.hpp" +#include "NumCpp/Functions/nan_to_num.hpp" +#include "NumCpp/Functions/nanargmax.hpp" +#include "NumCpp/Functions/nanargmin.hpp" +#include "NumCpp/Functions/nancumprod.hpp" +#include "NumCpp/Functions/nancumsum.hpp" +#include "NumCpp/Functions/nanmax.hpp" +#include "NumCpp/Functions/nanmean.hpp" +#include "NumCpp/Functions/nanmedian.hpp" +#include "NumCpp/Functions/nanmin.hpp" +#include "NumCpp/Functions/nanpercentile.hpp" +#include "NumCpp/Functions/nanprod.hpp" +#include "NumCpp/Functions/nans.hpp" +#include "NumCpp/Functions/nans_like.hpp" +#include "NumCpp/Functions/nanstdev.hpp" +#include "NumCpp/Functions/nansum.hpp" +#include "NumCpp/Functions/nanvar.hpp" +#include "NumCpp/Functions/nbytes.hpp" +#include "NumCpp/Functions/negative.hpp" +#include "NumCpp/Functions/newbyteorder.hpp" +#include "NumCpp/Functions/none.hpp" +#include "NumCpp/Functions/nonzero.hpp" +#include "NumCpp/Functions/norm.hpp" +#include "NumCpp/Functions/normalize.hpp" +#include "NumCpp/Functions/not_equal.hpp" +#include "NumCpp/Functions/nth_root.hpp" +#include "NumCpp/Functions/ones.hpp" +#include "NumCpp/Functions/ones_like.hpp" +#include "NumCpp/Functions/outer.hpp" +#include "NumCpp/Functions/packbits.hpp" +#include "NumCpp/Functions/pad.hpp" +#include "NumCpp/Functions/partition.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/Functions/place.hpp" +#include "NumCpp/Functions/polar.hpp" +#include "NumCpp/Functions/power.hpp" +#include "NumCpp/Functions/powerf.hpp" +#include "NumCpp/Functions/print.hpp" +#include "NumCpp/Functions/prod.hpp" +#include "NumCpp/Functions/proj.hpp" +#include "NumCpp/Functions/ptp.hpp" +#include "NumCpp/Functions/put.hpp" +#include "NumCpp/Functions/putmask.hpp" +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/Functions/radians.hpp" +#include "NumCpp/Functions/ravel.hpp" +#include "NumCpp/Functions/real.hpp" +#include "NumCpp/Functions/reciprocal.hpp" +#include "NumCpp/Functions/remainder.hpp" +#include "NumCpp/Functions/repeat.hpp" +#include "NumCpp/Functions/replace.hpp" +#include "NumCpp/Functions/reshape.hpp" +#include "NumCpp/Functions/resizeFast.hpp" +#include "NumCpp/Functions/resizeSlow.hpp" +#include "NumCpp/Functions/right_shift.hpp" +#include "NumCpp/Functions/rint.hpp" +#include "NumCpp/Functions/rms.hpp" +#include "NumCpp/Functions/roll.hpp" +#include "NumCpp/Functions/rot90.hpp" +#include "NumCpp/Functions/round.hpp" +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/Functions/select.hpp" +#include "NumCpp/Functions/setdiff1d.hpp" +#include "NumCpp/Functions/shape.hpp" +#include "NumCpp/Functions/sign.hpp" +#include "NumCpp/Functions/signbit.hpp" +#include "NumCpp/Functions/sin.hpp" +#include "NumCpp/Functions/sinc.hpp" +#include "NumCpp/Functions/sinh.hpp" +#include "NumCpp/Functions/size.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/Functions/split.hpp" +#include "NumCpp/Functions/sqrt.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/Functions/stack.hpp" +#include "NumCpp/Functions/stdev.hpp" +#include "NumCpp/Functions/subtract.hpp" +#include "NumCpp/Functions/sum.hpp" +#include "NumCpp/Functions/swap.hpp" +#include "NumCpp/Functions/swapCols.hpp" +#include "NumCpp/Functions/swapRows.hpp" +#include "NumCpp/Functions/swapaxes.hpp" +#include "NumCpp/Functions/take.hpp" +#include "NumCpp/Functions/tan.hpp" +#include "NumCpp/Functions/tanh.hpp" +#include "NumCpp/Functions/tile.hpp" +#include "NumCpp/Functions/toStlVector.hpp" +#include "NumCpp/Functions/tofile.hpp" +#include "NumCpp/Functions/trace.hpp" +#include "NumCpp/Functions/transpose.hpp" +#include "NumCpp/Functions/trapz.hpp" +#include "NumCpp/Functions/tri.hpp" +#include "NumCpp/Functions/trim_zeros.hpp" +#include "NumCpp/Functions/trunc.hpp" +#include "NumCpp/Functions/union1d.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/Functions/unpackbits.hpp" +#include "NumCpp/Functions/unwrap.hpp" +#include "NumCpp/Functions/vander.hpp" +#include "NumCpp/Functions/var.hpp" +#include "NumCpp/Functions/vsplit.hpp" +#include "NumCpp/Functions/vstack.hpp" +#include "NumCpp/Functions/where.hpp" +#include "NumCpp/Functions/wrap.hpp" +#include "NumCpp/Functions/wrap2Pi.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Functions/zeros_like.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/abs.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/abs.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fab0a8ccdb761e0ac49d5efdf8a3b5f2d3f8c51d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/abs.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the absolute value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.absolute.html + /// + /// @param inValue + /// @return value + /// + template + auto abs(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::abs(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the absolute value element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.absolute.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto abs(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return nc::abs(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/add.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/add.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fcd742c9a1ae08cedfb98bbd2b88af8a46388a66 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/add.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray add(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray add(const NdArray& inArray, dtype value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray add(dtype value, const NdArray& inArray) + { + return value + inArray; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> add(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> add(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> add(const NdArray& inArray, const std::complex& value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> add(const std::complex& value, const NdArray& inArray) + { + return value + inArray; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> add(const NdArray>& inArray, dtype value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> add(dtype value, const NdArray>& inArray) + { + return value + inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/alen.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/alen.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4cc8c69cccd85fe741f2d1dfeba9aa217a71c7ae --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/alen.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the length of the first dimension of the input array. + /// + /// @param inArray + /// @return length uint16 + /// + template + uint32 alen(const NdArray& inArray) noexcept + { + return inArray.shape().rows; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/all.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/all.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6245d32c12531e02d7a246eda225e9aad2fa03f5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/all.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether all array elements along a given axis evaluate to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.all.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray all(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.all(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/allclose.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/allclose.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0bb3409e921c58cb39bd675e0c29dd3a96de7380 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/allclose.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/abs.hpp" +#include "NumCpp/Functions/all.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns True if two arrays are element-wise equal within a tolerance. + /// inTolerance must be a positive number + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.allclose.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inTolerance: (Optional, default 1e-5) + /// @return bool + /// + template + bool allclose(const NdArray& inArray1, const NdArray& inArray2, double inTolerance = 1e-5) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array dimensions are not consistant."); + } + + for (uint32 i = 0; i < inArray1.size(); ++i) + { + if (std::abs(inArray1[i] - inArray2[i]) > inTolerance) + { + return false; + } + } + + return true; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b4d9dc74ef853fa3c5c3c250a2dd18d72b0f5613 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amax.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.amax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return max value + /// + template + NdArray amax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.max(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4b0980e86415a27580c16b531013e513eaeb80d4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/amin.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or minimum along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.amin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return min value + /// + template + NdArray amin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.min(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/angle.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/angle.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f42d3cb9df039ab442aef2fbf9b8b6d4693bba2a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/angle.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the angle of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.angle.html + /// + /// @param inValue + /// @return value + /// + template + auto angle(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::arg(inValue); + } + + //============================================================================ + // Method Description: + /// Return the angle of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.angle.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto angle(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return angle(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/any.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/any.hpp new file mode 100644 index 0000000000000000000000000000000000000000..699b9c5825f0fa82e87d27ff02a08a16ad556fb0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/any.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether any array element along a given axis evaluates to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.any.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray any(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.any(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/append.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/append.hpp new file mode 100644 index 0000000000000000000000000000000000000000..421ab2ccfcc5b0b85e7f587d7314a3f33aee54c5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/append.hpp @@ -0,0 +1,122 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Append values to the end of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.append.html + /// + /// @param inArray + /// @param inAppendValues + /// @param inAxis (Optional, default NONE): The axis along which values are appended. + /// If axis is not given, both inArray and inAppendValues + /// are flattened before use. + /// @return NdArray + /// + template + NdArray append(const NdArray& inArray, const NdArray& inAppendValues, Axis inAxis = Axis::NONE) + { + if (inArray.shape().isnull()) + { + return inAppendValues; + } + else if (inAppendValues.shape().isnull()) + { + return inArray; + } + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray(1, inArray.size() + inAppendValues.size()); + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), returnArray.begin()); + stl_algorithms::copy(inAppendValues.cbegin(), + inAppendValues.cend(), + returnArray.begin() + inArray.size()); + + return returnArray; + } + case Axis::ROW: + { + const Shape inShape = inArray.shape(); + const Shape appendShape = inAppendValues.shape(); + if (inShape.cols != appendShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR( + "all the input array dimensions except for the concatenation axis must match exactly"); + } + + NdArray returnArray(inShape.rows + appendShape.rows, inShape.cols); + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), returnArray.begin()); + stl_algorithms::copy(inAppendValues.cbegin(), + inAppendValues.cend(), + returnArray.begin() + inArray.size()); + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + const Shape appendShape = inAppendValues.shape(); + if (inShape.rows != appendShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR( + "all the input array dimensions except for the concatenation axis must match exactly"); + } + + NdArray returnArray(inShape.rows, inShape.cols + appendShape.cols); + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + stl_algorithms::copy(inArray.cbegin(row), inArray.cend(row), returnArray.begin(row)); + stl_algorithms::copy(inAppendValues.cbegin(row), + inAppendValues.cend(row), + returnArray.begin(row) + inShape.cols); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyFunction.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyFunction.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0bf16c4a75f3f3b3022c13a9e2d5df0bb3e9d893 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyFunction.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Apply the input function element wise to the input + /// array in place. + /// + /// @param inArray + /// @param inFunc + /// @return NdArray + /// + template + void applyFunction(NdArray& inArray, const std::function& inFunc) + { + stl_algorithms::transform(inArray.begin(), inArray.end(), inArray.begin(), inFunc); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyPoly1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyPoly1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..962116e068b47ba52f916c821ce20ba065c3056a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/applyPoly1d.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/applyFunction.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Polynomial/Poly1d.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Apply polynomial elemnt wise to the input values. + /// + /// @param inArray + /// @param inPoly + /// @return NdArray + /// + template + void applyPoly1d(NdArray& inArray, const polynomial::Poly1d& inPoly) + { + applyFunction(inArray, inPoly); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arange.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arange.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fea0207071fe04dd7910c48ec9f4e52e3eaa1285 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arange.hpp @@ -0,0 +1,148 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inStart + /// @param inStop + /// @param inStep: (Optional, defaults to 1) + /// @return NdArray + /// + template + NdArray arange(dtype inStart, dtype inStop, dtype inStep = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inStep > 0 && inStop < inStart) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must be larger than the start value for positive step."); + } + + if (inStep < 0 && inStop > inStart) + { + THROW_INVALID_ARGUMENT_ERROR("start value must be larger than the stop value for negative step."); + } + + std::vector values; + + dtype theValue = inStart; + auto counter = dtype{ 1 }; + + if (inStep > 0) + { + while (theValue < inStop) + { + values.push_back(theValue); + theValue = inStart + inStep * counter++; + } + } + else + { + while (theValue > inStop) + { + values.push_back(theValue); + theValue = inStart + inStep * counter++; + } + } + + return NdArray(values); + } + + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inStop: start is 0 and step is 1 + /// @return NdArray + /// + template + NdArray arange(dtype inStop) + { + if (inStop <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must ge greater than 0."); + } + + return arange(0, inStop, 1); + } + + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inSlice + /// @return NdArray + /// + template + NdArray arange(const Slice& inSlice) + { + return arange(inSlice.start, inSlice.stop, inSlice.step); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccos.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccos.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9996370f27d4789f66e2824787f1b8f0d5cb4424 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccos.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse cosine + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccos.html + /// + /// @param inValue + /// @return value + /// + template + auto arccos(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::acos(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse cosine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccos.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arccos(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arccos(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccosh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccosh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..53b20e66e474384162d5225f58eaaaa9aeca01ff --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arccosh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic cosine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccosh.html + /// + /// @param inValue + /// @return value + /// + template + auto arccosh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::acosh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic cosine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccosh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arccosh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arccosh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2e39f7ebc7c6b9afe087acc6edfda087fc971d5a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsin.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsin.html + /// + /// @param inValue + /// @return value + /// + template + auto arcsin(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::asin(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsin.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arcsin(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arcsin(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsinh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsinh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1763ba7dc64740fafa070ed00fd9ee2e8571aa14 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arcsinh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsinh.html + /// + /// @param inValue + /// @return value + /// + template + auto arcsinh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::asinh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsinh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arcsinh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arcsinh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5f61bb85bba9574a5ec90ee714091936734bf64e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan.html + /// + /// @param inValue + /// @return value + /// + template + auto arctan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::atan(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arctan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arctan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0e2ebf0a4183fc3e0a4cfe20287abd55d2c0b32d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctan2.hpp @@ -0,0 +1,86 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan2.html + /// + /// @param inY + /// @param inX + /// @return value + /// + template + auto arctan2(dtype inY, dtype inX) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::atan2(inY, inX); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan2.html + /// + /// @param inY + /// @param inX + /// @return NdArray + /// + template + auto arctan2(const NdArray& inY, const NdArray& inX) + { + if (inX.shape() != inY.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inY.shape()); + stl_algorithms::transform( + inY.cbegin(), + inY.cend(), + inX.cbegin(), + returnArray.begin(), + [](dtype y, dtype x) noexcept -> auto{ return arctan2(y, x); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctanh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctanh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f89a48c32fe7464b770a3527965c74ae0a387b9f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/arctanh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctanh.html + /// + /// @param inValue + /// @return value + /// + template + auto arctanh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::atanh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctanh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arctanh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arctanh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a7179de2bc4d3501d44381b4336da57ce18fd0c2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmax.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the maximum values along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argmax(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..adb4984bbda9085e54dbf710cc5704447a3e8693 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argmin.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the minimum values along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argmin(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argsort.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argsort.hpp new file mode 100644 index 0000000000000000000000000000000000000000..667febb544bc12ad8a0ec3555f62cebb0076af3a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argsort.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices that would sort an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argsort.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argsort(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argsort(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argwhere.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argwhere.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2e4d0905dbb37b77f596b9c800f8405b0bfcb22b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/argwhere.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the indices of array elements that are non-zero, grouped by element. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argwhere.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray argwhere(const NdArray& inArray) + { + return inArray.flatnonzero(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/around.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/around.hpp new file mode 100644 index 0000000000000000000000000000000000000000..796b697bc463d434a8d89313d0ca5d789974788b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/around.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.around.html + /// + /// @param inValue + /// @param inNumDecimals: (Optional, default = 0) + /// @return value + /// + template + dtype around(dtype inValue, uint8 inNumDecimals = 0) + { + NdArray value = { inValue }; + return value.round(inNumDecimals).item(); + } + + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.around.html + /// + /// @param inArray + /// @param inNumDecimals: (Optional, default = 0) + /// @return NdArray + /// + template + NdArray around(const NdArray& inArray, uint8 inNumDecimals = 0) + { + return inArray.round(inNumDecimals); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..86af313c1223a930cf9e7b7262d2679b412feabc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equal.hpp @@ -0,0 +1,56 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/array_equiv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// True if two arrays have the same shape and elements, False otherwise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.array_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return bool + /// + template + bool array_equal(const NdArray& inArray1, const NdArray& inArray2) noexcept + { + if (inArray1.shape() != inArray2.shape()) + { + return false; + } + + return array_equiv(inArray1, inArray2); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equiv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equiv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b5acfdd1666d2ae8ab7a9599e11bc27150bcb10d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/array_equiv.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns True if input arrays are shape consistent and all elements equal. + /// + /// Shape consistent means they are either the same shape, or one input array + /// can be broadcasted to create the same shape as the other one. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.array_equiv.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return bool + /// + template + bool array_equiv(const NdArray& inArray1, const NdArray& inArray2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inArray1.size() != inArray2.size()) + { + return false; + } + + if (DtypeInfo::isInteger()) + { + return stl_algorithms::equal(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin()); + } + + const auto comparitor = [](dtype value1, dtype value2) noexcept -> bool + { return utils::essentiallyEqual(value1, value2); }; + + return stl_algorithms::equal(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), comparitor); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/asarray.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/asarray.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bc3d379bd617dc48db9bc8e30c2308f350fa1bd0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/asarray.hpp @@ -0,0 +1,320 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert the list initializer to an array. + /// eg: NdArray myArray = NC::asarray({1,2,3}); + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::initializer_list inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the list initializer to an array. + /// eg: NdArray myArray = NC::asarray({{1,2,3}, {4, 5, 6}}); + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template + NdArray asarray(std::initializer_list> inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the std::array to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::array& inArray, bool copy = true) + { + return NdArray(inArray, copy); + } + + //============================================================================ + // Method Description: + /// Convert the std::array to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template + NdArray asarray(std::array, Dim0Size>& inArray, bool copy = true) + { + return NdArray(inArray, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::vector& inVector, bool copy = true) + { + return NdArray(inVector, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @return NdArray + /// + template + NdArray asarray(const std::vector>& inVector) + { + return NdArray(inVector); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template + NdArray asarray(std::vector>& inVector, bool copy = true) + { + return NdArray(inVector, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inDeque + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(const std::deque& inDeque) + { + return NdArray(inDeque); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inDeque + /// @return NdArray + /// + template + NdArray asarray(const std::deque>& inDeque) + { + return NdArray(inDeque); + } + + //============================================================================ + // Method Description: + /// Convert the set to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inSet + /// @return NdArray + /// + template + NdArray asarray(const std::set& inSet) + { + return NdArray(inSet); + } + + //============================================================================ + // Method Description: + /// Convert the list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template + NdArray asarray(const std::list& inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the forward_list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param iterBegin + /// @param iterEnd + /// @return NdArray + /// + template + auto asarray(Iterator iterBegin, Iterator iterEnd) + { + return NdArray::value_type>(iterBegin, iterEnd); + } + + //============================================================================ + // Method Description: + /// Convert the forward_list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param iterBegin + /// @param iterEnd + /// @return NdArray + /// + template + NdArray asarray(const dtype* iterBegin, const dtype* iterEnd) + { + return NdArray(iterBegin, iterEnd); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param size: the number of elements in the array + /// @return NdArray + /// + template + NdArray asarray(const dtype* ptr, uint32 size) + { + return NdArray(ptr, size); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// @return NdArray + /// + template + NdArray asarray(const dtype* ptr, uint32 numRows, uint32 numCols) + { + return NdArray(ptr, numRows, numCols); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param size: the number of elements in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// @return NdArray + /// + template::value, int> = 0> + NdArray asarray(dtype* ptr, uint32 size, BoolType takeOwnership) noexcept + { + return NdArray(ptr, size, takeOwnership); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// @return NdArray + /// + template::value, int> = 0> + NdArray asarray(dtype* ptr, uint32 numRows, uint32 numCols, BoolType takeOwnership) noexcept + { + return NdArray(ptr, numRows, numCols, takeOwnership); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/astype.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/astype.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6a2f74ba39a92180f3d1e4f61907bb9f7497ec58 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/astype.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray astype(const NdArray inArray) + { + return inArray.template astype(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/average.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/average.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b177389da7897ab4ef0577a09e584e9ba3e06bcf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/average.hpp @@ -0,0 +1,214 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + auto average(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return mean(inArray, inAxis); + } + + //============================================================================ + // Method Description: + /// Compute the weighted average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inWeights + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray average(const NdArray& inArray, const NdArray& inWeights, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + if (inWeights.shape() != inArray.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weight values are not consistant."); + } + + NdArray weightedArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inWeights.cbegin(), + weightedArray.begin(), + std::multiplies()); // NOLINT(modernize-use-transparent-functors) + + double sum = std::accumulate(weightedArray.begin(), weightedArray.end(), 0.); + NdArray returnArray = { sum /= inWeights.template astype().sum().item() }; + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray.shape(); + if (inWeights.size() != arrayShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weights value are not consistant."); + } + + double weightSum = inWeights.template astype().sum().item(); + NdArray returnArray(1, arrayShape.rows); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + NdArray weightedArray(1, arrayShape.cols); + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row), + inWeights.cbegin(), + weightedArray.begin(), + std::multiplies()); // NOLINT(modernize-use-transparent-functors) + + double sum = std::accumulate(weightedArray.begin(), weightedArray.end(), 0.); + returnArray(0, row) = sum / weightSum; + } + + return returnArray; + } + case Axis::ROW: + { + return average(inArray.transpose(), inWeights, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Compute the weighted average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inWeights + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray> + average(const NdArray>& inArray, const NdArray& inWeights, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto multiplies = [](const std::complex& lhs, dtype rhs) -> std::complex + { return complex_cast(lhs) * static_cast(rhs); }; + + switch (inAxis) + { + case Axis::NONE: + { + if (inWeights.shape() != inArray.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weight values are not consistant."); + } + + NdArray> weightedArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inWeights.cbegin(), + weightedArray.begin(), + multiplies); + + std::complex sum = + std::accumulate(weightedArray.begin(), weightedArray.end(), std::complex(0.)); + NdArray> returnArray = { sum /= inWeights.template astype().sum().item() }; + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray.shape(); + if (inWeights.size() != arrayShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weights value are not consistant."); + } + + double weightSum = inWeights.template astype().sum().item(); + NdArray> returnArray(1, arrayShape.rows); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + NdArray> weightedArray(1, arrayShape.cols); + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row), + inWeights.cbegin(), + weightedArray.begin(), + multiplies); + + const std::complex sum = + std::accumulate(weightedArray.begin(), weightedArray.end(), std::complex(0.)); + returnArray(0, row) = sum / weightSum; + } + + return returnArray; + } + case Axis::ROW: + { + return average(inArray.transpose(), inWeights, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bartlett.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bartlett.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a3e12df2ee04941914ef373eb1b90a22a69df111 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bartlett.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Bartlett window is very similar to a triangular window, except that the end + /// points are at zero. It is often used in signal processing for tapering a signal, + /// without generating too much ripple in the frequency domain. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.bartlett.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray bartlett(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto mMinus1Over2 = (mDouble - 1.) / 2.; + const auto mMinus1Over2Inv = 1. / mMinus1Over2; + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = mMinus1Over2Inv * (mMinus1Over2 - std::abs(n - mMinus1Over2)); + } + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/binaryRepr.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/binaryRepr.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b4f47f0296293dd15dcd526c813b6ea19679b76b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/binaryRepr.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the binary representation of the input number as a string. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.binary_repr.html + /// + /// @param inValue + /// @return std::string + /// + template + std::string binaryRepr(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::bitset::bits()>(inValue).to_string(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bincount.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bincount.hpp new file mode 100644 index 0000000000000000000000000000000000000000..15c0c50ddc5ec32cc28824b15fbbb545164e24d7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bincount.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Count number of occurrences of each value in array of non-negative ints. + /// Negative values will be counted in the zero bin. + /// + /// The number of bins(of size 1) is one larger than the largest value in x. + /// If minlength is specified, there will be at least this number of bins in + /// the output array(though it will be longer if necessary, depending on the + /// contents of x).Each bin gives the number of occurrences of its index value + /// in x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bincount.html + /// + /// @param inArray + /// @param inMinLength + /// @return NdArray + /// + template + NdArray bincount(const NdArray& inArray, uint16 inMinLength = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + dtype maxValue = inArray.max().item(); + if (maxValue < 0) + { + // no positive values so just return an empty array + return NdArray(0); + } + + if (maxValue + 1 > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR( + "array values too large, will result in gigantic array that will take up alot of memory..."); + } + + const uint16 outArraySize = std::max(static_cast(maxValue + 1), inMinLength); + NdArray clippedArray = inArray.clip(0, maxValue); + + NdArray outArray(1, outArraySize); + outArray.zeros(); + std::for_each(clippedArray.cbegin(), + clippedArray.cend(), + [&outArray](dtype value) noexcept -> void { ++outArray[value]; }); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Count number of occurrences of each value in array of non-negative ints. + /// Negative values will be counted in the zero bin. + /// + /// The number of bins(of size 1) is one larger than the largest value in x. + /// If minlength is specified, there will be at least this number of bins in + /// the output array(though it will be longer if necessary, depending on the + /// contents of x).Each bin gives the number of occurrences of its index value + /// in x.If weights is specified the input array is weighted by it, i.e. if a + /// value n is found at position i, out[n] += weight[i] instead of out[n] += 1. + /// Weights array shall be of the same shape as inArray. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bincount.html + /// + /// @param inArray + /// @param inWeights + /// @param inMinLength + /// @return NdArray + /// + template + NdArray bincount(const NdArray& inArray, const NdArray& inWeights, uint16 inMinLength = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inArray.shape() != inWeights.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("weights array must be the same shape as the input array."); + } + + dtype maxValue = inArray.max().item(); + if (maxValue < 0) + { + // no positive values so just return an empty array + return NdArray(0); + } + + if (maxValue + 1 > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR( + "array values too large, will result in gigantic array that will take up alot of memory..."); + } + + const uint16 outArraySize = std::max(static_cast(maxValue + 1), inMinLength); + NdArray clippedArray = inArray.clip(0, maxValue); + + NdArray outArray(1, outArraySize); + outArray.zeros(); + uint32 counter = 0; + std::for_each(clippedArray.cbegin(), + clippedArray.cend(), + [&outArray, &inWeights, &counter](dtype value) noexcept -> void + { outArray[value] += inWeights[counter++]; }); + + return outArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bit_count.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bit_count.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4ec25607e9d642d8c057b2924f65a733d71bed16 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bit_count.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Computes the number of 1-bits in an integer + /// + /// @param inValue + /// @return value + /// + template + constexpr int bit_count(dtype inValue) noexcept + { + STATIC_ASSERT_UNSIGNED_INTEGER(dtype); + + int count = 0; + for (int bit = 0; bit < DtypeInfo::bits(); ++bit) + { + count += static_cast((inValue & (dtype{ 1 } << bit)) >> bit); + } + + return count; + } + + //============================================================================ + // Method Description: + /// Computes the number of 1-bits in an integer + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray bit_count(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> int { return bit_count(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_and.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_and.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b14ed54319e61484b4750a85b53aecc7c7a8c534 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_and.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise AND of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_and.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_and(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 & inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_not.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_not.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d2513cf27758777935fd8f8d7542f0fa9733ee72 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_not.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise NOT the input array element-wise. + /// + /// inArray + /// @return NdArray + /// + template + NdArray bitwise_not(const NdArray& inArray) + { + return ~inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_or.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_or.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ec5cf552abbc1a1ee6186599f3e289e55da9b366 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_or.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise OR of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_or.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_or(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 | inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_xor.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_xor.hpp new file mode 100644 index 0000000000000000000000000000000000000000..14381c0331b6047b46b0d24ea3689c8abdb01c51 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/bitwise_xor.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise XOR of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_xor.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_xor(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 ^ inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/blackman.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/blackman.hpp new file mode 100644 index 0000000000000000000000000000000000000000..57c96f5c7c42d165825bd7fa0728262f82d7e7d9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/blackman.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Blackman window is a taper formed by using the first three terms of a summation of + /// cosines. It was designed to have close to the minimal leakage possible. It is close to + /// optimal, only slightly worse than a Kaiser window. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.blackman.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray blackman(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble, m, true)) + { + const auto nOverM = n / mDouble; + result[i++] = + 0.42 - 0.5 * std::cos(2. * constants::pi * nOverM) + 0.08 * std::cos(4. * constants::pi * nOverM); + } + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/byteswap.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/byteswap.hpp new file mode 100644 index 0000000000000000000000000000000000000000..42266375dbb4313e63a206249b9367e2ca0b7f2b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/byteswap.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the bytes of the array elements + /// swapped. + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray byteswap(const NdArray& inArray) + { + NdArray returnArray(inArray); + returnArray.byteswap(); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cbrt.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cbrt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a1b4ab098c3bf6778b1627e1e74cc7496b940e99 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cbrt.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cube-root of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cbrt.html + /// + /// @param inValue + /// @return value + /// + template + double cbrt(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::cbrt(static_cast(inValue)); + } + + //============================================================================ + // Method Description: + /// Return the cube-root of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cbrt.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray cbrt(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> double { return cbrt(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ceil.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ceil.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9668bbb1c7f44261824c323d04c9d6a651fea750 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ceil.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the ceiling of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ceil.html + /// + /// @param inValue + /// @return value + /// + template + dtype ceil(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::ceil(inValue); + } + + //============================================================================ + // Method Description: + /// Return the ceiling of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ceil.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray ceil(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return ceil(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/centerOfMass.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/centerOfMass.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e28baab0a8eb272ede04840150b96d8eda25896a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/centerOfMass.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the center of mass of the array values along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE which is a 2d center of mass) + /// @return NdArray: if axis is NONE then a 1x2 array of the centroid row/col is returned. + /// + template + NdArray centerOfMass(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape shape = inArray.shape(); + + switch (inAxis) + { + case Axis::NONE: + { + double inten = 0.; + double rowCenter = 0.; + double colCenter = 0.; + + for (uint32 row = 0; row < shape.rows; ++row) + { + for (uint32 col = 0; col < shape.cols; ++col) + { + const auto pixelValue = static_cast(inArray(row, col)); + + inten += pixelValue; + rowCenter += pixelValue * static_cast(row); + colCenter += pixelValue * static_cast(col); + } + } + + rowCenter /= inten; + colCenter /= inten; + + return { rowCenter, colCenter }; + } + case Axis::ROW: + { + NdArray returnArray(1, shape.cols); + returnArray.zeros(); + + const NdArray inten = inArray.template astype().sum(inAxis); + + for (uint32 colIdx = 0; colIdx < shape.cols; ++colIdx) + { + for (uint32 rowIdx = 0; rowIdx < shape.rows; ++rowIdx) + { + returnArray(0, colIdx) += + static_cast(inArray(rowIdx, colIdx)) * static_cast(rowIdx); + } + + returnArray(0, colIdx) /= inten[colIdx]; + } + + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape.rows); + returnArray.zeros(); + + const NdArray inten = inArray.template astype().sum(inAxis); + + for (uint32 rowIdx = 0; rowIdx < shape.rows; ++rowIdx) + { + for (uint32 colIdx = 0; colIdx < shape.cols; ++colIdx) + { + returnArray(0, rowIdx) += + static_cast(inArray(rowIdx, colIdx)) * static_cast(colIdx); + } + + returnArray(0, rowIdx) /= inten[rowIdx]; + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/clip.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/clip.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1b93b3f0766b766add166083fa4ab2653666cc8c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/clip.hpp @@ -0,0 +1,88 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Clip (limit) the value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.clip.html + /// + /// @param inValue + /// @param inMinValue + /// @param inMaxValue + /// @return NdArray + /// + template + dtype clip(dtype inValue, dtype inMinValue, dtype inMaxValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + +#ifdef __cpp_lib_clamp + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + return std::clamp(inValue, inMinValue, inMaxValue, comparitor); +#else + if (inValue < inMinValue) + { + return inMinValue; + } + else if (inValue > inMaxValue) + { + return inMaxValue; + } + + return inValue; +#endif + } + + //============================================================================ + // Method Description: + /// Clip (limit) the values in an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.clip.html + /// + /// @param inArray + /// @param inMinValue + /// @param inMaxValue + /// @return NdArray + /// + template + NdArray clip(const NdArray& inArray, dtype inMinValue, dtype inMaxValue) + { + return inArray.clip(inMinValue, inMaxValue); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/column_stack.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/column_stack.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b5751ffa385f58bc43c61ec50239040ebc535cb1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/column_stack.hpp @@ -0,0 +1,131 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Stack 1-D arrays as columns into a 2-D array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.column_stack.html + /// + /// @param begin: iterator to the beginning of the span + /// @param end: iterator to one past the end of the span + /// @return NdArray + /// + template + NdArray column_stack(Iterator begin, Iterator end) + { + // first loop through to calculate the final size of the array + Shape finalShape; + auto iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + if (ndarray.shape().isnull()) + { + continue; + } + + if (finalShape.isnull()) + { + finalShape = ndarray.shape(); + } + else if (ndarray.shape().rows != finalShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays must have the same number of rows."); + } + else + { + finalShape.cols += ndarray.shape().cols; + } + } + + // now that we know the final size, contruct the output array + NdArray returnArray(finalShape); + uint32 colStart = 0; + iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + const Shape theShape = ndarray.shape(); + for (uint32 row = 0; row < theShape.rows; ++row) + { + for (uint32 col = 0; col < theShape.cols; ++col) + { + returnArray(row, colStart + col) = ndarray(row, col); + } + } + colStart += theShape.cols; + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Stack 1-D arrays as columns into a 2-D array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.column_stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @return NdArray + /// + template + NdArray column_stack(const std::initializer_list>& inArrayList) + { + return detail::column_stack(inArrayList.begin(), inArrayList.end()); + } + + //============================================================================ + // Method Description: + /// Stack 1-D arrays as columns into a 2-D array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.column_stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @return NdArray + /// + template + NdArray column_stack(const std::vector>& inArrayList) + { + return detail::column_stack(inArrayList.begin(), inArrayList.end()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/complex.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/complex.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f826dcb020b429ea75512a6aabafe13bbe25410d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/complex.hpp @@ -0,0 +1,116 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @return value + /// + template + auto complex(dtype inReal) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::complex(inReal); + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @param inImag: the imaginary component of the complex number + /// @return value + /// + template + auto complex(dtype inReal, dtype inImag) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::complex(inReal, inImag); + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @return NdArray + /// + template + auto complex(const NdArray& inReal) + { + NdArray returnArray(inReal.shape()); + stl_algorithms::transform( + inReal.cbegin(), + inReal.cend(), + returnArray.begin(), + [](dtype real) -> auto{ return nc::complex(real); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @param inImag: the imaginary component of the complex number + /// @return NdArray + /// + template + auto complex(const NdArray& inReal, const NdArray& inImag) + { + if (inReal.shape() != inImag.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("Input real array must be the same shape as input imag array"); + } + + NdArray returnArray(inReal.shape()); + stl_algorithms::transform( + inReal.cbegin(), + inReal.cend(), + inImag.cbegin(), + returnArray.begin(), + [](dtype real, dtype imag) -> auto{ return nc::complex(real, imag); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/concatenate.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/concatenate.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3b3c415bda7c14bcc50a8d49d62d39a7ef99c020 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/concatenate.hpp @@ -0,0 +1,129 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/row_stack.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Join a sequence of arrays along an existing axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.concatenate.html + /// + /// @param begin: the begin iterator + /// @param end: the end iterator + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray concatenate(Iterator begin, Iterator end, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + uint32 finalSize = 0; + auto iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + finalSize += ndarray.size(); + } + + NdArray returnArray(1, finalSize); + uint32 offset = 0; + iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + stl_algorithms::copy(ndarray.cbegin(), ndarray.cend(), returnArray.begin() + offset); + offset += ndarray.size(); + } + + return returnArray; + } + case Axis::ROW: + { + return row_stack(begin, end); + } + case Axis::COL: + { + return column_stack(begin, end); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Join a sequence of arrays along an existing axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.concatenate.html + /// + /// @param inArrayList + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray concatenate(const std::initializer_list>& inArrayList, Axis inAxis = Axis::NONE) + { + return detail::concatenate(inArrayList.begin(), inArrayList.end(), inAxis); + } + + //============================================================================ + // Method Description: + /// Join a sequence of arrays along an existing axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.concatenate.html + /// + /// @param inArrayList + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray concatenate(const std::vector>& inArrayList, Axis inAxis = Axis::NONE) + { + return detail::concatenate(inArrayList.begin(), inArrayList.end(), inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/conj.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/conj.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f13ed7fb37b2a6a48b38db4797c29d08149a3a90 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/conj.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the complex conjugate of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.conj.html + /// + /// @param inValue + /// @return value + /// + template + auto conj(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::conj(inValue); + } + + //============================================================================ + // Method Description: + /// Return the complex conjugate of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.conj.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto conj(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::conj(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/contains.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/contains.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bbb7c0c11054f2df1be4a22523ab7bfa58dbdf01 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/contains.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// returns whether or not a value is included the array + /// + /// @param inArray + /// @param inValue + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray contains(const NdArray& inArray, dtype inValue, Axis inAxis = Axis::NONE) + { + return inArray.contains(inValue, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copy.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copy.hpp new file mode 100644 index 0000000000000000000000000000000000000000..da6e6b298eb5472cbbbfec914c88aaa6d13ab0bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copy.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return an array copy of the given object. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copy.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray copy(const NdArray& inArray) + { + return NdArray(inArray); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copySign.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copySign.hpp new file mode 100644 index 0000000000000000000000000000000000000000..883428dd5a0b9ab3c9a2672763660431faf88bb1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copySign.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change the sign of x1 to that of x2, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copysign.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray copySign(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [](dtype inValue1, dtype inValue2) -> dtype + { return inValue2 < dtype{ 0 } ? std::abs(inValue1) * -1 : std::abs(inValue1); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copyto.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copyto.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bf005f4a1b0130d24f421f404f2e7b6e3bef9369 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/copyto.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Copies values from one array to another + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copyto.html + /// + /// @param inDestArray + /// @param inSrcArray + /// @return NdArray + /// + template + NdArray& copyto(NdArray& inDestArray, const NdArray& inSrcArray) + { + inDestArray = inSrcArray; + return inDestArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/corrcoef.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/corrcoef.hpp new file mode 100644 index 0000000000000000000000000000000000000000..364a36dfd1ec0a80f104182c0d5598e143cdb565 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/corrcoef.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Functions/empty_like.hpp" +#include "NumCpp/Functions/sqrt.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return Pearson product-moment correlation coefficients. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @return NdArray + /// + template + NdArray corrcoef(const NdArray& x) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto covariance = cov(x); + auto normalizedCovariance = empty_like(covariance); + for (decltype(covariance.numRows()) i = 0; i < covariance.numRows(); ++i) + { + for (decltype(covariance.numCols()) j = 0; j < covariance.numCols(); ++j) + { + normalizedCovariance(i, j) = covariance(i, j) / sqrt(covariance(i, i) * covariance(j, j)); + } + } + + return normalizedCovariance; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cos.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cos.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f4d2e7d55992e67010baad959262fabfe54d7109 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cos.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Cosine + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cos.html + /// + /// @param inValue + /// @return value + /// + template + auto cos(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::cos(inValue); + } + + //============================================================================ + // Method Description: + /// Cosine element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cos.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto cos(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return cos(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cosh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cosh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ec99e8bfe94ab9abdb7a89555f1ab559d4bedd3a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cosh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Hyperbolic Cosine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cosh.html + /// + /// @param inValue + /// @return value + /// + template + auto cosh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::cosh(inValue); + } + + //============================================================================ + // Method Description: + /// Hyperbolic Cosine element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cosh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto cosh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return cosh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/count_nonzero.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/count_nonzero.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f00d3ca5fe085b7be8b3404f4396066405ffb7ca --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/count_nonzero.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Counts the number of non-zero values in the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.count_nonzero.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray count_nonzero(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + NdArray count = { inArray.size() - + static_cast( + stl_algorithms::count(inArray.cbegin(), inArray.cend(), dtype{ 0 })) }; + return count; + } + case Axis::COL: + { + Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(0, row) = + inShape.cols - + static_cast(stl_algorithms::count(inArray.cbegin(row), inArray.cend(row), dtype{ 0 })); + } + + return returnArray; + } + case Axis::ROW: + { + return count_nonzero(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov.hpp new file mode 100644 index 0000000000000000000000000000000000000000..13c2606832f1f095072d17667e4d772adc1ca1ad --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov.hpp @@ -0,0 +1,93 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Estimate a covariance matrix. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.cov.html + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @param bias: Default normalization (false) is by (N - 1), where N is the number of observations + /// given (unbiased estimate). If bias is True, then normalization is by N. + /// @return NdArray + /// + template + NdArray cov(const NdArray& x, bool bias = false) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto varMeans = mean(x, Axis::COL); + const auto numVars = x.numRows(); + const auto numObs = x.numCols(); + const auto normilizationFactor = bias ? static_cast(numObs) : static_cast(numObs - 1); + using IndexType = typename std::remove_const::type; + + // upper triangle + auto covariance = NdArray(numVars); + for (IndexType i = 0; i < numVars; ++i) + { + const auto var1Mean = varMeans[i]; + + for (IndexType j = i; j < numVars; ++j) + { + const auto var2Mean = varMeans[j]; + + double sum = 0.; + for (IndexType iObs = 0; iObs < numObs; ++iObs) + { + sum += (x(i, iObs) - var1Mean) * (x(j, iObs) - var2Mean); + } + + covariance(i, j) = sum / normilizationFactor; + } + } + + // fill in the rest of the symmetric matrix + for (IndexType j = 0; j < numVars; ++j) + { + for (IndexType i = j + 1; i < numVars; ++i) + { + covariance(i, j) = covariance(j, i); + } + } + + return covariance; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov_inv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov_inv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5478211725a54e03fa2d1708c9126ef294f36c35 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cov_inv.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Estimate an inverse covariance matrix, aka the concentration matrix + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @param bias: Default normalization (false) is by (N - 1), where N is the number of observations + /// given (unbiased estimate). If bias is True, then normalization is by N. + /// @return NdArray + /// + template + NdArray cov_inv(const NdArray& x, bool bias = false) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return linalg::inv(cov(x, bias)); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cross.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cross.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ab267e4665c6ca1a61292b671fe9cd38f48f8f85 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cross.hpp @@ -0,0 +1,171 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cross product of two (arrays of) vectors. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cross.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cross(const NdArray& inArray1, const NdArray& inArray2, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("the input array dimensions are not consistant."); + } + + switch (inAxis) + { + case Axis::NONE: + { + const uint32 arraySize = inArray1.size(); + if (arraySize != inArray2.size() || arraySize < 2 || arraySize > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + NdArray in1 = inArray1.flatten(); + NdArray in2 = inArray2.flatten(); + + switch (arraySize) + { + case 2: + { + NdArray returnArray = { in1[0] * in2[1] - in1[1] * in2[0] }; + return returnArray; + } + case 3: + { + dtype i = in1[1] * in2[2] - in1[2] * in2[1]; + dtype j = -(in1[0] * in2[2] - in1[2] * in2[0]); + dtype k = in1[0] * in2[1] - in1[1] * in2[0]; + + NdArray returnArray = { i, j, k }; + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented array size."); + return {}; // get rid of compiler warning + } + } + } + case Axis::ROW: + { + const Shape arrayShape = inArray1.shape(); + if (arrayShape != inArray2.shape() || arrayShape.rows < 2 || arrayShape.rows > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + Shape returnArrayShape; + returnArrayShape.cols = arrayShape.cols; + if (arrayShape.rows == 2) + { + returnArrayShape.rows = 1; + } + else + { + returnArrayShape.rows = 3; + } + + NdArray returnArray(returnArrayShape); + for (uint32 col = 0; col < arrayShape.cols; ++col) + { + const auto theCol = static_cast(col); + NdArray vec1 = inArray1(inArray1.rSlice(), { theCol, theCol + 1 }); + NdArray vec2 = inArray2(inArray2.rSlice(), { theCol, theCol + 1 }); + NdArray vecCross = cross(vec1, vec2, Axis::NONE); + + returnArray.put({ 0, static_cast(returnArrayShape.rows) }, { theCol, theCol + 1 }, vecCross); + } + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray1.shape(); + if (arrayShape != inArray2.shape() || arrayShape.cols < 2 || arrayShape.cols > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + Shape returnArrayShape; + returnArrayShape.rows = arrayShape.rows; + if (arrayShape.cols == 2) + { + returnArrayShape.cols = 1; + } + else + { + returnArrayShape.cols = 3; + } + + NdArray returnArray(returnArrayShape); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + const auto theRow = static_cast(row); + NdArray vec1 = inArray1({ theRow, theRow + 1 }, inArray1.cSlice()); + NdArray vec2 = inArray2({ theRow, theRow + 1 }, inArray2.cSlice()); + NdArray vecCross = cross(vec1, vec2, Axis::NONE); + + returnArray.put({ theRow, theRow + 1 }, { 0, static_cast(returnArrayShape.cols) }, vecCross); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cube.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cube.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e0f933599d61790e4f59dbeea80a71e0b48a0a38 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cube.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/cube.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Cubes the input + /// + /// @param inValue + /// @return cubed value + /// + template + constexpr dtype cube(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return utils::cube(inValue); + } + + //============================================================================ + // Method Description: + /// Cubes the elements of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray cube(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return cube(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumprod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumprod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e230cf31f45d310809ca2655926a1134ab2d19f2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumprod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative product of elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cumprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cumprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.cumprod(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumsum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumsum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..dedf9c8abfcea5afeacec2e18c14726d2994a4b4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/cumsum.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cumsum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cumsum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.cumsum(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deg2rad.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deg2rad.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a73435e3d879518450d812764f364ae6c3add01c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deg2rad.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.deg2rad.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto deg2rad(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue * constants::pi / 180.; + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.deg2rad.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto deg2rad(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return deg2rad(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/degrees.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/degrees.hpp new file mode 100644 index 0000000000000000000000000000000000000000..14a6462fc3d381b853ab881aa9f7a6d24118bb5c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/degrees.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.degrees.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto degrees(dtype inValue) noexcept + { + return rad2deg(inValue); + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.degrees.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto degrees(const NdArray& inArray) + { + return rad2deg(inArray); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deleteIndices.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deleteIndices.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ce9d087c24a54a5ed4d861ac7eb1fda125bae40b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/deleteIndices.hpp @@ -0,0 +1,316 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteFlatIndices(const NdArray& inArray, Indices inIndices) + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + const auto arraySize = inArray.size(); + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arraySize](auto& value) + { + if (value < 0) + { + value += arraySize; + } + }); + } + + auto indices = unique(inIndices); + + std::vector values; + values.reserve(indices.size()); + for (int32 i = 0; i < static_cast(inArray.size()); ++i) + { + if (std::binary_search(indices.begin(), indices.end(), i)) + { + continue; + } + + values.push_back(inArray[i]); + } + + return NdArray(values); + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along the row axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteRowIndices(const NdArray& inArray, Indices inIndices) + { + const auto arrayRows = static_cast(inArray.numRows()); + if constexpr (type_traits::is_ndarray_signed_int_v) + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arrayRows](auto& value) + { + if (value < 0) + { + value += arrayRows; + } + }); + } + + auto indices = unique(inIndices); + + uint32 indicesSize = 0; + std::for_each(indices.begin(), + indices.end(), + [arrayRows, &indicesSize](const auto& value) + { + if constexpr (std::is_signed_v) + { + if (value >= 0 && value < arrayRows) + { + ++indicesSize; + } + } + else + { + if (value < arrayRows) + { + ++indicesSize; + } + } + }); + + const auto arrayCols = static_cast(inArray.numCols()); + NdArray returnArray(arrayRows - indicesSize, arrayCols); + + uint32 rowCounter = 0; + for (int32 row = 0; row < arrayRows; ++row) + { + if (std::binary_search(indices.begin(), indices.end(), row)) + { + continue; + } + + for (int32 col = 0; col < arrayCols; ++col) + { + returnArray(rowCounter, col) = inArray(row, col); + } + + ++rowCounter; + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along the col axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteColumnIndices(const NdArray& inArray, Indices inIndices) + { + const auto arrayCols = static_cast(inArray.numCols()); + if constexpr (type_traits::is_ndarray_signed_int_v) + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arrayCols](auto& value) + { + if (value < 0) + { + value += arrayCols; + } + }); + } + + auto indices = unique(inIndices); + + uint32 indicesSize = 0; + std::for_each(indices.begin(), + indices.end(), + [arrayCols, &indicesSize](const auto& value) + { + if constexpr (std::is_signed_v) + { + if (value >= 0 && value < arrayCols) + { + ++indicesSize; + } + } + else + { + if (value < arrayCols) + { + ++indicesSize; + } + } + }); + + const auto arrayRows = static_cast(inArray.numRows()); + NdArray returnArray(arrayRows, arrayCols - indicesSize); + + uint32 colCounter = 0; + for (int32 col = 0; col < arrayCols; ++col) + { + if (std::binary_search(indices.begin(), indices.end(), col)) + { + continue; + } + + for (int32 row = 0; row < arrayRows; ++row) + { + returnArray(row, colCounter) = inArray(row, col); + } + + ++colCounter; + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @param inAxis (Optional, default NONE) if NONE the indices will be applied to the flattened array + /// @return NdArray + /// + template = 0> + NdArray deleteIndices(const NdArray& inArray, const Indices& inIndices, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + return detail::deleteFlatIndices(inArray, inIndices); + } + case Axis::ROW: + { + return detail::deleteRowIndices(inArray, inIndices); + } + case Axis::COL: + { + return detail::deleteColumnIndices(inArray, inIndices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndicesSlice + /// @param inAxis (Optional, default NONE) if none the indices will be applied to the flattened array + /// @return NdArray + /// + template + NdArray deleteIndices(const NdArray& inArray, Slice inIndicesSlice, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + inIndicesSlice.makePositiveAndValidate(inArray.size()); + break; + } + case Axis::ROW: + { + inIndicesSlice.makePositiveAndValidate(inArray.numRows()); + break; + } + case Axis::COL: + { + inIndicesSlice.makePositiveAndValidate(inArray.numCols()); + break; + } + } + + std::vector indices; + for (auto i = inIndicesSlice.start; i < inIndicesSlice.stop; i += inIndicesSlice.step) + { + indices.push_back(i); + } + + return deleteIndices(inArray, NdArray(indices.data(), indices.size(), false), inAxis); + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndex + /// @param inAxis (Optional, default NONE) if none the indices will be applied to the flattened array + /// @return NdArray + /// + template + NdArray deleteIndices(const NdArray& inArray, int32 inIndex, Axis inAxis = Axis::NONE) + { + NdArray inIndices = { inIndex }; + return deleteIndices(inArray, inIndices, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diag.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diag.hpp new file mode 100644 index 0000000000000000000000000000000000000000..eaf7952f21950f403ac9f69c35bb4e771d96ac4e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diag.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Functions/diagonal.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Extract a diagonal or construct a diagonal array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diag.html + /// + /// @param inArray + /// @param k Diagonal in question. The default is 0. + /// Use k>0 for diagonals above the main diagonal, and k<0 + /// for diagonals below the main diagonal. + /// + /// @return NdArray + /// + template + NdArray diag(const NdArray& inArray, int32 k = 0) + { + if (inArray.isflat()) + { + return diagflat(inArray, k); + } + + return diagonal(inArray, k, Axis::ROW); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagflat.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagflat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bc5bc6b43df04805edaa7ab3d44497771dbcbbc3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagflat.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Create a two-dimensional array with the flattened input as a diagonal. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diagflat.html + /// + /// @param inArray + /// @param k Diagonal to set; 0, the default, corresponds to the �main� diagonal, + /// a positive (negative) k giving the number of the diagonal above (below) the main. + /// + /// @return NdArray + /// + template + NdArray diagflat(const NdArray& inArray, int32 k = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto absK = static_cast(std::abs(k)); + NdArray returnArray(inArray.size() + absK); + + const uint32 rowOffset = k < 0 ? absK : 0; + const uint32 colOffset = k > 0 ? absK : 0; + + returnArray.zeros(); + for (uint32 i = 0; i < inArray.size(); ++i) + { + returnArray(i + rowOffset, i + colOffset) = inArray[i]; + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagonal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagonal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ae739928e6c2350e6283efdd7b554c0bf3104b0c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diagonal.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return specified diagonals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diagonal.html + /// + /// @param inArray + /// @param inOffset (Defaults to 0) + /// @param inAxis (Optional, default ROW) axis the offset is applied to + /// @return NdArray + /// + template + NdArray diagonal(const NdArray& inArray, int32 inOffset = 0, Axis inAxis = Axis::ROW) + { + return inArray.diagonal(inOffset, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diff.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diff.hpp new file mode 100644 index 0000000000000000000000000000000000000000..75d7cac072115f5cf7da766c54d88c6155c8bc1a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/diff.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the n-th discrete difference along given axis. + /// Unsigned dtypes will give you weird results...obviously. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diff.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray diff(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + + switch (inAxis) + { + case Axis::NONE: + { + if (inArray.size() < 2) + { + return NdArray(0); + } + + NdArray returnArray(1, inArray.size() - 1); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend() - 1, + inArray.cbegin() + 1, + returnArray.begin(), + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return inValue2 - inValue1; }); + + return returnArray; + } + case Axis::COL: + { + if (inShape.cols < 2) + { + return NdArray(0); + } + + NdArray returnArray(inShape.rows, inShape.cols - 1); + for (uint32 row = 0; row < inShape.rows; ++row) + { + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row) - 1, + inArray.cbegin(row) + 1, + returnArray.begin(row), + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return inValue2 - inValue1; }); + } + + return returnArray; + } + case Axis::ROW: + { + return diff(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/digitize.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/digitize.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b0bcb8378765a15127265cc1c7c0594375a6229a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/digitize.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the indices of the bins to which each value in input array belongs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.digitize.html + /// + /// @param x: Input array to be binned. + /// @param bins: Array of bins. + /// + /// @return NdArray + /// + template + NdArray digitize(const NdArray& x, const NdArray& bins) + { + const auto uniqueBins = unique(bins); + auto result = NdArray(1, x.size()); + result.fill(0); + + typename decltype(result)::size_type idx{ 0 }; + std::for_each(x.begin(), + x.end(), + [&uniqueBins, &result, &idx](const auto value) + { + const auto upperBin = std::upper_bound(uniqueBins.begin(), uniqueBins.end(), value); + result[idx++] = static_cast(std::distance(uniqueBins.begin(), upperBin)); + }); + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/divide.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/divide.hpp new file mode 100644 index 0000000000000000000000000000000000000000..74ba2c3d5286c295d7f0e28c60c10b16973bf269 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/divide.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray divide(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray divide(const NdArray& inArray, dtype value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray divide(dtype value, const NdArray& inArray) + { + return value / inArray; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> divide(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> divide(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> divide(const NdArray& inArray, const std::complex& value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> divide(const std::complex& value, const NdArray& inArray) + { + return value / inArray; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> divide(const NdArray>& inArray, dtype value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> divide(dtype value, const NdArray>& inArray) + { + return value / inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dot.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dot.hpp new file mode 100644 index 0000000000000000000000000000000000000000..44f57d52ad0f2370f2db61f433e92cf507cea2de --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dot.hpp @@ -0,0 +1,163 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray dot(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1.dot(inArray2); + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> dot(const NdArray& inArray1, const NdArray>& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape1 = inArray1.shape(); + const auto shape2 = inArray2.shape(); + + if (shape1 == shape2 && (shape1.rows == 1 || shape1.cols == 1)) + { + const std::complex dotProduct = + std::inner_product(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), std::complex{ 0 }); + NdArray> returnArray = { dotProduct }; + return returnArray; + } + if (shape1.cols == shape2.rows) + { + // 2D array, use matrix multiplication + NdArray> returnArray(shape1.rows, shape2.cols); + auto array2T = inArray2.transpose(); + + for (uint32 i = 0; i < shape1.rows; ++i) + { + for (uint32 j = 0; j < shape2.cols; ++j) + { + returnArray(i, j) = std::inner_product(array2T.cbegin(j), + array2T.cend(j), + inArray1.cbegin(i), + std::complex{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape1.rows) + ", " + utils::num2str(shape1.cols) + "]"; + errStr += " and [" + utils::num2str(shape2.rows) + ", " + utils::num2str(shape2.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return NdArray>(); // get rid of compiler warning + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> dot(const NdArray>& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape1 = inArray1.shape(); + const auto shape2 = inArray2.shape(); + + if (shape1 == shape2 && (shape1.rows == 1 || shape1.cols == 1)) + { + const std::complex dotProduct = + std::inner_product(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), std::complex{ 0 }); + NdArray> returnArray = { dotProduct }; + return returnArray; + } + if (shape1.cols == shape2.rows) + { + // 2D array, use matrix multiplication + NdArray> returnArray(shape1.rows, shape2.cols); + auto array2T = inArray2.transpose(); + + for (uint32 i = 0; i < shape1.rows; ++i) + { + for (uint32 j = 0; j < shape2.cols; ++j) + { + returnArray(i, j) = std::inner_product(array2T.cbegin(j), + array2T.cend(j), + inArray1.cbegin(i), + std::complex{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape1.rows) + ", " + utils::num2str(shape1.cols) + "]"; + errStr += " and [" + utils::num2str(shape2.rows) + ", " + utils::num2str(shape2.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return NdArray>(); // get rid of compiler warning + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dump.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dump.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cd0461229b873b2434161706b25bf868e3aa275f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/dump.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Dump a binary file of the array to the specified file. + /// The array can be read back with or NC::load. + /// + /// @param inArray + /// @param inFilename + /// @return NdArray + /// + template + void dump(const NdArray& inArray, const std::string& inFilename) + { + inArray.dump(inFilename); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a88c7b1afcf7a3a30ccd6bc1e996bacaf3e68eee --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, without initializing entries. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray empty(uint32 inNumRows, uint32 inNumCols) + { + return NdArray(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, without initializing entries. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray empty(const Shape& inShape) + { + return NdArray(inShape); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty_like.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty_like.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f560a3c1d22db6fda6e5d5e7283c3c96f09e3e53 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/empty_like.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the same shape as a given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray empty_like(const NdArray& inArray) + { + return NdArray(inArray.shape()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/endianess.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/endianess.hpp new file mode 100644 index 0000000000000000000000000000000000000000..73e9f633e9a5ccf2667085bc1bdf9a18f050fcb4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/endianess.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the endianess of the array values. + /// + /// @param inArray + /// @return Endian + /// + template + Endian endianess(const NdArray& inArray) noexcept + { + return inArray.endianess(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/equal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/equal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..630d55bb0fa509194df943bcd686528a559d8cbe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/equal.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return (x1 == x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 == inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c37077975fd7a17835bdd523a9fd9406dfb20b12 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the exponential of the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp.html + /// + /// @param inValue + /// @return value + /// + template + auto exp(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::exp(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the exponential of all elements in the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto exp(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return exp(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c343a16c3a1811efc902b1aaf77540055fed9adf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/exp2.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate 2**p for all p in the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp2.html + /// + /// @param inValue + /// @return value + /// + template + auto exp2(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::exp2(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate 2**p for all p in the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp2.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto exp2(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return exp2(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/expm1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/expm1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cf61a20b7b363bc96629c42f9b0f8fdceda7b06f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/expm1.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate exp(x) - 1 for the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.expm1.html + /// + /// @param inValue + /// @return value + /// + template + auto expm1(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::exp(inValue) - dtype{ 1 }; + } + + //============================================================================ + // Method Description: + /// Calculate exp(x) - 1 for all elements in the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.expm1.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto expm1(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return expm1(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/extract.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/extract.hpp new file mode 100644 index 0000000000000000000000000000000000000000..66f603b7cc30a89722b77605778a6bf78655265e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/extract.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the elements of an array that satisfy some condition. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.extract.html + /// + /// @param condition: An array whose nonzero or True entries indicate the elements of arr to extract. + /// @param arr: Input array of the same size as condition + /// @return NdArray + /// + template + NdArray extract(const NdArray& condition, const NdArray& arr) + { + if (condition.size() != arr.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input arguments 'condition' and 'arr' must have the same size."); + } + + std::vector values; + for (decltype(arr.size()) i = 0; i < arr.size(); ++i) + { + if (condition[i]) + { + values.push_back(arr[i]); + } + } + + return NdArray(values.begin(), values.end()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/eye.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/eye.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d09d368937f7abcadb94d9e037c9d61254011c2c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/eye.hpp @@ -0,0 +1,123 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inN: number of rows (N) + /// @param inM: number of columns (M) + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(uint32 inN, uint32 inM, int32 inK = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inN, inM); + returnArray.zeros(); + + if (inK < 0) + { + uint32 col = 0; + for (uint32 row = inK; row < inN; ++row) + { + if (col >= inM) + { + break; + } + + returnArray(row, col++) = dtype{ 1 }; + } + } + else + { + uint32 row = 0; + for (uint32 col = inK; col < inM; ++col) + { + if (row >= inN) + { + break; + } + + returnArray(row++, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inN: number of rows and columns (N) + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(uint32 inN, int32 inK = 0) + { + return eye(inN, inN, inK); + } + + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inShape + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(const Shape& inShape, int32 inK = 0) + { + return eye(inShape.rows, inShape.cols, inK); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fillDiagnol.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fillDiagnol.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b3c89c9b50556308bbad49f9175048e7b320b380 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fillDiagnol.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Fill the main diagonal of the given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fill_diagonal.html + /// + /// @param inArray + /// @param inValue + /// + template + void fillDiagonal(NdArray& inArray, dtype inValue) noexcept + { + const auto inShape = inArray.shape(); + for (uint32 row = 0; row < inShape.rows; ++row) + { + if (row < inShape.cols) + { + inArray(row, row) = inValue; + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/find.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/find.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7ef6434f33b3145b20446c33e4672c8c72a87dc9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/find.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find flat indices of nonzero elements. + /// + /// @param mask: the mask to apply to the array + /// @param n: the first n indices to return (optional, default all) + /// + /// @return NdArray + /// + inline NdArray find(const NdArray& mask, uint32 n = std::numeric_limits::max()) + { + NdArray indices = mask.flatnonzero(); + + if (indices.size() <= n) + { + return indices; + } + + return indices[Slice(0, n)]; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fix.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fix.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fc98c9dddeb831c333ad329e627e8de09164b239 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fix.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round to nearest integer towards zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fix.html + /// + /// @param inValue + /// @return value + /// + template + dtype fix(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue > 0 ? std::floor(inValue) : std::ceil(inValue); + } + + //============================================================================ + // Method Description: + /// Round to nearest integer towards zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fix.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray fix(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> double { return fix(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatnonzero.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatnonzero.hpp new file mode 100644 index 0000000000000000000000000000000000000000..412020b8fef5befdf59e66014a238f4e6632091e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatnonzero.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return indices that are non-zero in the flattened version of a. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flatnonzero.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray flatnonzero(const NdArray& inArray) + { + return inArray.flatnonzero(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatten.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatten.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a9fe93765a1a7da5ae13fa74ae5070ec1d1bb25b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flatten.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a copy of the array collapsed into one dimension. + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray flatten(const NdArray& inArray) + { + return inArray.flatten(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flip.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flip.hpp new file mode 100644 index 0000000000000000000000000000000000000000..963822b8ae6280a14b528c93a38d5a3332c6c951 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flip.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Reverse the order of elements in an array along the given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flip.html + /// + /// @param inArray + /// @param inAxis + /// @return NdArray + /// + template + NdArray flip(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray(inArray); + stl_algorithms::reverse(returnArray.begin(), returnArray.end()); + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inArray); + for (uint32 row = 0; row < inArray.shape().rows; ++row) + { + stl_algorithms::reverse(returnArray.begin(row), returnArray.end(row)); + } + return returnArray; + } + case Axis::ROW: + { + return flip(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fliplr.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fliplr.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f841173da4b8f7a7043c2ffa2f1da70ee5f59a58 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fliplr.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flip array in the left/right direction. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fliplr.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray fliplr(const NdArray& inArray) + { + return flip(inArray, Axis::COL); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flipud.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flipud.hpp new file mode 100644 index 0000000000000000000000000000000000000000..506ba5ae7a5189bdf1c7600d4d60d036d1dba886 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/flipud.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flip array in the up/down direction. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flipud.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray flipud(const NdArray& inArray) + { + return flip(inArray, Axis::ROW); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor.hpp new file mode 100644 index 0000000000000000000000000000000000000000..54d02500b83d4179f359fc212d8cb3f9f2be2bfa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the floor of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor.html + /// + /// @param inValue + /// @return value + /// + template + dtype floor(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::floor(inValue); + } + + //============================================================================ + // Method Description: + /// Return the floor of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray floor(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return floor(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor_divide.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor_divide.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5da836187926fe943e8e4b33a28c05958c468918 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/floor_divide.hpp @@ -0,0 +1,71 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/floor.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the largest integer smaller or equal to the division of the inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor_divide.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype floor_divide(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::floor(inValue1 / inValue2); + } + + //============================================================================ + // Method Description: + /// Return the largest integer smaller or equal to the division of the inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor_divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray floor_divide(const NdArray& inArray1, const NdArray& inArray2) + { + return floor(inArray1 / inArray2); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..74a326cd03f415de0b8236b07aede3234859038e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmax.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// maximum of inputs. + /// + /// Compare two value and returns a value containing the + /// maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype fmax(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::max(inValue1, + inValue2, + [](const dtype value1, const dtype value2) noexcept -> bool { return value1 < value2; }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmax(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return fmax(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray fmax(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return fmax(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray fmax(const dtype& inScalar, const NdArray& inArray) + { + return fmax(inArray, inScalar); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d167ea1ac8d2ac176c63093490d1944a88bfd5f6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmin.hpp @@ -0,0 +1,127 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// minimum of inputs. + /// + /// Compare two value and returns a value containing the + /// minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype fmin(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::min(inValue1, + inValue2, + [](const dtype value1, const dtype value2) noexcept -> bool { return value1 < value2; }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmin(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return fmin(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray fmin(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return fmin(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray fmin(const dtype& inScalar, const NdArray& inArray) + { + return fmin(inArray, inScalar); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f1e5746955a6230e4ef6efffff0a17dca4d7a9fa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fmod.hpp @@ -0,0 +1,90 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template, int> = 0> + dtype fmod(dtype inValue1, dtype inValue2) noexcept + { + return inValue1 % inValue2; + } + + //============================================================================ + // Method Description: + /// Return the remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template, int> = 0> + dtype fmod(dtype inValue1, dtype inValue2) noexcept + { + return std::fmod(inValue1, inValue2); + } + + //============================================================================ + // Method Description: + /// Return the element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmod(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 % inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/frombuffer.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/frombuffer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..371679af3f8ec7553f70959e9dcf883cb1d0e4eb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/frombuffer.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Interpret a buffer as a 1-dimensional array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.frombuffer.html + /// + /// @param inBufferPtr + /// @param inNumBytes + /// @return NdArray + /// + template + NdArray frombuffer(const char* inBufferPtr, uint32 inNumBytes) + { + if (inNumBytes % sizeof(dtype) != 0) + { + THROW_INVALID_ARGUMENT_ERROR("inNumBytes % sizeof(dtype) != 0"); + } + + const auto numElements = static_cast(inNumBytes / sizeof(dtype)); + return NdArray(reinterpret_cast(inBufferPtr), numElements); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfile.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfile.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8f813583a551c9f3eb8840ef5a0e9beb15808f35 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfile.hpp @@ -0,0 +1,113 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fromstring.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array from data in a binary file. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromfile.html + /// + /// @param inFilename + /// @return NdArray + /// + template + NdArray fromfile(const std::string& inFilename) + { + if (!std::filesystem::exists(inFilename)) + { + THROW_INVALID_ARGUMENT_ERROR("input filename does not exist.\n\t" + inFilename); + } + + // read in as binary file + std::ifstream file(inFilename.c_str(), std::ios::in | std::ios::binary); + if (!file.is_open()) + { + THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename); + } + + file.seekg(0, std::ifstream::end); + const uint32 fileSize = static_cast(file.tellg()); + file.seekg(0, std::ifstream::beg); + + std::vector fileBuffer; + fileBuffer.reserve(fileSize); + file.read(fileBuffer.data(), fileSize); + + if (file.bad() || file.fail()) + { + THROW_INVALID_ARGUMENT_ERROR("error occured while reading the file"); + } + + file.close(); + + NdArray returnArray(reinterpret_cast(fileBuffer.data()), fileSize / sizeof(dtype)); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Construct an array from data in a text file. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromfile.html + /// + /// @param inFilename + /// @param inSep: Delimiter separator between values in the file + /// @return NdArray + /// + template + NdArray fromfile(const std::string& inFilename, const char inSep) + { + std::ifstream file(inFilename.c_str()); + if (!file.is_open()) + { + THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename); + } + + std::stringstream buffer; + buffer << file.rdbuf(); + file.close(); + + return fromstring(buffer.str(), inSep); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfunction.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfunction.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b5024bd62a19d2d767fa836d02c681813f5e145c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromfunction.hpp @@ -0,0 +1,115 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array by executing a function over each coordinate. + /// The resulting array therefore has a value fn(x) at coordinate(x). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html + /// + /// @param func: callable that accepts an integer coordinate and returns type T + /// @param size: the size of the 1d array to create + /// + /// @return NdArray + /// + template + NdArray fromfunction(const std::function::size_type)> func, + typename NdArray::size_type size) + { + NdArray result(1, size); + const auto indices = [size] + { + std::vector::size_type> temp(size); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + + stl_algorithms::transform(indices.begin(), + indices.end(), + result.begin(), + [&func](const auto idx) { return func(idx); }); + + return result; + } + + //============================================================================ + // Method Description: + /// Construct an array by executing a function over each coordinate. + /// The resulting array therefore has a value fn(x, y) at coordinate(x, y). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html + /// + /// @param func: callable that accepts an integer coordinate and returns type T + /// @param shape: the shape of the array to create + /// + /// @return NdArray + /// + template + NdArray fromfunction( + const std::function::size_type, typename NdArray::size_type)> func, + Shape shape) + { + NdArray result(shape); + const auto rows = [&shape] + { + std::vector::size_type> temp(shape.rows); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + const auto cols = [&shape] + { + std::vector::size_type> temp(shape.cols); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + + stl_algorithms::for_each(rows.begin(), + rows.end(), + [&cols, &result, &func](const auto row) + { + stl_algorithms::transform(cols.begin(), + cols.end(), + result.begin(row), + [&func, row](const auto col) { return func(row, col); }); + }); + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromiter.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromiter.hpp new file mode 100644 index 0000000000000000000000000000000000000000..45c9acc99f473dacef565137cdfe6a1ae382d892 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromiter.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Create a new 1-dimensional array from an iterable object. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromiter.html + /// + /// @param inBegin + /// @param inEnd + /// @return NdArray + /// + template + NdArray fromiter(Iter inBegin, Iter inEnd) + { + return NdArray(inBegin, inEnd); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromstring.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromstring.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ed7e35ef3ba09c73996e7f2607eb6e1b3da1fd0b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/fromstring.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array from data in a string + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromstring.html + /// + /// @param inStr + /// @param inSep: Delimiter separator between values in the string + /// @return NdArray + /// + template + NdArray fromstring(const std::string& inStr, const char inSep = ' ') + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::istringstream inputStream(inStr); + auto values = std::vector{}; + dtype value{}; + for (std::string segment; std::getline(inputStream, segment, inSep);) + { + if (!inputStream.fail()) + { + std::istringstream segmentStream(segment); + while (segmentStream >> value) + { + if (!inputStream.fail()) + { + values.push_back(value); + } + } + } + } + + return NdArray(values); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full.hpp new file mode 100644 index 0000000000000000000000000000000000000000..86115265a9c62fb2dc9f4bae0c5a42fee92c5388 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full.hpp @@ -0,0 +1,88 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inSquareSize + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(uint32 inSquareSize, dtype inFillValue) + { + NdArray returnArray(inSquareSize, inSquareSize); + returnArray.fill(inFillValue); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inNumRows + /// @param inNumCols + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(uint32 inNumRows, uint32 inNumCols, dtype inFillValue) + { + NdArray returnArray(inNumRows, inNumCols); + returnArray.fill(inFillValue); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inShape + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(const Shape& inShape, dtype inFillValue) + { + return full(inShape.rows, inShape.cols, inFillValue); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full_like.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full_like.hpp new file mode 100644 index 0000000000000000000000000000000000000000..503bb11d064751d00b8fd66ed6ea741e81ebc5a1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/full_like.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a full array with the same shape and type as a given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full_like.html + /// + /// @param inArray + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full_like(const NdArray& inArray, dtype inFillValue) + { + return full(inArray.shape(), inFillValue); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gcd.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gcd.hpp new file mode 100644 index 0000000000000000000000000000000000000000..10d16d6e6a0563711bf7ed6e58533cbc91c0b3ad --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gcd.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/integer/common_factor_rt.hpp" +#endif + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the greatest common divisor of |x1| and |x2|. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gcd.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return dtype + /// + template + dtype gcd(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + +#ifdef __cpp_lib_gcd_lcm + return std::gcd(inValue1, inValue2); +#else + return boost::integer::gcd(inValue1, inValue2); +#endif // #ifdef __cpp_lib_gcd_lcm + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Returns the greatest common divisor of the values in the + /// input array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gcd.html + /// + /// @param inArray + /// @return NdArray + /// + template + dtype gcd(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + return boost::integer::gcd_range(inArray.cbegin(), inArray.cend()).first; + } +#endif // #ifndef NUMCPP_NO_USE_BOOST +} // namespace nc + +#endif // defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/geomspace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/geomspace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..57ef78593209b173e8a4d1078256d09426d7f9f1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/geomspace.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/logb.hpp" +#include "NumCpp/Functions/logspace.hpp" +#include "NumCpp/Functions/nth_root.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return numbers spaced evenly on a log scale (a geometric progression). + /// + /// This is similar to logspace, but with endpoints specified directly. + /// Each output sample is a constant multiple of the previous. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html + /// + /// @param start: the starting value of a sequence + /// @param stop: The final value of the sequence, unless endpoint is False. + /// In that case, num + 1 values are spaced over the interval + /// in log-space, of which all but the last (a sequence of length num) are returned. + /// @param num: Number of samples to generate. Default 50. + /// @param endPoint: If true, stop is the last sample. Otherwide,it is not included. Default is true. + /// @return NdArray + /// + template + NdArray geomspace(dtype start, dtype stop, uint32 num = 50, bool endPoint = true) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (utils::essentiallyEqual(start, dtype{ 0 })) + { + THROW_INVALID_ARGUMENT_ERROR("Geometric sequence cannot include zero"); + } + + if (num == 1) + { + return { static_cast(start) }; + } + else if (num == 2 && endPoint) + { + return { static_cast(start), static_cast(stop) }; + } + + const auto base = nth_root(stop / start, num - 1); + const auto logStart = logb(start, base); + const auto logStop = logb(stop, base); + return logspace(logStart, logStop, num, endPoint, base); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gradient.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gradient.hpp new file mode 100644 index 0000000000000000000000000000000000000000..777a515d2338e74c8fab80ada1df3fd188fd5802 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/gradient.hpp @@ -0,0 +1,247 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the gradient of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gradient.html + /// + /// + /// @param inArray + /// @param inAxis (default ROW) + /// @return NdArray + /// + template + NdArray gradient(const NdArray& inArray, Axis inAxis = Axis::ROW) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::ROW: + { + const auto inShape = inArray.shape(); + if (inShape.rows < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 row."); + } + + // first do the first and last rows + auto returnArray = NdArray(inShape); + for (uint32 col = 0; col < inShape.cols; ++col) + { + returnArray(0, col) = static_cast(inArray(1, col)) - static_cast(inArray(0, col)); + returnArray(-1, col) = + static_cast(inArray(-1, col)) - static_cast(inArray(-2, col)); + } + + // then rip through the rest of the array + for (uint32 col = 0; col < inShape.cols; ++col) + { + for (uint32 row = 1; row < inShape.rows - 1; ++row) + { + returnArray(row, col) = + (static_cast(inArray(row + 1, col)) - static_cast(inArray(row - 1, col))) / + 2.; + } + } + + return returnArray; + } + case Axis::COL: + { + const auto inShape = inArray.shape(); + if (inShape.cols < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 columns."); + } + + // first do the first and last columns + auto returnArray = NdArray(inShape); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(row, 0) = static_cast(inArray(row, 1)) - static_cast(inArray(row, 0)); + returnArray(row, -1) = + static_cast(inArray(row, -1)) - static_cast(inArray(row, -2)); + } + + // then rip through the rest of the array + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 1; col < inShape.cols - 1; ++col) + { + returnArray(row, col) = + (static_cast(inArray(row, col + 1)) - static_cast(inArray(row, col - 1))) / + 2.; + } + } + + return returnArray; + } + default: + { + // will return the gradient of the flattened array + if (inArray.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 element."); + } + + auto returnArray = NdArray(1, inArray.size()); + returnArray[0] = static_cast(inArray[1]) - static_cast(inArray[0]); + returnArray[-1] = static_cast(inArray[-1]) - static_cast(inArray[-2]); + + stl_algorithms::transform(inArray.cbegin() + 2, + inArray.cend(), + inArray.cbegin(), + returnArray.begin() + 1, + [](dtype value1, dtype value2) -> double + { return (static_cast(value1) - static_cast(value2)) / 2.; }); + + return returnArray; + } + } + } + + //============================================================================ + // Method Description: + /// Return the gradient of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gradient.html + /// + /// + /// @param inArray + /// @param inAxis (default ROW) + /// @return NdArray + /// + template + NdArray> gradient(const NdArray>& inArray, Axis inAxis = Axis::ROW) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::ROW: + { + const auto inShape = inArray.shape(); + if (inShape.rows < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 row."); + } + + // first do the first and last rows + auto returnArray = NdArray>(inShape); + for (uint32 col = 0; col < inShape.cols; ++col) + { + returnArray(0, col) = complex_cast(inArray(1, col)) - complex_cast(inArray(0, col)); + returnArray(-1, col) = + complex_cast(inArray(-1, col)) - complex_cast(inArray(-2, col)); + } + + // then rip through the rest of the array + for (uint32 col = 0; col < inShape.cols; ++col) + { + for (uint32 row = 1; row < inShape.rows - 1; ++row) + { + returnArray(row, col) = (complex_cast(inArray(row + 1, col)) - + complex_cast(inArray(row - 1, col))) / + 2.; + } + } + + return returnArray; + } + case Axis::COL: + { + const auto inShape = inArray.shape(); + if (inShape.cols < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 columns."); + } + + // first do the first and last columns + auto returnArray = NdArray>(inShape); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(row, 0) = complex_cast(inArray(row, 1)) - complex_cast(inArray(row, 0)); + returnArray(row, -1) = + complex_cast(inArray(row, -1)) - complex_cast(inArray(row, -2)); + } + + // then rip through the rest of the array + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 1; col < inShape.cols - 1; ++col) + { + returnArray(row, col) = (complex_cast(inArray(row, col + 1)) - + complex_cast(inArray(row, col - 1))) / + 2.; + } + } + + return returnArray; + } + default: + { + // will return the gradient of the flattened array + if (inArray.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 element."); + } + + auto returnArray = NdArray>(1, inArray.size()); + returnArray[0] = complex_cast(inArray[1]) - complex_cast(inArray[0]); + returnArray[-1] = complex_cast(inArray[-1]) - complex_cast(inArray[-2]); + + stl_algorithms::transform( + inArray.cbegin() + 2, + inArray.cend(), + inArray.cbegin(), + returnArray.begin() + 1, + [](const std::complex& value1, const std::complex& value2) -> std::complex + { return (complex_cast(value1) - complex_cast(value2)) / 2.; }); + + return returnArray; + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater.hpp new file mode 100644 index 0000000000000000000000000000000000000000..37b6caf49e3b4e7fe41689f9e2d3d3ad424bc707 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 > x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray greater(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 > inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater_equal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater_equal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..47fccbc49e7859b8fc161f5cfae4fd1936cf09de --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/greater_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 >= x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater_equal.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray greater_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 >= inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hamming.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hamming.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fee9d5ec465875bbf69351adb7f832624678357f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hamming.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the Hamming window. + /// + /// The Hamming window is a taper formed by using a weighted cosine. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hamming.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray hamming(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto twoPiDivMMinus1 = (2. * constants::pi) / (mDouble - 1.); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = 0.54 - 0.46 * std::cos(twoPiDivMMinus1 * n); + } + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hammingEncode.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hammingEncode.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6272b6b9344733db14a0bb10277ba3faa6f1260d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hammingEncode.hpp @@ -0,0 +1,396 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Hamming EDAC encoding https://en.wikipedia.org/wiki/Hamming_code +/// + +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include +#include +#include + +#include "boost/dynamic_bitset.hpp" + +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::edac +{ + namespace detail + { + //============================================================================ + // Method Description: + /// @brief Tests if value is a power of two + /// + /// @param n integer value + /// @return bool true if value is a power of two, else false + /// + template, int> = 0> + constexpr bool isPowerOfTwo(IntType n) noexcept + { + // Returns true if the given non-negative integer n is a power of two. + return n != 0 && (n & (n - 1)) == 0; + } + + //============================================================================ + // Method Description: + /// Calculates the next power of two after n + /// >>> _next_power_of_two(768) + /// 1024 + /// >>> _next_power_of_two(4) + /// 8 + /// + /// @param n integer value + /// @return next power of two + /// @exception std::invalid_argument if input value is less than zero + //// + template, int> = 0> + std::size_t nextPowerOfTwo(IntType n) + { + if (n < 0) + { + throw std::invalid_argument("Input value must be greater than or equal to zero."); + } + + if (isPowerOfTwo(n)) + { + return static_cast(n) << 1; + } + + return static_cast(std::pow(2, std::ceil(std::log2(n)))); + } + + //============================================================================ + // Method Description: + /// Calculates the first n powers of two + /// + /// @param n integer value + /// @return first n powers of two + /// @exception std::bad_alloc if unable to allocate for return vector + /// + template, int> = 0> + std::vector powersOfTwo(IntType n) + { + auto i = std::size_t{ 0 }; + auto power = std::size_t{ 1 }; + auto powers = std::vector(); + powers.reserve(n); + + while (i < static_cast(n)) + { + powers.push_back(power); + power <<= 1; + ++i; + } + + return powers; + } + + //============================================================================ + // Method Description: + /// Calculates the number of needed Hamming SECDED parity bits to encode the data + /// + /// @param numDataBits the number of data bits to encode + /// @return number of Hamming SECDED parity bits + /// @exception std::invalid_argument if input value is less than zero + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + std::size_t numSecdedParityBitsNeeded(IntType numDataBits) + { + const auto n = nextPowerOfTwo(numDataBits); + const auto lowerBin = static_cast(std::floor(std::log2(n))); + const auto upperBin = lowerBin + 1; + const auto dataBitBoundary = n - lowerBin - 1; + const auto numParityBits = numDataBits <= dataBitBoundary ? lowerBin + 1 : upperBin + 1; + + if (!isPowerOfTwo(numParityBits + numDataBits)) + { + throw std::runtime_error("input number of data bits is not a valid Hamming SECDED code configuration."); + } + + return numParityBits; + } + + //============================================================================ + // Method Description: + /// Returns the indices of all data bits covered by a specified parity bit in a bitstring + /// of length numDataBits. The indices are relative to DATA BITSTRING ITSELF, NOT including + /// parity bits. + /// + /// @param numDataBits the number of data bits to encode + /// @param parityBit the parity bit number + /// @return number of Hamming SECDED parity bits + /// @exception std::invalid_argument if parityBit is not a power of two + /// @exception std::bad_alloc if unable to allocate return vector + /// + template, int> = 0, + std::enable_if_t, int> = 0> + std::vector dataBitsCovered(IntType1 numDataBits, IntType2 parityBit) + { + if (!isPowerOfTwo(parityBit)) + { + throw std::invalid_argument("All hamming parity bits are indexed by powers of two."); + } + + std::size_t dataIndex = 1; // bit we're currently at in the DATA bitstring + std::size_t totalIndex = 3; // bit we're currently at in the OVERALL bitstring + auto parityBit_ = static_cast(parityBit); + + auto indices = std::vector(); + indices.reserve(numDataBits); // worst case + + while (dataIndex <= static_cast(numDataBits)) + { + const auto currentBitIsData = !isPowerOfTwo(totalIndex); + if (currentBitIsData && (totalIndex % (parityBit_ << 1)) >= parityBit_) + { + indices.push_back(dataIndex - 1); // adjust output to be zero indexed + } + + dataIndex += currentBitIsData ? 1 : 0; + ++totalIndex; + } + + return indices; + } + + //============================================================================ + // Method Description: + /// Calculates the overall parity of the data, assumes last bit is the parity bit itself + /// + /// @param data the data word + /// @return overall parity bit value + /// + template + constexpr bool calculateParity(const std::bitset& data) noexcept + { + bool parity = false; + for (std::size_t i = 0; i < DataBits - 1; ++i) + { + parity ^= data[i]; + } + + return parity; + } + + //============================================================================ + // Method Description: + /// Calculates the overall parity of the data, assumes last bit is the parity bit itself + /// + /// @param data the data word + /// @return overall parity bit value + /// + inline bool calculateParity(const boost::dynamic_bitset<>& data) noexcept + { + bool parity = false; + for (std::size_t i = 0; i < data.size() - 1; ++i) + { + parity ^= data[i]; + } + + return parity; + } + + //============================================================================ + // Method Description: + /// Calculates the specified Hamming parity bit (1, 2, 4, 8, etc.) for the given data. + /// Assumes even parity to allow for easier computation of parity using XOR. + /// + /// @param data the data word + /// @param parityBit the parity bit number + /// @return parity bit value + /// @exception std::invalid_argument if parityBit is not a power of two + /// @exception std::bad_alloc if unable to allocate return vector + /// + template, int> = 0> + bool calculateParity(const std::bitset& data, IntType parityBit) + { + const auto bitsCovered = dataBitsCovered(DataBits, parityBit); + return std::accumulate(bitsCovered.begin(), + bitsCovered.end(), + false, + [&data](bool parity, const auto value) noexcept -> bool { return parity ^= value; }); + } + + //============================================================================ + // Method Description: + /// Checks that the number of DataBits and EncodedBits are consistent + /// + /// @return the number of parity bits + /// @exception std::runtime_error if DataBits and EncodedBits are not consistent + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + std::size_t checkBitsConsistent() + { + const auto numParityBits = detail::numSecdedParityBitsNeeded(DataBits); + if (numParityBits + DataBits != EncodedBits) + { + throw std::runtime_error("DataBits and EncodedBits are not consistent"); + } + + return numParityBits; + } + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED decoded bits from the endoded bits. Assumes that the + /// DataBits and EncodedBits have been checks for consistancy already + /// + /// @param encodedBits the Hamming SECDED encoded word + /// @return data bits from the encoded word + /// + template, int> = 0> + std::bitset extractData(const std::bitset& encodedBits) noexcept + { + auto dataBits = std::bitset(); + + std::size_t dataIndex = 0; + for (std::size_t encodedIndex = 0; encodedIndex < EncodedBits; ++encodedIndex) + { + if (!isPowerOfTwo(encodedIndex + 1)) + { + dataBits[dataIndex++] = encodedBits[encodedIndex]; + if (dataIndex == DataBits) + { + break; + } + } + } + + return dataBits; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED encoded bits for the data bits + /// + /// @param dataBits the data bits to encode + /// @return encoded data bits + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template + boost::dynamic_bitset<> encode(const std::bitset& dataBits) + { + const auto numParityBits = detail::numSecdedParityBitsNeeded(DataBits); + const auto numEncodedBits = numParityBits + DataBits; + + auto encodedBits = boost::dynamic_bitset<>(numEncodedBits); // NOLINT(google-readability-casting) + + // set the parity bits + for (const auto parityBit : + detail::powersOfTwo(numParityBits - 1)) // -1 because overall parity will be calculated seperately later + { + encodedBits[parityBit - 1] = detail::calculateParity(dataBits, parityBit); + } + + // set the data bits, switch to 1 based to make things easier for isPowerOfTwo + std::size_t dataBitIndex = 0; + for (std::size_t bitIndex = 1; bitIndex <= numEncodedBits - 1; + ++bitIndex) // -1 to account for the overall parity bit + { + if (!detail::isPowerOfTwo(bitIndex)) + { + encodedBits[bitIndex - 1] = dataBits[dataBitIndex++]; + } + } + + // compute and set overall parity for the entire encoded data (not including the overall parity bit itself) + encodedBits[numEncodedBits - 1] = detail::calculateParity(encodedBits); // overall parity at the end + + // all done! + return encodedBits; + } + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED decoded bits for the enocoded bits + /// https://en.wikipedia.org/wiki/Hamming_code + /// + /// @param encodedBits the encoded bits to decode + /// @param decodedBits the output decoded bits + /// @return int status (0=no errors, 1=1 corrected error, 2=2 errors detected) + /// @exception std::runtime_error if DataBits and EncodedBits are not consistent + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + int decode(std::bitset encodedBits, std::bitset& decodedBits) + { + const auto numParityBits = detail::checkBitsConsistent(); + + // the data bits, which may be corrupted + decodedBits = detail::extractData(encodedBits); + + // check the overall parity bit + const auto overallExpected = detail::calculateParity(encodedBits); + const auto overallActual = encodedBits[EncodedBits - 1]; + const auto overallCorrect = overallExpected == overallActual; + + // check individual parities - each parity bit's index (besides overall parity) is a power of two + std::size_t indexOfError = 0; + for (const auto parityBit : detail::powersOfTwo(numParityBits - 1)) + { + const auto expected = detail::calculateParity(decodedBits, parityBit); + const auto actual = encodedBits[parityBit - 1]; // -1 because parityBit is 1 based + if (expected != actual) + { + indexOfError += parityBit; + } + } + + // attempt to repair a single flipped bit or throw exception if more than one + if (overallCorrect && indexOfError != 0) + { + // two errors found + return 2; + } + else if (!overallCorrect && indexOfError != 0) + { + // one error found, flip the bit in error and we're good + encodedBits.flip(indexOfError - 1); + decodedBits = detail::extractData(encodedBits); + return 1; + } + + return 0; + } +} // namespace nc::edac +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hanning.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hanning.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cc7586839347add6b1c3567586f26be14098794a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hanning.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the Hamming window. + /// + /// The Hanning window is a taper formed by using a weighted cosine. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hanning.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray hanning(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto twoPiDivMMinus1 = (2. * constants::pi) / (mDouble - 1.); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = 0.5 - 0.5 * std::cos(twoPiDivMMinus1 * n); + } + + return result; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/histogram.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/histogram.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6be744d2dd38c913fb1558708b1d10b69a33e008 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/histogram.hpp @@ -0,0 +1,142 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the histogram of a set of data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.histogram.html + /// + /// + /// @param inArray + /// @param inBinEdges: monotonically increasing array of bin edges, including the + /// rightmost edge, allowing for non-uniform bin widths. + /// + /// @return array of histogram counts + /// + template + NdArray histogram(const NdArray& inArray, const NdArray& inBinEdges) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inBinEdges.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("number of bin edges must be >= 2."); + } + + // sort just in case the user hasn't already + const auto binEdges = sort(inBinEdges); + + NdArray histo = zeros(1, binEdges.size() - 1); + for (const auto value : inArray) + { + if (value < binEdges.front() || value > binEdges.back()) + { + continue; + } + + // binary search to find the bin idx + constexpr bool keepSearching = true; + uint32 lowIdx = 0; + uint32 highIdx = binEdges.size() - 1; + while (keepSearching) + { + const uint32 idx = (lowIdx + highIdx) / 2; // integer division + if (lowIdx == highIdx || lowIdx == highIdx - 1) + { + // we found the bin + ++histo[lowIdx]; + break; + } + + if (value > binEdges[idx]) + { + lowIdx = idx; + } + else if (value < binEdges[idx]) + { + highIdx = idx; + } + else + { + // we found the bin + ++histo[idx]; + break; + } + } + } + + return histo; + } + + //============================================================================ + // Method Description: + /// Compute the histogram of a set of data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.histogram.html + /// + /// + /// @param inArray + /// @param inNumBins( default 10) + /// + /// @return std::pair of NdArrays; first is histogram counts, seconds is the bin edges + /// + template + std::pair, NdArray> histogram(const NdArray& inArray, uint32 inNumBins = 10) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inNumBins == 0) + { + THROW_INVALID_ARGUMENT_ERROR("number of bins must be positive."); + } + + constexpr bool useEndPoint = true; + const NdArray binEdges = linspace(static_cast(inArray.min().item()), + static_cast(inArray.max().item()), + inNumBins + 1, + useEndPoint); + + const auto histo = histogram(inArray, binEdges); + return std::make_pair(histo, binEdges); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hsplit.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hsplit.hpp new file mode 100644 index 0000000000000000000000000000000000000000..347a274e4cd7e5aa484df43f1d831b41b8f52240 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hsplit.hpp @@ -0,0 +1,107 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays horizontal (column-wise). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html + /// + /// @param inArray + /// @param indices: the indices to split + /// + /// @return NdArray + /// + template = 0> + std::vector> hsplit(const NdArray& inArray, const Indices& indices) + { + const auto numCols = static_cast(inArray.numCols()); + NdArray uniqueIndices(1, indices.size()); + stl_algorithms::transform(indices.begin(), + indices.end(), + uniqueIndices.begin(), + [numCols](auto index) noexcept -> int32 + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index = std::max(index + numCols, int32{ 0 }); + } + } + if (static_cast(index) > numCols - 1) + { + index = numCols - 1; + } + + return static_cast(index); + }); + uniqueIndices = unique(uniqueIndices); + + std::vector> splits{}; + splits.reserve(uniqueIndices.size() + 1); + + const auto rSlice = inArray.rSlice(); + int32 lowerIdx = 0; + for (const auto index : uniqueIndices) + { + if (index == 0) + + { + splits.push_back(NdArray(Shape(inArray.numRows(), 0))); + continue; + } + else + { + splits.push_back(inArray(rSlice, Slice(lowerIdx, index))); + } + + lowerIdx = index; + } + + if (lowerIdx < numCols - 1) + { + splits.push_back(inArray(rSlice, Slice(lowerIdx, numCols))); + } + else + { + splits.push_back(inArray(rSlice, -1)); + } + + return splits; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hstack.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hstack.hpp new file mode 100644 index 0000000000000000000000000000000000000000..098cdf33f5b0ae6d64b1e17bb2c9fc3b72ee2f9a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hstack.hpp @@ -0,0 +1,71 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Stack arrays in sequence horizontally (column wise). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hstack.html + /// + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray hstack(std::initializer_list> inArrayList) + { + return detail::column_stack(inArrayList.begin(), inArrayList.end()); + } + + //============================================================================ + // Method Description: + /// Stack arrays in sequence horizontally (column wise). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hstack.html + /// + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray hstack(std::vector> inArrayList) + { + return detail::column_stack(inArrayList.begin(), inArrayList.end()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hypot.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hypot.hpp new file mode 100644 index 0000000000000000000000000000000000000000..13279f66a60c20247bee91b04e497aa14832c1bf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/hypot.hpp @@ -0,0 +1,146 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return value + /// + template + double hypot(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::hypot(static_cast(inValue1), static_cast(inValue2)); + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2 + x3**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @param inValue3 + /// + /// @return value + /// + template + double hypot(dtype inValue1, dtype inValue2, dtype inValue3) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_hypot + return std::hypot(static_cast(inValue1), static_cast(inValue2), static_cast(inValue3)); +#else + return std::sqrt(utils::sqr(static_cast(inValue1)) + utils::sqr(static_cast(inValue2)) + + utils::sqr(static_cast(inValue3))); +#endif + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray hypot(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> double + { return hypot(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @param inArray3 + /// + /// @return NdArray + /// + template + NdArray + hypot(const NdArray& inArray1, const NdArray& inArray2, const NdArray& inArray3) + { + if (inArray1.size() != inArray2.size() || inArray1.size() != inArray3.size()) + { + THROW_INVALID_ARGUMENT_ERROR("input array sizes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + for (typename NdArray::size_type i = 0; i < inArray1.size(); ++i) + { + returnArray[i] = hypot(inArray1[i], inArray2[i], inArray3[i]); + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/identity.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/identity.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ad77c35edfea86747b8c4e6476a5f90114a56e7e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/identity.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the identity array. + /// + /// The identity array is a square array with ones on the main diagonal. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.identity.html + /// + /// @param inSquareSize + /// + /// @return NdArray + /// + template + NdArray identity(uint32 inSquareSize) + { + NdArray returnArray(inSquareSize); + returnArray.zeros(); + for (uint32 i = 0; i < inSquareSize; ++i) + { + returnArray(i, i) = dtype{ 1 }; + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/imag.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/imag.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d65211df78d0a496359216dd252c088623b7f847 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/imag.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the imaginar part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.imag.html + /// + /// @param inValue + /// @return value + /// + template + auto imag(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::imag(inValue); + } + + //============================================================================ + // Method Description: + /// Return the imaginary part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.imag.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto imag(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::imag(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/inner.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/inner.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4f240224b821c5c3cbb330a074f4cc3198e36eed --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/inner.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Inner product of two 1-D arrays. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.inner.html + /// + /// @param a: array 1 + /// @param b: array 2 + /// @return NdArray + /// + template + dtype inner(const NdArray& a, const NdArray& b) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (a.size() != b.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'a' and 'b' must have the same size"); + } + + return std::inner_product(a.cbegin(), a.cend(), b.cbegin(), dtype{ 0 }); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/insert.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/insert.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3ab350ad272b0ba851e47088280dec3ef12bf1fc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/insert.hpp @@ -0,0 +1,551 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/ones_like.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Insert values before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the value before in the flattened + /// @param value: value to insert + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const dtype& value) + { + const NdArray values = { value }; + return insert(arr, index, values); + } + + //============================================================================ + // Method Description: + /// Insert values before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before in the flattened + /// @param values: value to insert + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const NdArray& values) + { + if (index < 0) + { + index += arr.size(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.size())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + const auto valuesSlice = Slice(index, index + values.size()); + auto result = NdArray(1, arr.size() + values.size()); + result.put(valuesSlice, values); + + NdArray mask(result.shape()); + mask.fill(true); + mask.put(valuesSlice, false); + result.putMask(mask, arr.flatten()); + + return result; + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before + /// @param value: value to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const dtype& value, Axis axis) + { + const NdArray values = { value }; + return insert(arr, index, values, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const NdArray& values, Axis axis) + { + switch (axis) + { + case Axis::NONE: + { + return insert(arr, index, values); + } + case Axis::ROW: + { + if (!(values.size() == arr.numCols() || values.isscalar() || values.numCols() == arr.numCols())) + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + if (index < 0) + { + index += arr.numRows(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.numRows())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + auto result = NdArray(); + int32 valuesSize{}; + if (values.size() == arr.numCols() || values.isscalar()) + { + result.resizeFast(arr.numRows() + 1, arr.numCols()); + valuesSize = 1; + } + else if (values.numCols() == arr.numCols()) + { + result.resizeFast(arr.numRows() + values.numRows(), arr.numCols()); + valuesSize = values.numRows(); + } + + auto mask = ones_like(result); + mask.put(Slice(index, index + valuesSize), mask.cSlice(), false); + + result.putMask(mask, arr); + result.putMask(!mask, values); + + return result; + } + case Axis::COL: + { + if (!(values.size() == arr.numRows() || values.isscalar() || values.numRows() == arr.numRows())) + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + if (index < 0) + { + index += arr.numCols(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.numCols())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + auto result = NdArray(); + int32 valuesSize{}; + if (values.size() == arr.numRows() || values.isscalar()) + { + result.resizeFast(arr.numRows(), arr.numCols() + 1); + valuesSize = 1; + } + else if (values.numRows() == arr.numRows()) + { + result.resizeFast(arr.numRows(), arr.numCols() + values.numCols()); + valuesSize = values.numCols(); + } + + auto mask = ones_like(result); + mask.put(mask.rSlice(), Slice(index, index + valuesSize), false); + + result.putMask(mask, arr); + result.putMask(!mask, values); + + return result; + } + default: + { + // get rid of compiler warning + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param indices: indices to insert the values before + /// @param value: value to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template = 0> + NdArray insert(const NdArray& arr, const Indices& indices, const dtype& value, Axis axis = Axis::NONE) + { + const NdArray values = { value }; + return insert(arr, indices, values, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param slice: slice to insert the values before + /// @param value: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, Slice slice, const dtype& value, Axis axis = Axis::NONE) + { + auto sliceIndices = slice.toIndices(arr.dimSize(axis)); + return insert(arr, NdArray(sliceIndices.data(), sliceIndices.size(), false), value, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param indices: indices to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template = 0> + NdArray + insert(const NdArray& arr, const Indices& indices, const NdArray& values, Axis axis = Axis::NONE) + { + const auto isScalarValue = values.isscalar(); + + switch (axis) + { + case Axis::NONE: + { + if (!isScalarValue && indices.size() != values.size()) + { + THROW_INVALID_ARGUMENT_ERROR("could not broadcast values into indices"); + } + + const auto arrSize = static_cast(arr.size()); + + std::vector> indexValues(indices.size()); + if (isScalarValue) + { + const auto value = values.front(); + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrSize, value](auto index) -> std::pair + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrSize; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrSize) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), value); + }); + } + else + { + stl_algorithms::transform(indices.begin(), + indices.end(), + values.begin(), + indexValues.begin(), + [arrSize](auto index, const auto& value) -> std::pair + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrSize; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrSize) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), value); + }); + } + + stl_algorithms::sort(indexValues.begin(), + indexValues.end(), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first < indexValue2.first; }); + auto indexValuesUnique = std::vector{}; + std::unique_copy(indexValues.begin(), + indexValues.end(), + std::back_inserter(indexValuesUnique), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first == indexValue2.first; }); + + auto result = NdArray(1, arr.size() + indexValuesUnique.size()); + + auto mask = ones_like(result); + int32 counter = 0; + std::for_each(indexValuesUnique.begin(), + indexValuesUnique.end(), + [&counter, &mask](auto& indexValue) noexcept -> void + { mask[indexValue.first + counter++] = false; }); + + result.putMask(mask, arr); + + auto valuesSorted = [&indexValuesUnique] + { + std::vector values_; + values_.reserve(indexValuesUnique.size()); + std::transform(indexValuesUnique.begin(), + indexValuesUnique.end(), + std::back_inserter(values_), + [](const auto& indexValue) { return indexValue.second; }); + return values_; + }(); + + result.putMask(!mask, NdArray(valuesSorted.data(), valuesSorted.size(), false)); + + return result; + } + case Axis::ROW: + { + const auto arrNumRows = static_cast(arr.numRows()); + + std::vector>> indexValues(indices.size()); + if (values.isscalar()) + { + const auto value = values.front(); + auto valueRow = NdArray(1, arr.numCols()); + valueRow.fill(value); + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &valueRow](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), valueRow); + }); + } + else if (values.size() == arr.numCols()) + { + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &values](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), values); + }); + } + else if (values.numCols() == arr.numCols() && values.numRows() == indices.size()) + { + int32 counter = 0; + std::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &values, &counter](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), + values(counter++, values.cSlice())); + }); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + stl_algorithms::sort(indexValues.begin(), + indexValues.end(), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first < indexValue2.first; }); + auto indexValuesUnique = std::vector{}; + std::unique_copy(indexValues.begin(), + indexValues.end(), + std::back_inserter(indexValuesUnique), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first == indexValue2.first; }); + + auto result = NdArray(arrNumRows + indexValuesUnique.size(), arr.numCols()); + + auto mask = ones_like(result); + int32 counter = 0; + std::for_each(indexValuesUnique.begin(), + indexValuesUnique.end(), + [&counter, &mask](auto& indexValue) noexcept -> void + { mask.put(indexValue.first + counter++, mask.cSlice(), false); }); + + result.putMask(mask, arr); + + counter = 0; + for (const auto& [index, values_] : indexValuesUnique) + { + result.put(index + counter++, result.cSlice(), values_); + } + + return result; + } + case Axis::COL: + { + return insert(arr.transpose(), indices, values.transpose(), Axis::ROW).transpose(); + } + default: + { + // get rid of compiler warning + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param slice: slice to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, Slice slice, const NdArray& values, Axis axis = Axis::NONE) + { + auto sliceIndices = slice.toIndices(arr.dimSize(axis)); + return insert(arr, NdArray(sliceIndices.data(), sliceIndices.size(), false), values, axis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/interp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/interp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..72afb1831999b78dfe084b7d24507921cd777782 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/interp.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/interp.hpp" + +namespace nc +{ + //============================================================================ + /// Returns the linear interpolation between two points + /// + /// @param inValue1 + /// @param inValue2 + /// @param inPercent + /// + /// @return linear interpolated point + /// + template + constexpr double interp(dtype inValue1, dtype inValue2, double inPercent) noexcept + { + return utils::interp(inValue1, inValue2, inPercent); + } + + //============================================================================ + // Method Description: + /// One-dimensional linear interpolation. + /// + /// Returns the one - dimensional piecewise linear interpolant + /// to a function with given values at discrete data - points. + /// If input arrays are not one dimensional they will be + /// internally flattened. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.interp.html + /// + /// @param inX: The x-coordinates at which to evaluate the interpolated values. + /// @param inXp: The x-coordinates of the data points, must be increasing. Otherwise, xp is internally sorted. + /// @param inFp: The y-coordinates of the data points, same length as inXp. + /// + /// @return NdArray + /// + template + NdArray interp(const NdArray& inX, const NdArray& inXp, const NdArray& inFp) + { + // do some error checking first + if (inXp.size() != inFp.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inXp and inFp need to be the same size()."); + } + + if (inX.min().item() < inXp.min().item() || inX.max().item() > inXp.max().item()) + { + THROW_INVALID_ARGUMENT_ERROR("endpoints of inX should be contained within inXp."); + } + + // sort the input inXp and inFp data + NdArray sortedXpIdxs = argsort(inXp); + NdArray sortedXp(1, inFp.size()); + NdArray sortedFp(1, inFp.size()); + uint32 counter = 0; + for (auto sortedXpIdx : sortedXpIdxs) + { + sortedXp[counter] = inXp[sortedXpIdx]; + sortedFp[counter++] = inFp[sortedXpIdx]; + } + + // get the sorted input inX array indices + NdArray sortedXIdxs = argsort(inX); + + NdArray returnArray(1, inX.size()); + + uint32 currXpIdx = 0; + uint32 currXidx = 0; + while (currXidx < inX.size()) + { + const auto sortedXIdx = sortedXIdxs[currXidx]; + const auto x = inX[sortedXIdx]; + const auto xPLow = sortedXp[currXpIdx]; + const auto xPHigh = sortedXp[currXpIdx + 1]; + const auto fPLow = sortedFp[currXpIdx]; + const auto fPHigh = sortedFp[currXpIdx + 1]; + + if (xPLow <= x && x <= xPHigh) + { + const double percent = static_cast(x - xPLow) / static_cast(xPHigh - xPLow); + returnArray[sortedXIdx] = utils::interp(fPLow, fPHigh, percent); + ++currXidx; + } + else + { + ++currXpIdx; + } + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/intersect1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/intersect1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b1a0f36777f000a9b1659af53514846b110ae5cb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/intersect1d.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the intersection of two arrays. + /// + /// Return the sorted, unique values that are in both of the input arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.intersect1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray intersect1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::vector res(inArray1.size() + inArray2.size()); + const std::set in1(inArray1.cbegin(), inArray1.cend()); + const std::set in2(inArray2.cbegin(), inArray2.cend()); + + const auto iter = stl_algorithms::set_intersection(in1.begin(), in1.end(), in2.begin(), in2.end(), res.begin()); + res.resize(iter - res.begin()); + return NdArray(res); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/invert.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/invert.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c4384811a2e82abf7138a829ca72284d8168a118 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/invert.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute bit-wise inversion, or bit-wise NOT, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.invert.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray invert(const NdArray& inArray) + { + return ~inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isclose.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isclose.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d62f75e112188ef87c66434dc46e7822e448a169 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isclose.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a boolean array where two arrays are element-wise + /// equal within a tolerance. + /// + /// For finite values, isclose uses the following equation to test whether two floating point values are equivalent. + /// absolute(a - b) <= (atol + rtol * absolute(b)) + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isclose.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inRtol: relative tolerance (default 1e-5) + /// @param inAtol: absolute tolerance (default 1e-9) + /// + /// @return NdArray + /// + template + NdArray isclose(const NdArray& inArray1, + const NdArray& inArray2, + double inRtol = 1e-05, + double inAtol = 1e-08) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [inRtol, inAtol](dtype inValueA, dtype inValueB) noexcept -> bool + { return std::abs(inValueA - inValueB) <= (inAtol + inRtol * std::abs(inValueB)); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isinf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isinf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d963c96cca9e13ab7b4761e6a0d8faafa0e9cc65 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isinf.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isinf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isinf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isinf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isinf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isinf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isnan.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isnan.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bcc6ec4cb0733d1a664c03fc79094a5a5748934a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isnan.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for NaN and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isnan.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isnan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (DtypeInfo::isInteger()) + { + return false; + } + + return std::isnan(static_cast(inValue)); // static_cast is needed for compiler error + } + + //============================================================================ + // Method Description: + /// Test element-wise for NaN and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isnan.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isnan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isnan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isneginf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isneginf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c91b28c326bdb93e31d425dd3dd35a117901324d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isneginf.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for negative inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isneginf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isneginf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return inValue < 0 && std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for negative inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isneginf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isneginf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isneginf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isposinf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isposinf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..09030cd87cef19f89dc07da57cd3f3080da630f2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/isposinf.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for positive inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isposinf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isposinf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return inValue > 0 && std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for positive inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isposinf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isposinf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isposinf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/kaiser.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/kaiser.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6ceb6c57eaf163418aca140923b89c6475912796 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/kaiser.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/bessel_in.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Kaiser window is a taper formed by using a Bessel function. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.kaiser.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @param beta: shape parameter for the window + /// @return NdArray + /// + inline NdArray kaiser(int32 m, double beta) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto mMinus1 = mDouble - 1.; + const auto mMinus1Over2 = mMinus1 / 2.; + const auto mMinus1Squared = utils::sqr(mMinus1); + const auto i0Beta = special::bessel_in(0, beta); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(-mMinus1Over2, mMinus1Over2, m, true)) + { + auto value = beta * std::sqrt(1. - (4. * utils::sqr(n)) / mMinus1Squared); + result[i++] = special::bessel_in(0, value) / i0Beta; + } + + return result; + } +} // namespace nc + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/lcm.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/lcm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..aca751566b856ed475019a07382209a97240e7b8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/lcm.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/integer/common_factor_rt.hpp" +#endif + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the least common multiple of |x1| and |x2|. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.lcm.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return dtype + /// + template + dtype lcm(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + +#ifdef __cpp_lib_gcd_lcm + return std::lcm(inValue1, inValue2); +#else + return boost::integer::lcm(inValue1, inValue2); +#endif + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Returns the least common multiple of the values of the input array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.lcm.html + /// + /// @param inArray + /// @return NdArray + /// + template + dtype lcm(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + + return boost::integer::lcm_range(inArray.cbegin(), inArray.cend()).first; + } +#endif // #ifndef NUMCPP_NO_USE_BOOST +} // namespace nc + +#endif // #if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ldexp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ldexp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9d616977aa1883592b0cf39d9568be934141d64e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ldexp.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns x1 * 2^x2. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ldexp.html + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return value + /// + template + dtype ldexp(dtype inValue1, uint8 inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::ldexp(static_cast(inValue1), inValue2)); + } + + //============================================================================ + // Method Description: + /// Returns x1 * 2^x2, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ldexp.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray ldexp(const NdArray& inArray1, const NdArray& inArray2) + { + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [](dtype inValue1, uint8 inValue2) noexcept -> dtype + { return ldexp(inValue1, inValue2); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/left_shift.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/left_shift.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bb91fd645c05a033f3d94803e18391434100c745 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/left_shift.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Shift the bits of an integer to the left. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.left_shift.html + /// + /// @param inArray + /// @param inNumBits + /// + /// @return NdArray + /// + template + NdArray left_shift(const NdArray& inArray, uint8 inNumBits) + { + return inArray << inNumBits; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less.hpp new file mode 100644 index 0000000000000000000000000000000000000000..38d7ea81acffe80af5e552c8b9a832446c23be4f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 < x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.less.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray less(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 < inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less_equal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less_equal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a3f1920d57223964dc6699d276660891b44da30a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/less_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 <= x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.less_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray less_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 <= inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/linspace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/linspace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..563ca5b140f93265a6a96164efb33080d39e60ac --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/linspace.hpp @@ -0,0 +1,121 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return evenly spaced numbers over a specified interval. + /// + /// Returns num evenly spaced samples, calculated over the + /// interval[start, stop]. + /// + /// The endpoint of the interval can optionally be excluded. + /// + /// Mostly only usefull if called with a floating point type + /// for the template argument. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.linspace.html + /// + /// @param inStart + /// @param inStop + /// @param inNum: number of points (default = 50) + /// @param endPoint: include endPoint (default = true) + /// + /// @return NdArray + /// + template + NdArray linspace(dtype inStart, dtype inStop, uint32 inNum = 50, bool endPoint = true) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inNum == 0) + { + return NdArray(0); + } + + if (inNum == 1) + { + NdArray returnArray = { inStart }; + return returnArray; + } + + if (inStop <= inStart) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must be greater than the start value."); + } + + if (endPoint) + { + if (inNum == 2) + { + NdArray returnArray = { inStart, inStop }; + return returnArray; + } + + NdArray returnArray(1, inNum); + returnArray.front() = inStart; + returnArray.back() = inStop; + + dtype step = (inStop - inStart) / static_cast(inNum - 1); + + for (uint32 i = 1; i < inNum - 1; ++i) + { + returnArray[i] = inStart + static_cast(i) * step; + } + + return returnArray; + } + + if (inNum == 2) + { + dtype step = (inStop - inStart) / (inNum); + NdArray returnArray = { inStart, inStart + step }; + return returnArray; + } + + NdArray returnArray(1, inNum); + returnArray.front() = inStart; + + dtype step = (inStop - inStart) / static_cast(inNum); + + for (uint32 i = 1; i < inNum; ++i) + { + returnArray[i] = inStart + static_cast(i) * step; + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/load.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/load.hpp new file mode 100644 index 0000000000000000000000000000000000000000..57037787ec8e49bc7952ab4b79cad9b511ef1741 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/load.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/fromfile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// loads a .bin file from the dump() method into an NdArray + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.load.html + /// + /// @param inFilename + /// + /// @return NdArray + /// + template + NdArray load(const std::string& inFilename) + { + return fromfile(inFilename); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log.hpp new file mode 100644 index 0000000000000000000000000000000000000000..80171580494c98a6d360765951a8d064e933cec9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Natural logarithm. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(inValue); + } + + //============================================================================ + // Method Description: + /// Natural logarithm, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log10.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log10.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2c1afcea9b2f64102490535a5dae92c500d7b0c5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log10.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the base 10 logarithm of the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log10.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log10(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log10(inValue); + } + + //============================================================================ + // Method Description: + /// Return the base 10 logarithm of the input array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log10.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log10(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log10(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log1p.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log1p.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cf044eb6fd5ad6ea3047b0a702cc963902243589 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log1p.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the natural logarithm of one plus the input array. + /// + /// Calculates log(1 + x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log1p.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log1p(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log1p(inValue); + } + + //============================================================================ + // Method Description: + /// Return the natural logarithm of one plus the input array, element-wise. + /// + /// Calculates log(1 + x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log1p.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log1p(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log1p(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f4aabc354cc17ea71faf7388e853e8f87699e2f3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/log2.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Base-2 logarithm of x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log2.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log2(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log2(inValue); + } + + //============================================================================ + // Method Description: + /// Base-2 logarithm of x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log2.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log2(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log2(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f59e9b1df14c4e5927de0e23a098c5e5a5ca979a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return value + /// + template + auto logaddexp(dtype x1, dtype x2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(std::exp(x1) + std::exp(x2)); + } + + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs, element-wise. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return NdArray + /// + template + auto logaddexp(const NdArray& x1, const NdArray& x2) + { + if (x1.size() != x2.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'x1', and 'x2' must be the same size"); + } + + NdArray returnArray(x1.shape()); + stl_algorithms::transform( + x1.cbegin(), + x1.cend(), + x2.cbegin(), + returnArray.begin(), + [](dtype inX1, dtype inX2) noexcept -> auto{ return logaddexp(inX1, inX2); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1c5c8372f7fb675d5125f9276d7024fbedc046af --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logaddexp2.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return value + /// + template + auto logaddexp2(dtype x1, dtype x2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log2(utils::powerf(2, x1) + utils::powerf(2, x2)); + } + + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs, element-wise. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return NdArray + /// + template + auto logaddexp2(const NdArray& x1, const NdArray& x2) + { + if (x1.size() != x2.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'x1', and 'x2' must be the same size"); + } + + NdArray returnArray(x1.shape()); + stl_algorithms::transform( + x1.cbegin(), + x1.cend(), + x2.cbegin(), + returnArray.begin(), + [](dtype inX1, dtype inX2) noexcept -> auto{ return logaddexp2(inX1, inX2); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logb.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logb.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d1a2e818f994c0de8e6accb772bd07785f7ffa90 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logb.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of an arbitrary base + /// + /// @param inValue + /// @param inBase: the logorithm base + /// + /// @return value + /// + template + auto logb(dtype inValue, dtype inBase) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(inValue) / std::log(inBase); + } + + //============================================================================ + // Method Description: + /// Logarithm of an arbitrary base + /// + /// @param inArray + /// @param inBase: the logorithm base + /// + /// @return NdArray + /// + template + auto logb(const NdArray& inArray, dtype inBase) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inBase](dtype inValue) noexcept -> auto{ return logb(inValue, inBase); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_and.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_and.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0d370625e48f3941a61fdd5b9fd8bc1812809589 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_and.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 AND x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_and.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_and(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 && inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_not.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_not.hpp new file mode 100644 index 0000000000000000000000000000000000000000..566e5f9cf779133808bd38ae27443b33a2179234 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_not.hpp @@ -0,0 +1,59 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of NOT x element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_not.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray logical_not(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> bool { return utils::essentiallyEqual(inValue, dtype{ 0 }); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_or.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_or.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e9e0fdf2b167d7cccf09ea80a909623d3541989f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_or.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 OR x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_or.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_or(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 || inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_xor.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_xor.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9f4453099cc37ae204b41802316bb1380d8c98ee --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logical_xor.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 XOR x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_xor.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_xor(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) -> bool { + return !utils::essentiallyEqual(inValue1, dtype{ 0 }) != + !utils::essentiallyEqual(inValue2, dtype{ 0 }); + }); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logspace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logspace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5fdcd35cc0936efffc75ab0f3229333a2295cf9b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/logspace.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return numbers spaced evenly on a log scale. + /// + /// This is similar to logspace, but with endpoints specified directly. + /// Each output sample is a constant multiple of the previous. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logspace.html + /// + /// @param start: the starting value of a sequence + /// @param stop: The final value of the sequence, unless endpoint is False. + /// In that case, num + 1 values are spaced over the interval + /// in log-space, of which all but the last (a sequence of length num) are returned. + /// @param num: Number of samples to generate. Default 50. + /// @param endPoint: If true, stop is the last sample. Otherwise,it is not included. Default is true. + /// @param base: The base of the log space. The step size between the elements in ln(samples) / ln(base) + /// @return NdArray + /// + template + NdArray logspace(dtype start, dtype stop, uint32 num = 50, bool endPoint = true, double base = 10.) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + auto spacedValues = linspace(static_cast(start), static_cast(stop), num, endPoint); + stl_algorithms::for_each(spacedValues.begin(), + spacedValues.end(), + [base](auto& value) -> void { value = utils::powerf(base, value); }); + + return spacedValues; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/matmul.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/matmul.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2adb4ea32d8b54eb75ec82a440567647a8de41f5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/matmul.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray matmul(const NdArray& inArray1, const NdArray& inArray2) + { + return dot(inArray1, inArray2); + } + + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray> matmul(const NdArray& inArray1, const NdArray>& inArray2) + { + return dot(inArray1, inArray2); + } + + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray> matmul(const NdArray>& inArray1, const NdArray& inArray2) + { + return dot(inArray1, inArray2); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/max.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/max.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4880e08501812ed57689048ada911c752f1e1451 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/max.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray max(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.max(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/maximum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/maximum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b6c90b7c5e37294a717c14eed8fcdac782c02fc5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/maximum.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray maximum(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](const dtype& lhs, const dtype& rhs) noexcept -> bool { return lhs < rhs; }; + return broadcast::broadcaster(inArray1, + inArray2, + [&comparitor](const dtype& value1, const dtype& value2) + { return std::max(value1, value2, comparitor); }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray maximum(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return maximum(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray maximum(const dtype& inScalar, const NdArray& inArray) + { + return maximum(inArray, inScalar); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mean.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mean.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a2e81fdc17867e8c4e30afa337e3be8f94ff4aec --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mean.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //=========================================================================== + // Method Description: + /// Compute the mean along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray mean(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = std::accumulate(inArray.cbegin(), inArray.cend(), 0.); + NdArray returnArray = { sum /= static_cast(inArray.size()) }; + + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + auto sum = std::accumulate(inArray.cbegin(row), inArray.cend(row), 0.); + returnArray(0, row) = sum / static_cast(inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + return mean(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Compute the mean along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> mean(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = std::accumulate(inArray.cbegin(), inArray.cend(), std::complex(0.)); + NdArray> returnArray = { sum /= std::complex(inArray.size()) }; + + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + auto sum = std::accumulate(inArray.cbegin(row), inArray.cend(row), std::complex(0.)); + returnArray(0, row) = sum / std::complex(inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + NdArray> transposedArray = inArray.transpose(); + NdArray> returnArray(1, transposedArray.numRows()); + for (uint32 row = 0; row < transposedArray.numRows(); ++row) + { + auto sum = std::accumulate(transposedArray.cbegin(row), + transposedArray.cend(row), + std::complex(0.)); + returnArray(0, row) = sum / std::complex(transposedArray.numCols()); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/median.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/median.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6b66f305f140cdde6e9a4858cb1a7bfba88c7c36 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/median.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the median along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.median.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray median(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.median(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/meshgrid.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/meshgrid.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8504956d40061840a3d7d43cf5d9cdf61a3d97bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/meshgrid.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return coordinate matrices from coordinate vectors. + /// Make 2D coordinate arrays for vectorized evaluations of 2D scalar + /// vector fields over 2D grids, given one - dimensional coordinate arrays x1, x2, ..., xn. + /// If input arrays are not one dimensional they will be flattened. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.meshgrid.html + /// + /// @param inICoords + /// @param inJCoords + /// + /// @return std::pair, NdArray >, i and j matrices + /// + template + std::pair, NdArray> meshgrid(const NdArray& inICoords, const NdArray& inJCoords) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 numRows = inJCoords.size(); + const uint32 numCols = inICoords.size(); + auto returnArrayI = NdArray(numRows, numCols); + auto returnArrayJ = NdArray(numRows, numCols); + + // first the I array + for (uint32 row = 0; row < numRows; ++row) + { + for (uint32 col = 0; col < numCols; ++col) + { + returnArrayI(row, col) = inICoords[col]; + } + } + + // then the I array + for (uint32 col = 0; col < numCols; ++col) + { + for (uint32 row = 0; row < numRows; ++row) + { + returnArrayJ(row, col) = inJCoords[row]; + } + } + + return std::make_pair(returnArrayI, returnArrayJ); + } + + //============================================================================ + // Method Description: + /// Return coordinate matrices from coordinate vectors. + /// Make 2D coordinate arrays for vectorized evaluations of 2D scalar + /// vector fields over 2D grids, given one - dimensional coordinate arrays x1, x2, ..., xn. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.meshgrid.html + /// + /// @param inSlice1 + /// @param inSlice2 + /// + /// @return std::pair, NdArray >, i and j matrices + /// + template + std::pair, NdArray> meshgrid(const Slice& inSlice1, const Slice& inSlice2) + { + return meshgrid(arange(inSlice1), arange(inSlice2)); + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/min.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/min.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6e8f5000e7d46476c7318a71697ba3887824f57e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/min.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or minimum along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray min(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.min(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/minimum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/minimum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7a8fedd5c7810ee7cf322fd49aeac25020b824cb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/minimum.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray minimum(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](const dtype& lhs, const dtype& rhs) noexcept -> bool { return lhs < rhs; }; + return broadcast::broadcaster(inArray1, + inArray2, + [&comparitor](const dtype& value1, const dtype& value2) + { return std::min(value1, value2, comparitor); }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray minimum(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return minimum(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray minimum(const dtype& inScalar, const NdArray& inArray) + { + return minimum(inArray, inScalar); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ae3d466cd04a752cf1f5e94f3066e5d41359deef --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/mod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mod.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray mod(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 % inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/multiply.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/multiply.hpp new file mode 100644 index 0000000000000000000000000000000000000000..129f22da3014cc7540bd52c8e5fa24ae84a5e315 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/multiply.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray multiply(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray multiply(const NdArray& inArray, dtype value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray multiply(dtype value, const NdArray& inArray) + { + return value * inArray; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> multiply(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> multiply(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> multiply(const NdArray& inArray, const std::complex& value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> multiply(const std::complex& value, const NdArray& inArray) + { + return value * inArray; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> multiply(const NdArray>& inArray, dtype value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> multiply(dtype value, const NdArray>& inArray) + { + return value * inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nan_to_num.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nan_to_num.hpp new file mode 100644 index 0000000000000000000000000000000000000000..218d30943ef9beff9d40e02b18808225459ed4a8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nan_to_num.hpp @@ -0,0 +1,85 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Replace NaN with zero and infinity with large finite numbers (default behaviour) + /// or with the numbers defined by the user using the nan, posinf and/or neginf keywords. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html + /// + /// @param inArray + /// @param nan: value to be used to fill NaN values, default 0 + /// @param posInf: value to be used to fill positive infinity values, default a very large number + /// @param negInf: value to be used to fill negative infinity values, default a very large negative number + /// @return NdArray + /// + template + NdArray nan_to_num(NdArray inArray, + dtype nan = static_cast(0.), + dtype posInf = DtypeInfo::max(), + dtype negInf = DtypeInfo::min()) + { + STATIC_ASSERT_FLOAT(dtype); + + stl_algorithms::for_each(inArray.begin(), + inArray.end(), + [nan, posInf, negInf](dtype& value) + { + if (isnan(value)) + { + value = nan; + } + else if (isinf(value)) + { + if (value > static_cast(0.)) + { + value = posInf; + } + else + { + value = negInf; + } + } + }); + + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a6a9c412aaac368bab1c78e7435fbcb0398ec225 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmax.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the maximum values along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanargmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nanargmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::min(); + }; + }); + + return argmax(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..038807f075a314425177ca9499a1ebeef7b9b639 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanargmin.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the minimum values along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanargmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nanargmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::max(); + }; + }); + + return argmin(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumprod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumprod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..64222da37285424699f1f264f4c94f339bb8eba5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumprod.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/cumprod.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative product of elements along a given axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nancumprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nancumprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = dtype{ 1 }; + }; + }); + + return cumprod(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumsum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumsum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..40b7b8b934af71621dde754bd6543f0ee5bfb8a4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nancumsum.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/cumsum.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along a given axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nancumsum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nancumsum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = dtype{ 0 }; + }; + }); + + return cumsum(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ee8aecea7bea66d0e448a73186898cbd575af584 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmax.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::min(); + }; + }); + + return max(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmean.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmean.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3beb22a7f3f1f97dc1b9aed5b8cf5db6fef9cc03 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmean.hpp @@ -0,0 +1,118 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the mean along the specified axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmean(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = static_cast(std::accumulate(inArray.cbegin(), + inArray.cend(), + 0., + [](dtype inValue1, dtype inValue2) -> dtype { + return std::isnan(inValue2) ? inValue1 + : inValue1 + inValue2; + })); + + const auto numberNonNan = + static_cast(std::accumulate(inArray.cbegin(), + inArray.cend(), + 0., + [](dtype inValue1, dtype inValue2) -> dtype + { return std::isnan(inValue2) ? inValue1 : inValue1 + 1; })); + + NdArray returnArray = { sum /= numberNonNan }; + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + auto sum = static_cast( + std::accumulate(inArray.cbegin(row), + inArray.cend(row), + 0., + [](dtype inValue1, dtype inValue2) -> dtype + { return std::isnan(inValue2) ? inValue1 : inValue1 + inValue2; })); + + auto numberNonNan = + static_cast(std::accumulate(inArray.cbegin(row), + inArray.cend(row), + 0., + [](dtype inValue1, dtype inValue2) -> dtype { + return std::isnan(inValue2) ? inValue1 : inValue1 + 1; + })); + + returnArray(0, row) = sum / numberNonNan; + } + + return returnArray; + } + case Axis::ROW: + { + return nanmean(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmedian.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmedian.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b028eb5a15dabf7e6a31457dc81e4d1e083de546 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmedian.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the median along the specified axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmedian.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmedian(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector values; + for (auto value : inArray) + { + if (!std::isnan(value)) + { + values.push_back(value); + } + } + + const uint32 middle = static_cast(values.size()) / 2; + stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end()); + NdArray returnArray = { values[middle] }; + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + std::vector values; + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (!std::isnan(inArray(row, col))) + { + values.push_back(inArray(row, col)); + } + } + + const uint32 middle = static_cast(values.size()) / 2; + stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end()); + returnArray(0, row) = values[middle]; + } + + return returnArray; + } + case Axis::ROW: + { + return nanmedian(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..78328b3e47025cb184811fa88f84d079c098ff94 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanmin.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/min.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or maximum along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::max(); + }; + }); + + return min(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanpercentile.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanpercentile.hpp new file mode 100644 index 0000000000000000000000000000000000000000..65ac75735760e9b270f0d6484ec7531b7ff47029 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanpercentile.hpp @@ -0,0 +1,133 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the qth percentile of the data along the specified axis, while ignoring nan values. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanpercentile.html + /// + /// @param inArray + /// @param inPercentile + /// @param inAxis (Optional, default NONE) + /// @param inInterpMethod (default linear) choices = ['linear','lower','higher','nearest','midpoint'] + /// @return NdArray + /// + template + NdArray nanpercentile(const NdArray& inArray, + double inPercentile, + Axis inAxis = Axis::NONE, + const std::string& inInterpMethod = "linear") + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector arrayCopy; + arrayCopy.reserve(inArray.size()); + for (auto value : inArray) + { + if (!isnan(value)) + { + arrayCopy.push_back(static_cast(value)); + } + } + + if (arrayCopy.empty()) + { + NdArray returnArray = { constants::nan }; + return returnArray; + } + + return percentile(NdArray(arrayCopy.data(), + static_cast::size_type>(arrayCopy.size()), + false), + inPercentile, + Axis::NONE, + inInterpMethod); + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + NdArray outValue = nanpercentile(NdArray(&inArray.front(row), inShape.cols), + inPercentile, + Axis::NONE, + inInterpMethod); + + if (outValue.isscalar()) + { + returnArray[row] = outValue.item(); + } + else + { + returnArray[row] = constants::nan; + } + } + + return returnArray; + } + case Axis::ROW: + { + return nanpercentile(inArray.transpose(), inPercentile, Axis::COL, inInterpMethod); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanprod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanprod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b69170e4330eddebdbc2e0c18b7f11e107226485 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanprod.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/prod.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = static_cast(1); + }; + }); + + return prod(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans.hpp new file mode 100644 index 0000000000000000000000000000000000000000..30272e571135c329f0916abff8ba03e501ea0d4f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inSquareSize + /// @return NdArray + /// + inline NdArray nans(uint32 inSquareSize) + { + return full(inSquareSize, constants::nan); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + inline NdArray nans(uint32 inNumRows, uint32 inNumCols) + { + return full(inNumRows, inNumCols, constants::nan); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inShape + /// @return NdArray + /// + inline NdArray nans(const Shape& inShape) + { + return full(inShape, constants::nan); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans_like.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans_like.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8a219363ac20105548edeb137e9b7040ad3e1c20 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nans_like.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray nans_like(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + returnArray.nans(); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanstdev.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanstdev.hpp new file mode 100644 index 0000000000000000000000000000000000000000..83c38a95b74ee32d68c6a0eb8117f2af009497f7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanstdev.hpp @@ -0,0 +1,114 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/nanmean.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis, while ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanstd.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanstdev(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + double meanValue = nanmean(inArray, inAxis).item(); + double sum = 0; + double counter = 0; + for (auto value : inArray) + { + if (std::isnan(value)) + { + continue; + } + + sum += utils::sqr(static_cast(value) - meanValue); + ++counter; + } + NdArray returnArray = { std::sqrt(sum / counter) }; + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray meanValue = nanmean(inArray, inAxis); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + double sum = 0; + double counter = 0; + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (std::isnan(inArray(row, col))) + { + continue; + } + + sum += utils::sqr(static_cast(inArray(row, col)) - meanValue[row]); + ++counter; + } + returnArray(0, row) = std::sqrt(sum / counter); + } + + return returnArray; + } + case Axis::ROW: + { + return nanstdev(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nansum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nansum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b8e7a5a31f6116b9be808f64f78259207c633180 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nansum.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/sum.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nansum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nansum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = static_cast(0); + }; + }); + + return sum(arrayCopy, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanvar.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanvar.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e3977a0437edd6dabf70b9006db1fe718f296fc1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nanvar.hpp @@ -0,0 +1,56 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/nanstdev.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis, while ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanvar.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanvar(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + return square(nanstdev(inArray, inAxis)); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nbytes.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nbytes.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e04e741cb3e5e975d642bdd127ea29203d9a497e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nbytes.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the number of bytes held by the array + /// + /// @param inArray + /// @return number of bytes + /// + template + uint64 nbytes(const NdArray& inArray) noexcept + { + return inArray.nbytes(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/negative.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/negative.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ac6c506ca21f08ae2ba1add484bb4c51d7143ac9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/negative.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Numerical negative, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.negative.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray negative(const NdArray& inArray) + { + return -inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/newbyteorder.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/newbyteorder.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ba6e2d80c8b1446206147676090dc909e60cafa2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/newbyteorder.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types, + /// floating point types will not compile and you will + /// be confused as to why... + /// + /// + /// @param inValue + /// @param inEndianess + /// + /// @return inValue + /// + template + dtype newbyteorder(dtype inValue, Endian inEndianess) + { + NdArray valueArray = { inValue }; + return valueArray.newbyteorder(inEndianess).item(); + } + + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types, + /// floating point types will not compile and you will + /// be confused as to why... + /// + /// + /// @param inArray + /// @param inEndianess + /// + /// @return NdArray + /// + template + NdArray newbyteorder(const NdArray& inArray, Endian inEndianess) + { + return inArray.newbyteorder(inEndianess); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/none.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/none.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5a3835edb68160d323805df1195c80691121f11a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/none.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether no array elements along a given axis evaluate to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.all.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray none(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.none(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nonzero.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nonzero.hpp new file mode 100644 index 0000000000000000000000000000000000000000..27cbaff7c60b9fb11530d0aefe090e57a0a97c8d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nonzero.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the indices of the flattened array of the + /// elements that are non-zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nonzero.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + std::pair, NdArray> nonzero(const NdArray& inArray) + { + return inArray.nonzero(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/norm.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/norm.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f0a94321da75063c4d495d4c46ab2dc33db0b24c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/norm.hpp @@ -0,0 +1,142 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray norm(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double sumOfSquares = 0.; + const auto function = [&sumOfSquares](dtype value) -> void + { sumOfSquares += utils::sqr(static_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray returnArray = { std::sqrt(sumOfSquares) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + sumOfSquares = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(sumOfSquares); + } + + return returnArray; + } + case Axis::ROW: + { + return norm(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> norm(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex sumOfSquares(0., 0.); + const auto function = [&sumOfSquares](const std::complex& value) -> void + { sumOfSquares += utils::sqr(complex_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray> returnArray = { std::sqrt(sumOfSquares) }; + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + sumOfSquares = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(sumOfSquares); + } + + return returnArray; + } + case Axis::ROW: + { + return norm(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/normalize.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/normalize.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a6e987f5a3b85a1c7a5cedebacf92a89d983531d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/normalize.hpp @@ -0,0 +1,127 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/norm.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray normalize(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + return inArray / norm(inArray, Axis::NONE); + } + case Axis::COL: + { + NdArray returnArray(inArray.shape()); + const auto cSlice = returnArray.cSlice(); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + returnArray.put(row, cSlice, normalize(inArray.row(row), Axis::NONE)); + } + + return returnArray; + } + case Axis::ROW: + { + return normalize(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> normalize(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + return inArray / norm(inArray, Axis::NONE); + } + case Axis::COL: + { + NdArray> returnArray(inArray.shape()); + const auto cSlice = returnArray.cSlice(); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + returnArray.put(row, cSlice, normalize(inArray.row(row), Axis::NONE)); + } + + return returnArray; + } + case Axis::ROW: + { + return normalize(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/not_equal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/not_equal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cfa71de28ab7882fc6d46576f011bfbf065dcd80 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/not_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return (x1 != x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.not_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray not_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 != inArray2; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nth_root.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nth_root.hpp new file mode 100644 index 0000000000000000000000000000000000000000..aec55043847b153b9162743c53fe926a4b532968 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/nth_root.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the nth-root of an value. + /// + /// @param inValue + /// @param inRoot + /// @return value + /// + template + double nth_root(dtype1 inValue, dtype2 inRoot) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return utils::powerf(static_cast(inValue), 1. / static_cast(inRoot)); + } + + //============================================================================ + // Method Description: + /// Return the nth-root of an array. + /// + /// @param inArray + /// @param inRoot + /// @return NdArray + /// + template + NdArray nth_root(const NdArray& inArray, dtype2 inRoot) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inRoot](dtype1 inValue) noexcept -> double { return nth_root(inValue, inRoot); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones.hpp new file mode 100644 index 0000000000000000000000000000000000000000..26324380c7b04352be6daa8ed110e38c0ad507b2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inSquareSize + /// @return NdArray + /// + template + NdArray ones(uint32 inSquareSize) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inSquareSize, inSquareSize, dtype{ 1 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray ones(uint32 inNumRows, uint32 inNumCols) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inNumRows, inNumCols, dtype{ 1 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray ones(const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inShape, dtype{ 1 }); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones_like.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones_like.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2733699b64f7143adbb260cf355cb5db5dc95e04 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ones_like.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray ones_like(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + returnArray.ones(); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/outer.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/outer.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3e4520216469ae80f7860f71ef617374ca7359ab --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/outer.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The outer product of two vectors. Inputs are flattened if not already 1-dimensional. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.outer.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray outer(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto size = inArray1.size(); + + if (size != inArray2.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input arrays must be the same length"); + } + + auto returnArray = NdArray(size); + for (uint32 row = 0; row < size; ++row) + { + const auto array1Value = inArray1[row]; + + std::transform(inArray2.begin(), + inArray2.end(), + returnArray.begin(row), + [array1Value](dtype value) -> dtype { return array1Value * value; }); + } + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/packbits.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/packbits.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d9cf92fe65713b1c0307bb8b4e7064f9494a77e0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/packbits.hpp @@ -0,0 +1,193 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Packs the elements of a binary-valued array into bits in a uint8 array. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.packbits.html + /// + /// @param a: An array of integers or booleans whose elements should be packed to bits. + /// @param axis: The dimension over which bit-packing is done. None implies packing the flattened array. + /// @return NdArray + /// + template || std::is_same_v, int> = 0> + NdArray packbitsLittleEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + const auto numFullValues = a.size() / 8; + const auto leftOvers = a.size() % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(1, resultSize); + result.fill(0); + + for (typename NdArray::size_type i = 0; i < numFullValues; ++i) + { + const auto startIdx = i * 8; + for (auto bit = 0; bit < 8; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result[i] |= (value << bit); + } + } + + if (leftOvers != 0) + { + const auto startIdx = numFullValues * 8; + for (std::remove_const_t bit = 0; bit < leftOvers; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result.back() |= (value << bit); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + const auto numFullValues = aShape.cols / 8; + const auto leftOvers = aShape.cols % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(aShape.rows, resultSize); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (typename NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, packbitsLittleEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return packbitsLittleEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Packs the elements of a binary-valued array into bits in a uint8 array. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.packbits.html + /// + /// @param a: An array of integers or booleans whose elements should be packed to bits. + /// @param axis: The dimension over which bit-packing is done. None implies packing the flattened array. + /// @return NdArray + /// + template || std::is_same_v, int> = 0> + NdArray packbitsBigEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + const auto numFullValues = a.size() / 8; + const auto leftOvers = a.size() % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(1, resultSize); + result.fill(0); + + for (typename NdArray::size_type i = 0; i < numFullValues; ++i) + { + const auto startIdx = i * 8; + for (auto bit = 0; bit < 8; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result[i] |= (value << (7 - bit)); + } + } + + if (leftOvers != 0) + { + const auto startIdx = numFullValues * 8; + for (std::remove_const_t bit = 0; bit < leftOvers; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result.back() |= (value << (7 - bit)); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + const auto numFullValues = aShape.cols / 8; + const auto leftOvers = aShape.cols % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(aShape.rows, resultSize); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (typename NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, packbitsBigEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return packbitsBigEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/pad.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/pad.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e50900963402d3fa44d74dee84e7a780ec5a2e8c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/pad.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Pads an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.pad.html + /// + /// @param inArray + /// @param inPadWidth + /// @param inPadValue + /// @return NdArray + /// + template + NdArray pad(const NdArray& inArray, uint16 inPadWidth, dtype inPadValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + Shape outShape(inShape); + outShape.rows += 2 * inPadWidth; + outShape.cols += 2 * inPadWidth; + + NdArray returnArray(outShape); + returnArray.fill(inPadValue); + returnArray.put(Slice(inPadWidth, inPadWidth + inShape.rows), + Slice(inPadWidth, inPadWidth + inShape.cols), + inArray); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/partition.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/partition.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4b5bd07c18a32c68ef7ffdf02b42e320288a8bbb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/partition.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Rearranges the elements in the array in such a way that + /// value of the element in kth position is in the position it + /// would be in a sorted array. All elements smaller than the kth + /// element are moved before this element and all equal or greater + /// are moved behind it. The ordering of the elements in the two + /// partitions is undefined. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.partition.html + /// + /// @param inArray + /// @param inKth: kth element + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray partition(const NdArray& inArray, uint32 inKth, Axis inAxis = Axis::NONE) + { + NdArray returnArray(inArray); + returnArray.partition(inKth, inAxis); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/percentile.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/percentile.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3600f40069256f6557fbb1251382f999d1d2ec05 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/percentile.hpp @@ -0,0 +1,203 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the qth percentile of the data along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.percentile.html + /// + /// @param inArray + /// @param inPercentile: percentile must be in the range [0, 100] + /// @param inAxis (Optional, default NONE) + /// @param inInterpMethod (Optional) interpolation method + /// linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. + /// lower : i. + /// higher : j. + /// nearest : i or j, whichever is nearest. + /// midpoint : (i + j) / 2. + /// @return NdArray + /// + template + NdArray percentile(const NdArray& inArray, + double inPercentile, + Axis inAxis = Axis::NONE, + const std::string& inInterpMethod = "linear") + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inPercentile < 0. || inPercentile > 100.) + { + THROW_INVALID_ARGUMENT_ERROR("input percentile value must be of the range [0, 100]."); + } + + if (inArray.isempty()) + { + return {}; + } + else if (inArray.isscalar()) + { + NdArray returnArray = { static_cast(inArray.front()) }; + return returnArray; + } + + if (inInterpMethod != "linear" && inInterpMethod != "lower" && inInterpMethod != "higher" && + inInterpMethod != "nearest" && inInterpMethod != "midpoint") + { + std::string errStr = "input interpolation method is not a vaid option.\n"; + errStr += "\tValid options are 'linear', 'lower', 'higher', 'nearest', 'midpoint'."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + switch (inAxis) + { + case Axis::NONE: + { + NdArray arrayCopy = inArray.template astype(); + stl_algorithms::sort(arrayCopy.begin(), arrayCopy.end()); + + if (utils::essentiallyEqual(inPercentile, 0.)) + { + NdArray returnArray = { arrayCopy.front() }; + return returnArray; + } + if (utils::essentiallyEqual(inPercentile, 100.)) + { + NdArray returnArray = { arrayCopy.back() }; + return returnArray; + } + + const auto i = + static_cast(std::floor(static_cast(inArray.size() - 1) * inPercentile / 100.)); + const auto indexLower = clip(i, 0, inArray.size() - 2); + + if (inInterpMethod == "linear") + { + const double percentI = static_cast(indexLower) / static_cast(inArray.size() - 1); + const double fraction = + (inPercentile / 100. - percentI) / + (static_cast(indexLower + 1) / static_cast(inArray.size() - 1) - percentI); + + NdArray returnArray = { arrayCopy[indexLower] + + (arrayCopy[indexLower + 1] - arrayCopy[indexLower]) * fraction }; + return returnArray; + } + + if (inInterpMethod == "lower") + { + NdArray returnArray = { arrayCopy[indexLower] }; + return returnArray; + } + + if (inInterpMethod == "higher") + { + NdArray returnArray = { arrayCopy[indexLower + 1] }; + return returnArray; + } + + if (inInterpMethod == "nearest") + { + const double percent = inPercentile / 100.; + const double percent1 = static_cast(indexLower) / static_cast(inArray.size() - 1); + const double percent2 = + static_cast(indexLower + 1) / static_cast(inArray.size() - 1); + const double diff1 = percent - percent1; + const double diff2 = percent2 - percent; + + switch (argmin({ diff1, diff2 }).item()) + { + case 0: + { + NdArray returnArray = { arrayCopy[indexLower] }; + return returnArray; + } + case 1: + { + NdArray returnArray = { arrayCopy[indexLower + 1] }; + return returnArray; + } + } + } + + if (inInterpMethod == "midpoint") + { + NdArray returnArray = { (arrayCopy[indexLower] + arrayCopy[indexLower + 1]) / 2. }; + return returnArray; + } + + THROW_INVALID_ARGUMENT_ERROR("interpolation method has not been implemented: " + inInterpMethod); + break; // get rid of compiler warning... + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray[row] = percentile(NdArray(&inArray.front(row), inShape.cols), + inPercentile, + Axis::NONE, + inInterpMethod) + .item(); + } + + return returnArray; + } + case Axis::ROW: + { + return percentile(inArray.transpose(), inPercentile, Axis::COL, inInterpMethod); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/place.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/place.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7c00a8062b14c25ee6e069e4e626b9a68fb4bef9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/place.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change elements of an array based on conditional and input values. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.place.html + /// + /// @param arr: Array to put data into. + /// @param mask: Boolean mask array. Must have the same size as arr + /// @param vals: Values to put into a. Only the first N elements are used, where N is the + /// number of True values in mask. If vals is smaller than N, it will be repeated. + /// @return NdArray + /// + template + void place(NdArray& arr, const NdArray& mask, const NdArray& vals) + { + if (mask.size() != arr.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input arguments 'arr' and 'mask' must have the same size."); + } + + if (vals.isempty()) + { + return; + } + + auto valIdx = 0; + for (decltype(arr.size()) i = 0; i < arr.size(); ++i) + { + if (mask[i]) + { + arr[i] = vals[valIdx++ % vals.size()]; + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/polar.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/polar.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fcc8d14c1c8b8da44732bdf8f10313baf33f0edf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/polar.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a complex number with magnitude r and phase angle theta. + /// + /// @param magnitude + /// @param phaseAngle + /// + /// @return std::complex + /// + template + auto polar(dtype magnitude, dtype phaseAngle) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::polar(magnitude, phaseAngle); + } + + //============================================================================ + // Method Description: + /// Returns a complex number with magnitude r and phase angle theta. + /// + /// @param magnitude + /// @param phaseAngle + /// @return NdArray + /// + template + auto polar(const NdArray& magnitude, const NdArray& phaseAngle) + { + if (magnitude.shape() != phaseAngle.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("Input magnitude and phaseAngle arrays must be the same shape"); + } + + NdArray returnArray(magnitude.shape()); + stl_algorithms::transform( + magnitude.cbegin(), + magnitude.cend(), + phaseAngle.begin(), + returnArray.begin(), + [](dtype mag, dtype angle) -> auto{ return nc::polar(mag, angle); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/power.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/power.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5612fdbcc3865612401d45060690b6d511c3136c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/power.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inValue + /// @param inExponent + /// @return value raised to the power + /// + template + constexpr dtype power(dtype inValue, uint8 inExponent) noexcept + { + return utils::power(inValue, inExponent); + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponent + /// @return NdArray + /// + template + NdArray power(const NdArray& inArray, uint8 inExponent) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inExponent](dtype inValue) noexcept -> dtype + { return nc::power(inValue, inExponent); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer powers + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponents + /// @return NdArray + /// + template + NdArray power(const NdArray& inArray, const NdArray& inExponents) + { + if (inArray.shape() != inExponents.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inExponents.cbegin(), + returnArray.begin(), + [](dtype inValue, uint8 inExponent) -> dtype + { return nc::power(inValue, inExponent); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/powerf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/powerf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b8c60f39542565548f63078c9c3f1bb71d6de415 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/powerf.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inValue + /// @param inExponent + /// @return value raised to the power + /// + template + auto powerf(dtype1 inValue, dtype2 inExponent) noexcept + { + return utils::powerf(inValue, inExponent); + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponent + /// @return NdArray + /// + template + auto powerf(const NdArray& inArray, dtype2 inExponent) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inExponent](dtype1 inValue) noexcept -> auto{ return nc::powerf(inValue, inExponent); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point powers + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponents + /// @return NdArray + /// + template + auto powerf(const NdArray& inArray, const NdArray& inExponents) + { + if (inArray.shape() != inExponents.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + inExponents.cbegin(), + returnArray.begin(), + [](dtype1 inValue, dtype2 inExponent) noexcept -> auto{ return nc::powerf(inValue, inExponent); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/print.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/print.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b533c769735b7e1401cf19bce322230b4a804015 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/print.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Prints the array to the console. + /// + /// @param inArray + /// @return None + /// + template + void print(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::cout << inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/prod.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/prod.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b34e3dddab16bb2f41a0def382926a8645c51529 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/prod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the product of array elements over a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.prod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray prod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.prod(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/proj.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/proj.hpp new file mode 100644 index 0000000000000000000000000000000000000000..43a7646ec37a1ac7221321216197076fc1ae574e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/proj.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the projection of the complex number z onto the Riemann sphere. + /// + /// @param inValue + /// @return value + /// + template + auto proj(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::proj(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the projection of the complex number z onto the Riemann sphere. + /// + /// @param inArray + /// @return NdArray + /// + template + auto proj(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::proj(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ptp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ptp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bbb6d31ca9526649eaf66c091308b8cb154c5d12 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ptp.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Range of values (maximum - minimum) along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ptp.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray ptp(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.ptp(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/put.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/put.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9b4bcbaa586acb391cbe2a30205cac41a8bf65c4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/put.hpp @@ -0,0 +1,472 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// set the flat index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndex + /// @param inValue + /// + template + NdArray& put(NdArray& inArray, int32 inIndex, const dtype& inValue) + { + inArray.put(inIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// set the 2D row/col index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRow + /// @param inCol + /// @param inValue + /// + template + NdArray& put(NdArray& inArray, int32 inRow, int32 inCol, const dtype& inValue) + { + inArray.put(inRow, inCol, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inIndices, const dtype& inValue) + { + inArray.put(inIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values[n] for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inIndices, const NdArray& inValues) + { + inArray.put(inIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inSlice, const dtype& inValue) + { + inArray.put(inSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inSlice, const NdArray& inValues) + { + inArray.put(inSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const ColIndices& inColIndices, + const dtype& inValue) + { + inArray.put(inRowIndices, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const RowIndices& inRowIndices, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowIndices, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, const ColIndices& inColIndices, const dtype& inValue) + { + inArray.put(inRowSlice, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inRowSlice, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowSlice, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inRowIndices, int32 inColIndex, const dtype& inValue) + { + inArray.put(inRowIndices, inColIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inRowSlice, int32 inColIndex, const dtype& inValue) + { + inArray.put(inRowSlice, inColIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, int32 inRowIndex, const Indices& inColIndices, const dtype& inValue) + { + inArray.put(inRowIndex, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, int32 inRowIndex, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowIndex, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const ColIndices& inColIndices, + const NdArray& inValues) + { + inArray.put(inRowIndices, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const Slice& inColSlice, + const NdArray& inValues) + { + inArray.put(inRowIndices, inColSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, + const Slice& inRowSlice, + const ColIndices& inColIndices, + const NdArray& inValues) + { + inArray.put(inRowSlice, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, const Slice& inColSlice, const NdArray& inValues) + { + inArray.put(inRowSlice, inColSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const Indices& inRowIndices, int32 inColIndex, const NdArray& inValues) + { + inArray.put(inRowIndices, inColIndex, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, int32 inColIndex, const NdArray& inValues) + { + inArray.put(inRowSlice, inColIndex, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, int32 inRowIndex, const Indices& inColIndices, const NdArray& inValues) + { + inArray.put(inRowIndex, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, int32 inRowIndex, const Slice& inColSlice, const NdArray& inValues) + { + inArray.put(inRowIndex, inColSlice, inValues); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/putmask.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/putmask.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9a757c851d9e69b4514aff284ff2b39efef862d7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/putmask.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Changes elements of an array based on conditional and input values. + /// + /// Sets a.flat[n] = values[n] for each n where mask.flat[n] == True. + /// + /// If values is not the same size as a and mask then it will repeat. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.putmask.html + /// + /// @param inArray + /// @param inMask + /// @param inValue + /// @return NdArray + /// + template + NdArray& putmask(NdArray& inArray, const NdArray& inMask, dtype inValue) + { + inArray.putMask(inMask, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Changes elements of an array based on conditional and input values. + /// + /// Sets a.flat[n] = values[n] for each n where mask.flat[n] == True. + /// + /// If values is not the same size as a and mask then it will repeat. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.putmask.html + /// + /// @param inArray + /// @param inMask + /// @param inValues + /// @return NdArray + /// + template + NdArray& putmask(NdArray& inArray, const NdArray& inMask, const NdArray& inValues) + { + inArray.putMask(inMask, inValues); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rad2deg.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rad2deg.hpp new file mode 100644 index 0000000000000000000000000000000000000000..edff3bf7dc0dad94565410cd0d4cdd6cd874fb74 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rad2deg.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from radians to degrees. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rad2deg.html + /// + /// @param inValue + /// + /// @return value + /// + template + constexpr auto rad2deg(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue * 180. / constants::pi; + } + + //============================================================================ + // Method Description: + /// Convert angles from radians to degrees. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rad2deg.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto rad2deg(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return rad2deg(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/radians.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/radians.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e0e15db43bec91c99fbef876ea671ced328c824a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/radians.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.radians.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto radians(dtype inValue) noexcept + { + return deg2rad(inValue); + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.radians.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto radians(const NdArray& inArray) + { + return deg2rad(inArray); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ravel.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ravel.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b363abf42a6c1c2e35b4c8a18a7f3e44e37bd383 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/ravel.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flattens the array but does not make a copy. + /// + /// Numpy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray& ravel(NdArray& inArray) noexcept + { + inArray.ravel(); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/real.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/real.hpp new file mode 100644 index 0000000000000000000000000000000000000000..15822a13f3dca1a253c700db9d05207d47b3f396 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/real.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the real part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.real.html + /// + /// @param inValue + /// @return value + /// + template + auto real(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::real(inValue); + } + + //============================================================================ + // Method Description: + /// Return the real part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.real.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto real(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::real(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reciprocal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reciprocal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ccb85c832ba549d9b8cc4f7cfb8b83b4fb2eda85 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reciprocal.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the reciprocal of the argument, element-wise. + /// + /// Calculates 1 / x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.reciprocal.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray reciprocal(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray.shape()); + + uint32 counter = 0; + std::for_each(inArray.cbegin(), + inArray.cend(), + [&returnArray, &counter](dtype value) noexcept -> void + { returnArray[counter++] = 1. / static_cast(value); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return the reciprocal of the argument, element-wise. + /// + /// Calculates 1 / x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.reciprocal.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray> reciprocal(const NdArray>& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray> returnArray(inArray.shape()); + + uint32 counter = 0; + std::for_each(inArray.cbegin(), + inArray.cend(), + [&returnArray, &counter](std::complex value) -> void + { returnArray[counter++] = std::complex(1.) / complex_cast(value); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/remainder.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/remainder.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6ece5f489766c3710c72ab97f8176212c99994ea --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/remainder.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.remainder.html + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return NdArray + /// + template + double remainder(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::remainder(inValue1, inValue2)); + } + + //============================================================================ + // Method Description: + /// Return element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.remainder.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray remainder(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> double + { return remainder(inValue1, inValue2); }); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/repeat.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/repeat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5126095e4a7a3312c0283cf420261a5333ab86cc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/repeat.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.repeat.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray repeat(const NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + return inArray.repeat(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.repeat.html + /// + /// @param inArray + /// @param inRepeatShape + /// + /// @return NdArray + /// + template + NdArray repeat(const NdArray& inArray, const Shape& inRepeatShape) + { + return inArray.repeat(inRepeatShape); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/replace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/replace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4714302f4584ca31d4642ac4dfad20aeafdae33c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/replace.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Replaces the matching elements of an array with the new value + /// + /// @param inArray + /// @param oldValue: the value to replace + /// @param newValue: the value to replace with + /// + /// @return NdArray + /// + template + NdArray replace(const NdArray& inArray, dtype oldValue, dtype newValue) + { + auto returnArray = inArray.copy(); + returnArray.replace(oldValue, newValue); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reshape.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reshape.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6e0d97e8f287dabe89513d49fcd57df35804b62c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/reshape.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inSize + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, uint32 inSize) + { + inArray.reshape(inSize); + return inArray; + } + + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, int32 inNumRows, int32 inNumCols) + { + inArray.reshape(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, const Shape& inNewShape) + { + inArray.reshape(inNewShape); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeFast.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeFast.hpp new file mode 100644 index 0000000000000000000000000000000000000000..62ca62bd4cf9996a2a1d2a4753f6f45985449ad6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeFast.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& resizeFast(NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + inArray.resizeFast(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& resizeFast(NdArray& inArray, const Shape& inNewShape) + { + inArray.resizeFast(inNewShape); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeSlow.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeSlow.hpp new file mode 100644 index 0000000000000000000000000000000000000000..75404f63eb6dc6dba3f36d33f5cf5f0cbf4d994f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/resizeSlow.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& resizeSlow(NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + inArray.resizeSlow(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& resizeSlow(NdArray& inArray, const Shape& inNewShape) + { + inArray.resizeSlow(inNewShape); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/right_shift.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/right_shift.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7c785c55920bfaa6f0170dc2f7828538924332b4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/right_shift.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Shift the bits of an integer to the right. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.right_shift.html + /// + /// @param inArray + /// @param inNumBits + /// + /// @return NdArray + /// + template + NdArray right_shift(const NdArray& inArray, uint8 inNumBits) + { + return inArray >> inNumBits; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rint.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rint.hpp new file mode 100644 index 0000000000000000000000000000000000000000..65300a2c109a0a42d1b335876076d835aecf5cf5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rint.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round value to the nearest integer. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rint.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype rint(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::rint(inValue); + } + + //============================================================================ + // Method Description: + /// Round elements of the array to the nearest integer. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rint.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray rint(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return rint(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rms.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rms.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c36aa97e3ba7a0bd20d235b1a3caaa2cdd50de07 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rms.hpp @@ -0,0 +1,141 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the root mean square (RMS) along the specified axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray rms(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double squareSum = 0.; + const auto function = [&squareSum](dtype value) -> void + { squareSum += utils::sqr(static_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + NdArray returnArray = { std::sqrt(squareSum / static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + squareSum = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(squareSum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + return rms(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Compute the root mean square (RMS) along the specified axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> rms(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex squareSum = 0.; + const auto function = [&squareSum](std::complex value) -> void + { squareSum += utils::sqr(complex_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + NdArray> returnArray = { std::sqrt(squareSum / + static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + squareSum = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(squareSum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + return rms(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/roll.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/roll.hpp new file mode 100644 index 0000000000000000000000000000000000000000..90c0e0eac62a4f2e7dc8aaad419f3f62a8da41e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/roll.hpp @@ -0,0 +1,100 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Roll array elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.roll.html + /// + /// @param inArray + /// @param inShift: (elements to shift, positive means forward, negative means backwards) + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray roll(const NdArray& inArray, int32 inShift, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + uint32 shift = std::abs(inShift) % inArray.size(); + if (inShift > 0) + { + shift = inArray.size() - shift; + } + + NdArray returnArray(inArray); + stl_algorithms::rotate(returnArray.begin(), returnArray.begin() + shift, returnArray.end()); + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + uint32 shift = std::abs(inShift) % inShape.cols; + if (inShift > 0) + { + shift = inShape.cols - shift; + } + + NdArray returnArray(inArray); + for (uint32 row = 0; row < inShape.rows; ++row) + { + stl_algorithms::rotate(returnArray.begin(row), + returnArray.begin(row) + shift, + returnArray.end(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return roll(inArray.transpose(), inShift, Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rot90.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rot90.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f51eba514bd1ccdfcc73d2af2c645c13c917ff10 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/rot90.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Rotate an array by 90 degrees counter clockwise in the plane. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rot90.html + /// + /// @param inArray + /// @param inK: the number of times to rotate 90 degrees + /// + /// @return NdArray + /// + template + NdArray rot90(const NdArray& inArray, uint8 inK = 1) + { + inK %= 4; + switch (inK) + { + case 0: + { + return inArray; + } + case 1: + { + return flipud(inArray.transpose()); + } + case 2: + { + return flip(inArray, Axis::NONE); + } + case 3: + { + return fliplr(inArray.transpose()); + } + default: + { + // this isn't actually possible, just putting this here to get rid + // of the compiler warning. + return {}; + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/round.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/round.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1a9b6ecc1f1deb458ee99aeb71b79f1d12efd121 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/round.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round value to the given number of decimals. + /// + /// @param inValue + /// @param inDecimals + /// + /// @return value + /// + template + dtype round(dtype inValue, uint8 inDecimals = 0) + { + NdArray input = { inValue }; + return input.round(inDecimals).item(); + } + + //============================================================================ + // Method Description: + /// Round an array to the given number of decimals. + /// + /// @param inArray + /// @param inDecimals + /// + /// @return NdArray + /// + template + NdArray round(const NdArray& inArray, uint8 inDecimals = 0) + { + return inArray.round(inDecimals); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/row_stack.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/row_stack.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0c68ce6a25fa38164890fd3e110233a918a17d62 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/row_stack.hpp @@ -0,0 +1,129 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Stack arrays in sequence vertically (row wise). + /// + /// @param begin: iterator to the beginning of the span + /// @param end: iterator to one past the end of the span + /// + /// @return NdArray + /// + template + NdArray row_stack(Iterator begin, Iterator end) + { + // first loop through to calculate the final size of the array + Shape finalShape; + auto iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + if (ndarray.shape().isnull()) + { + continue; + } + + if (finalShape.isnull()) + { + finalShape = ndarray.shape(); + } + else if (ndarray.shape().cols != finalShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays must have the same number of columns."); + } + else + { + finalShape.rows += ndarray.shape().rows; + } + } + + // now that we know the final size, contruct the output array + NdArray returnArray(finalShape); + uint32 rowStart = 0; + iter = begin; + while (iter != end) + { + const auto& ndarray = *iter++; + const Shape theShape = ndarray.shape(); + for (uint32 row = 0; row < theShape.rows; ++row) + { + for (uint32 col = 0; col < theShape.cols; ++col) + { + returnArray(rowStart + row, col) = ndarray(row, col); + } + } + rowStart += theShape.rows; + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Stack arrays in sequence vertically (row wise). + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray row_stack(const std::initializer_list>& inArrayList) + { + return detail::row_stack(inArrayList.begin(), inArrayList.end()); + } + + //============================================================================ + // Method Description: + /// Stack arrays in sequence vertically (row wise). + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray row_stack(const std::vector>& inArrayList) + { + return detail::row_stack(inArrayList.begin(), inArrayList.end()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/select.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/select.hpp new file mode 100644 index 0000000000000000000000000000000000000000..eb34aeda398c36e1ddb2573cc8bf715baeb9f222 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/select.hpp @@ -0,0 +1,158 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return an array drawn from elements in choiceVec, depending on conditions. + /// + /// NumPy Reference: + /// https://numpy.org/doc/stable/reference/generated/numpy.select.html?highlight=select#numpy.select + /// + /// @param condVec The vector of conditions which determine from which array in choiceVec + /// the output elements are taken. When multiple conditions are satisfied, + /// the first one encountered in choiceVec is used. + /// @param choiceVec The vector of array pointers from which the output elements are taken. + /// It has to be of the same length as condVec. + /// @param defaultValue The element inserted in output when all conditions evaluate to False + /// @return NdArray + /// + template + NdArray select(const std::vector*>& condVec, + const std::vector*>& choiceVec, + dtype defaultValue = dtype{ 0 }) + { + if (choiceVec.size() != condVec.size()) + { + THROW_INVALID_ARGUMENT_ERROR("condVec and choiceVec need to be the same size"); + } + + if (choiceVec.size() == 0) + { + THROW_INVALID_ARGUMENT_ERROR("choiceVec is size 0"); + } + + auto theShape = condVec.front()->shape(); + for (const auto cond : condVec) + { + const auto& theCond = *cond; + if (theCond.shape() != theShape) + { + THROW_INVALID_ARGUMENT_ERROR("all NdArrays of the condVec must be the same shape"); + } + } + + for (const auto choice : choiceVec) + { + const auto& theChoice = *choice; + if (theChoice.shape() != theShape) + { + THROW_INVALID_ARGUMENT_ERROR( + "all NdArrays of the choiceVec must be the same shape, and the same as condVec"); + } + } + + using size_type = typename NdArray::size_type; + constexpr auto nullChoice = std::numeric_limits::max(); + + NdArray choiceIndices(theShape); + choiceIndices.fill(nullChoice); + for (size_type condIdx = 0; condIdx < condVec.size(); ++condIdx) + { + const auto& theCond = *condVec[condIdx]; + for (size_type i = 0; i < theCond.size(); ++i) + { + if (theCond[i] && choiceIndices[i] == nullChoice) + { + choiceIndices[i] = condIdx; + } + } + } + + NdArray result(theShape); + result.fill(defaultValue); + for (size_type i = 0; i < choiceIndices.size(); ++i) + { + const auto choiceIndex = choiceIndices[i]; + if (choiceIndex != nullChoice) + { + const auto& theChoice = *choiceVec[choiceIndex]; + result[i] = theChoice[i]; + } + } + + return result; + } + + //============================================================================ + // Method Description: + /// Return an array drawn from elements in choiceList, depending on conditions. + /// + /// NumPy Reference: + /// https://numpy.org/doc/stable/reference/generated/numpy.select.html?highlight=select#numpy.select + /// + /// @param condList The list of conditions which determine from which array in choiceList + /// the output elements are taken. When multiple conditions are satisfied, + /// the first one encountered in choiceList is used. + /// @param choiceList The list of array pointers from which the output elements are taken. + /// It has to be of the same length as condVec. + /// @param defaultValue The element inserted in output when all conditions evaluate to False + /// @return NdArray + /// + template + NdArray select(const std::vector>& condList, + const std::vector>& choiceList, + dtype defaultValue = dtype{ 0 }) + { + std::vector*> condVec(condList.size()); + stl_algorithms::transform(condList.begin(), + condList.end(), + condVec.begin(), + [](auto& cond) noexcept -> const NdArray* { return &cond; }); + + std::vector*> choiceVec(choiceList.size()); + stl_algorithms::transform(choiceList.begin(), + choiceList.end(), + choiceVec.begin(), + [](auto& choice) noexcept -> const NdArray* { return &choice; }); + + return select(condVec, choiceVec, defaultValue); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/setdiff1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/setdiff1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8220ed7e819e2b78cba5d070a05362860391fa04 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/setdiff1d.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the set difference of two arrays. + /// + /// Return the sorted, unique values in ar1 that are not in ar2. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.setdiff1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray setdiff1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool { return lhs < rhs; }; + + const auto set1 = unique(inArray1); + const auto set2 = unique(inArray2); + + std::vector res(set1.size()); + const auto last = + stl_algorithms::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/shape.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/shape.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d3ddad58ffca34338b730df007bfb19da99cc534 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/shape.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the shape of the array + /// + /// @param inArray + /// @return Shape + /// + template + Shape shape(const NdArray& inArray) noexcept + { + return inArray.shape(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sign.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sign.hpp new file mode 100644 index 0000000000000000000000000000000000000000..672f289314cff377db681c0dcb6ef71b446d5b6e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sign.hpp @@ -0,0 +1,92 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns an element-wise indication of the sign of a number. + /// + /// The sign function returns - 1 if x < 0, 0 if x == 0, 1 if x > 0. + /// nan is returned for nan inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sign.html + /// + /// @param inValue + /// @return NdArray + /// + template + int8 sign(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inValue < dtype{ 0 }) + { + return -1; + } + + if (inValue > dtype{ 0 }) + { + return 1; + } + + return 0; + } + + //============================================================================ + // Method Description: + /// Returns an element-wise indication of the sign of a number. + /// + /// The sign function returns - 1 if x < 0, 0 if x == 0, 1 if x > 0. + /// nan is returned for nan inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sign.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray sign(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> int8 { return sign(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/signbit.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/signbit.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7a1f30fda1b52006015997e90c4cf91af4c9d1d1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/signbit.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns element-wise True where signbit is set (less than zero). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.signbit.html + /// + /// @param inValue + /// @return NdArray + /// + template + bool signbit(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue < dtype{ 0 } ? true : false; + } + + //============================================================================ + // Method Description: + /// Returns element-wise True where signbit is set (less than zero). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.signbit.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray signbit(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return signbit(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sin.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sin.hpp new file mode 100644 index 0000000000000000000000000000000000000000..de1b5c9d5fe46994552b258fdbd8d45760d2ba4d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sin.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sin.html + /// + /// @param inValue + /// @return value + /// + template + auto sin(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sin(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sin.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sin(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sin(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinc.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinc.hpp new file mode 100644 index 0000000000000000000000000000000000000000..44bf816ff7345e2f9f9df8b9ab28bc3bf857ef85 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinc.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sinc function. + /// + /// The sinc function is sin(pi*x) / (pi*x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinc.html + /// + /// @param inValue + /// @return value + /// + template + auto sinc(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sin(constants::pi * inValue) / (constants::pi * inValue); + } + + //============================================================================ + // Method Description: + /// Return the sinc function. + /// + /// The sinc function is sin(pi*x) / (pi*x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinc.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sinc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sinc(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..03927dd7c8475d33c46b1c27faae02a9183ebd98 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sinh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Hyperbolic sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinh.html + /// + /// @param inValue + /// @return value + /// + template + auto sinh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sinh(inValue); + } + + //============================================================================ + // Method Description: + /// Hyperbolic sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sinh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sinh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/size.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/size.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3dca94857dc939c980fae47370a2a9d20bedb704 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/size.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the number of elements. + /// + /// @param inArray + /// @return uint32 size + /// + template + uint32 size(const NdArray& inArray) noexcept + { + return inArray.size(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sort.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sort.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7fce03c12b8f193d20f22d0d1cd37ec435ac9afb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sort.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a sorted copy of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sort.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray sort(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + NdArray returnArray(inArray); + returnArray.sort(inAxis); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/split.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/split.hpp new file mode 100644 index 0000000000000000000000000000000000000000..21a0a4a5bdd2677fc5be63febab38893cb45b4d9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/split.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Functions/hsplit.hpp" +#include "NumCpp/Functions/vsplit.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays as views into array. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.split.html + /// + /// @param inArray + /// @param indices: the indices to split + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template = 0> + std::vector> split(const NdArray& inArray, const Indices& indices, Axis inAxis = Axis::ROW) + { + switch (inAxis) + { + case Axis::ROW: + { + return vsplit(inArray, indices); + } + case Axis::COL: + { + return hsplit(inArray, indices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input inAxis must be either Axis::ROW or Axis::COL"); + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sqrt.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sqrt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cddaef150cd28c44cd1bcd463c2f39e6a421d53d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sqrt.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the positive square-root of a value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sqrt.html + /// + /// @param inValue + /// @return value + /// + template + auto sqrt(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sqrt(inValue); + } + + //============================================================================ + // Method Description: + /// Return the positive square-root of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sqrt.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sqrt(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sqrt(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/square.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/square.hpp new file mode 100644 index 0000000000000000000000000000000000000000..567d3cb954aeaca52708e2f31b8a17ee44431abc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/square.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the square of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.square.html + /// + /// @param inValue + /// @return value + /// + template + constexpr dtype square(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return utils::sqr(inValue); + } + + //============================================================================ + // Method Description: + /// Return the square of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.square.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray square(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return square(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stack.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stack.hpp new file mode 100644 index 0000000000000000000000000000000000000000..df954823a960d80a06aa9a87dace95ddbaef2266 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stack.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.stack.html + /// + /// @param begin: iterator to the beginning of the span + /// @param end: iterator to one past the end of the span + /// @param inAxis: the axis to stack + /// @return NdArray + /// + template + NdArray stack(Iterator begin, Iterator end, Axis inAxis) + { + switch (inAxis) + { + case Axis::ROW: + { + return row_stack(begin, end); + } + case Axis::COL: + { + return column_stack(begin, end); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("inAxis must be either ROW or COL."); + return {}; // getting rid of compiler warning + } + } + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @param inAxis: axis to stack the input NdArrays + /// @return NdArray + /// + template + NdArray stack(std::initializer_list> inArrayList, Axis inAxis = Axis::NONE) + { + return detail::stack(inArrayList.begin(), inArrayList.end(), inAxis); + } + + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @param inAxis: axis to stack the input NdArrays + /// @return NdArray + /// + template + NdArray stack(std::vector> inArrayList, Axis inAxis = Axis::NONE) + { + return detail::stack(inArrayList.begin(), inArrayList.end(), inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stdev.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stdev.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fc205e6deaf87f10612439ca669fc2b6805a8855 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/stdev.hpp @@ -0,0 +1,168 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.std.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray stdev(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double meanValue = 0.; + double sum = 0.; + + const auto function = [&sum, &meanValue](dtype value) -> void + { sum += utils::sqr(static_cast(value) - meanValue); }; + + switch (inAxis) + { + case Axis::NONE: + { + meanValue = mean(inArray, inAxis).item(); + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray returnArray = { std::sqrt(sum / inArray.size()) }; + return returnArray; + } + case Axis::COL: + { + NdArray meanValueArray = mean(inArray, inAxis); + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + return stdev(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.std.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray> stdev(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex meanValue(0., 0.); + std::complex sum(0., 0.); + + const auto function = [&sum, &meanValue](std::complex value) -> void + { sum += utils::sqr(complex_cast(value) - meanValue); }; + + switch (inAxis) + { + case Axis::NONE: + { + meanValue = mean(inArray, inAxis).item(); + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray> returnArray = { std::sqrt(sum / static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray> meanValueArray = mean(inArray, inAxis); + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + NdArray> meanValueArray = mean(inArray, inAxis); + NdArray> transposedArray = inArray.transpose(); + NdArray> returnArray(1, transposedArray.numRows()); + for (uint32 row = 0; row < transposedArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = std::complex(0., 0.); + std::for_each(transposedArray.cbegin(row), transposedArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / static_cast(transposedArray.numCols())); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/subtract.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/subtract.hpp new file mode 100644 index 0000000000000000000000000000000000000000..abc2f37f7720795f206bebe11179d6ef67e39659 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/subtract.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray subtract(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray subtract(const NdArray& inArray, dtype value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray subtract(dtype value, const NdArray& inArray) + { + return value - inArray; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> subtract(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> subtract(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> subtract(const NdArray& inArray, const std::complex& value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> subtract(const std::complex& value, const NdArray& inArray) + { + return value - inArray; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> subtract(const NdArray>& inArray, dtype value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> subtract(dtype value, const NdArray>& inArray) + { + return value - inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sum.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sum.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b6cdc1a7c968871ffbfc663cad3d75d0a30cca3a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/sum.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Sum of array elements over a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray sum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.sum(inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swap.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swap.hpp new file mode 100644 index 0000000000000000000000000000000000000000..52e4110733ccfd69cfafdaaddd76a4e464106b5d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swap.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps the contents of two arrays + /// + /// @param inArray1 + /// @param inArray2 + /// + template + void swap(NdArray& inArray1, NdArray& inArray2) noexcept + { + NdArray tmp(std::move(inArray1)); + inArray1 = std::move(inArray2); + inArray2 = std::move(tmp); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapCols.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapCols.hpp new file mode 100644 index 0000000000000000000000000000000000000000..842f8a227e3df89711fd814eee6313bc3fa2cd0e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapCols.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps cols of the array + /// + /// @param inArray + /// @param colIdx1 + /// @param colIdx2 + /// + template + NdArray& swapCols(NdArray& inArray, int32 colIdx1, int32 colIdx2) noexcept + { + inArray.swapCols(colIdx1, colIdx2); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapRows.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapRows.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a8329acee85b27e69fa775215224803bcc236eab --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapRows.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param inArray + /// @param rowIdx1 + /// @param rowIdx2 + /// + template + NdArray& swapRows(NdArray& inArray, int32 rowIdx1, int32 rowIdx2) noexcept + { + inArray.swapRows(rowIdx1, rowIdx2); + return inArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapaxes.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapaxes.hpp new file mode 100644 index 0000000000000000000000000000000000000000..12fe6393e2d4fbbb6043edd2e41d9648ed175943 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/swapaxes.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Interchange two axes of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.swapaxes.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray swapaxes(const NdArray& inArray) + { + return inArray.swapaxes(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/take.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/take.hpp new file mode 100644 index 0000000000000000000000000000000000000000..939af1a342afbf19358e9e54343f486ad8cf214b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/take.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.take.html + /// + /// @param inArray + /// @param inIndices + /// @param inAxis + /// @return NdArray + /// + template = 0> + NdArray take(const NdArray& inArray, const Indices& inIndices, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + return inArray[inIndices]; + } + case Axis::ROW: + { + return inArray(inIndices, inArray.cSlice()); + } + case Axis::COL: + { + return inArray(inArray.rSlice(), inIndices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tan.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tan.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fc76229890dffd8c16017c80033f0bedc0b1be08 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tan.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tan.html + /// + /// @param inValue + /// @return value + /// + template + auto tan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::tan(inValue); + } + + //============================================================================ + // Method Description: + /// Compute tangent element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tan.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto tan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return tan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tanh.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tanh.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1d156c05bc5f76c6b9ceb3707e8047e067d71ecb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tanh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute hyperbolic tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tanh.html + /// + /// @param inValue + /// @return value + /// + template + auto tanh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::tanh(inValue); + } + + //============================================================================ + // Method Description: + /// Compute hyperbolic tangent element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tanh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto tanh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return tanh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tile.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tile.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d999bd23bd50cd910a6f2d505eb356e4bbeaf33d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tile.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array by repeating A the number of times given by reps. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tile.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray tile(const NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + return inArray.repeat(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Construct an array by repeating A the number of times given by reps. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tile.html + /// + /// @param inArray + /// @param inReps + /// @return NdArray + /// + template + NdArray tile(const NdArray& inArray, const Shape& inReps) + { + return inArray.repeat(inReps); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/toStlVector.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/toStlVector.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d55c6bf50642265111383f6973a1d092f3c3f394 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/toStlVector.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Write flattened array to an STL vector + /// + /// @param inArray + /// @return std::vector + /// + template + std::vector toStlVector(const NdArray& inArray) + { + return inArray.toStlVector(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tofile.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tofile.hpp new file mode 100644 index 0000000000000000000000000000000000000000..940a38e94c44407acd71c799f49633241133f136 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tofile.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Write array to a file as binary. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// @param inArray + /// @param inFilename + /// @return None + /// + template + void tofile(const NdArray& inArray, const std::string& inFilename) + { + return inArray.tofile(inFilename); + } + + //============================================================================ + // Method Description: + /// Write array to a file as text. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// @param inArray + /// @param inFilename + /// @param inSep: Separator between array items for text output. + /// @return None + /// + template + void tofile(const NdArray& inArray, const std::string& inFilename, const char inSep) + { + return inArray.tofile(inFilename, inSep); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9c03e6d79b7e0ec6ee568fc0ec2b5175849dd2a0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trace.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sum along diagonals of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trace.html + /// + /// @param inArray + /// @param inOffset: (Offset from main diaganol, default = 0, negative=above, positve=below) + /// @param inAxis (Optional, default ROW) + /// @return NdArray + /// + template + dtype trace(const NdArray& inArray, int16 inOffset = 0, Axis inAxis = Axis::ROW) noexcept + { + return inArray.trace(inOffset, inAxis); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/transpose.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/transpose.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d6853df2a4d8f59ccd56c762a4348284727fe2c7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/transpose.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Permute the dimensions of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.transpose.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray transpose(const NdArray& inArray) + { + return inArray.transpose(); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trapz.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trapz.hpp new file mode 100644 index 0000000000000000000000000000000000000000..21e29f6a01e70affaf8ef32706825423d4dec0d0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trapz.hpp @@ -0,0 +1,167 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Integrate along the given axis using the composite trapezoidal rule. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html + /// + /// @param inArray + /// @param dx: (Optional defaults to 1.) + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray trapz(const NdArray& inArray, double dx = 1., Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + switch (inAxis) + { + case Axis::NONE: + { + double sum = 0.; + for (uint32 i = 0; i < inArray.size() - 1; ++i) + { + sum += static_cast(inArray[i + 1] - inArray[i]) / 2. + static_cast(inArray[i]); + } + + NdArray returnArray = { sum * dx }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inShape.rows, 1); + for (uint32 row = 0; row < inShape.rows; ++row) + { + double sum = 0; + for (uint32 col = 0; col < inShape.cols - 1; ++col) + { + sum += static_cast(inArray(row, col + 1) - inArray(row, col)) / 2. + + static_cast(inArray(row, col)); + } + + returnArray[row] = sum * dx; + } + + return returnArray; + } + case Axis::ROW: + { + return trapz(inArray.transpose(), dx, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Integrate along the given axis using the composite trapezoidal rule. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html + /// + /// @param inArrayY + /// @param inArrayX + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray trapz(const NdArray& inArrayY, const NdArray& inArrayX, Axis inAxis = Axis::NONE) + { + const Shape inShapeY = inArrayY.shape(); + const Shape inShapeX = inArrayX.shape(); + + if (inShapeY != inShapeX) + { + THROW_INVALID_ARGUMENT_ERROR("input x and y arrays should be the same shape."); + } + + switch (inAxis) + { + case Axis::NONE: + { + double sum = 0.; + for (uint32 i = 0; i < inArrayY.size() - 1; ++i) + { + const auto dx = static_cast(inArrayX[i + 1] - inArrayX[i]); + sum += dx * + (static_cast(inArrayY[i + 1] - inArrayY[i]) / 2. + static_cast(inArrayY[i])); + } + + NdArray returnArray = { sum }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inShapeY.rows, 1); + for (uint32 row = 0; row < inShapeY.rows; ++row) + { + double sum = 0; + for (uint32 col = 0; col < inShapeY.cols - 1; ++col) + { + const auto dx = static_cast(inArrayX(row, col + 1) - inArrayX(row, col)); + sum += dx * (static_cast(inArrayY(row, col + 1) - inArrayY(row, col)) / 2. + + static_cast(inArrayY(row, col))); + } + + returnArray[row] = sum; + } + + return returnArray; + } + case Axis::ROW: + { + return trapz(inArrayY.transpose(), inArrayX.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tri.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tri.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fdc3b112e72373b8b386f236d85484e0dd2eb942 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/tri.hpp @@ -0,0 +1,257 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// An array with ones at and below the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(uint32 inN, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN); + returnArray.zeros(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inN) + { + break; + } + + returnArray(row, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and below the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows + /// @param inM: number of columns + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(uint32 inN, uint32 inM, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else if (inOffset < 0) + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN, inM); + returnArray.zeros(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inM) + { + break; + } + + returnArray(row, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + // forward declare + template + NdArray triu(uint32 inN, uint32 inM, int32 inOffset = 0); + + //============================================================================ + // Method Description: + /// Lower triangle of an array. + /// + /// Return a copy of an array with elements above the k - th diagonal zeroed. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tril.html + /// + /// @param inArray: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(const NdArray& inArray, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + auto outArray = inArray.copy(); + outArray.putMask(triu(inShape.rows, inShape.cols, inOffset + 1), 0); + return outArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and above the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows + /// @param inM: number of columns + /// @param inOffset: (the sub-diagonal at and above which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(uint32 inN, uint32 inM, int32 inOffset) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + // because i'm stealing the lines of code from tril and reversing it, this is necessary + inOffset -= 1; + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else if (inOffset < 0) + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN, inM); + returnArray.ones(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inM) + { + break; + } + + returnArray(row, col) = dtype{ 0 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and above the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows and cols + /// @param inOffset: (the sub-diagonal at and above which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(uint32 inN, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return tril(inN, -inOffset).transpose(); + } + + //============================================================================ + // Method Description: + /// Upper triangle of an array. + /// + /// Return a copy of an array with elements below the k - th diagonal zeroed. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.triu.html + /// + /// @param inArray: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(const NdArray& inArray, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + auto outArray = inArray.copy(); + outArray.putMask(tril(inShape.rows, inShape.cols, inOffset - 1), 0); + return outArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trim_zeros.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trim_zeros.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bcd020875ef75f42602b258245ae210a367bd601 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trim_zeros.hpp @@ -0,0 +1,147 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trim the leading and/or trailing zeros from a 1-D array or sequence. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trim_zeros.html + /// + /// @param inArray + /// @param inTrim: ("f" = front, "b" = back, "fb" = front and back) + /// + /// @return NdArray + /// + template + NdArray trim_zeros(const NdArray& inArray, const std::string& inTrim = "fb") + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inTrim == "f") + { + uint32 place = 0; + for (auto value : inArray) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + break; + } + + ++place; + } + + if (place == inArray.size()) + { + return NdArray(0); + } + + NdArray returnArray(1, inArray.size() - place); + stl_algorithms::copy(inArray.cbegin() + place, inArray.cend(), returnArray.begin()); + + return returnArray; + } + + if (inTrim == "b") + { + uint32 place = inArray.size(); + for (uint32 i = inArray.size() - 1; i > 0; --i) + { + if (!utils::essentiallyEqual(inArray[i], dtype{ 0 })) + { + break; + } + + --place; + } + + if (place == 0 || (place == 1 && utils::essentiallyEqual(inArray[0], dtype{ 0 }))) + { + return NdArray(0); + } + + NdArray returnArray(1, place); + stl_algorithms::copy(inArray.cbegin(), inArray.cbegin() + place, returnArray.begin()); + + return returnArray; + } + + if (inTrim == "fb") + { + uint32 placeBegin = 0; + for (auto value : inArray) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + break; + } + + ++placeBegin; + } + + if (placeBegin == inArray.size()) + { + return NdArray(0); + } + + uint32 placeEnd = inArray.size(); + for (uint32 i = inArray.size() - 1; i > 0; --i) + { + if (!utils::essentiallyEqual(inArray[i], dtype{ 0 })) + { + break; + } + + --placeEnd; + } + + if (placeEnd == 0 || (placeEnd == 1 && utils::essentiallyEqual(inArray[0], dtype{ 0 }))) + { + return NdArray(0); + } + + NdArray returnArray(1, placeEnd - placeBegin); + stl_algorithms::copy(inArray.cbegin() + placeBegin, inArray.cbegin() + placeEnd, returnArray.begin()); + + return returnArray; + } + + THROW_INVALID_ARGUMENT_ERROR("trim options are 'f' = front, 'b' = back, 'fb' = front and back."); + return {}; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trunc.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trunc.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b15acf2bd80cf712da49564bf6870412fa0b5ff2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/trunc.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truncated value of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trunc.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype trunc(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::trunc(inValue); + } + + //============================================================================ + // Method Description: + /// Return the truncated value of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trunc.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray trunc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return trunc(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/union1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/union1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9817d62f8c887077dded14443a330643f6a1a299 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/union1d.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the union of two arrays. + /// + /// Return the unique, sorted array of values that are in + /// either of the two input arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.union1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray union1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool { return lhs < rhs; }; + + const auto set1 = unique(inArray1); + const auto set2 = unique(inArray2); + + std::vector res(set1.size() + set2.size()); + const auto last = + stl_algorithms::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unique.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unique.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0d6e05adce8c99f6c36ff38cec20184d549584b1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unique.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the unique elements of an array. + /// + /// Returns the sorted unique elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unique.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray unique(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool + { return utils::essentiallyEqual(lhs, rhs); }; + + const auto sorted = sort(inArray); + + std::vector res(sorted.size()); + const auto last = stl_algorithms::unique_copy(sorted.begin(), sorted.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unpackbits.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unpackbits.hpp new file mode 100644 index 0000000000000000000000000000000000000000..570b765e1dd080f713237e3cac082b7c12e7533d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unpackbits.hpp @@ -0,0 +1,161 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Unpacks elements of a uint8 array into a binary-valued output array. + /// + /// Each element of a represents a bit - field that should be unpacked into a binary - + /// valued output array.The shape of the output array is either 1 - D(if axis is None) or + /// the same shape as the input array with unpacking done along the axis specified. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html + /// + /// @param a: An array of uint8 whose elements should be unpacked to bits. + /// @param axis: The dimension over which bit-unpacking is done. None implies unpacking the flattened array. + /// @return NdArray + /// + inline NdArray unpackbitsLittleEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + NdArray result(1, a.size() * 8); + + for (NdArray::size_type byte = 0; byte < a.size(); ++byte) + { + const auto startIdx = byte * 8; + const auto byteValue = a[byte]; + + for (uint8 bit = 0; bit < 8; ++bit) + { + result[startIdx + bit] = static_cast((byteValue & (uint8{ 1 } << bit)) >> bit); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + NdArray result(aShape.rows, aShape.cols * 8); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, unpackbitsLittleEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return unpackbitsLittleEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Unpacks elements of a uint8 array into a binary-valued output array. + /// + /// Each element of a represents a bit - field that should be unpacked into a binary - + /// valued output array.The shape of the output array is either 1 - D(if axis is None) or + /// the same shape as the input array with unpacking done along the axis specified. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html + /// + /// @param a: An array of uint8 whose elements should be unpacked to bits. + /// @param axis: The dimension over which bit-unpacking is done. None implies unpacking the flattened array. + /// @return NdArray + /// + inline NdArray unpackbitsBigEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + NdArray result(1, a.size() * 8); + + for (NdArray::size_type byte = 0; byte < a.size(); ++byte) + { + const auto startIdx = byte * 8; + const auto byteValue = a[byte]; + + for (uint8 bit = 0; bit < 8; ++bit) + { + const auto bitToMask = static_cast(7 - bit); + result[startIdx + bit] = + static_cast((byteValue & (uint8{ 1 } << bitToMask)) >> bitToMask); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + NdArray result(aShape.rows, aShape.cols * 8); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, unpackbitsBigEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return unpackbitsBigEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unwrap.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unwrap.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2e9299a41d3b812671d00d3a309b8f8525fe5e81 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/unwrap.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Unwrap by changing deltas between values to 2*pi complement. + /// Unwraps to [-pi, pi]. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unwrap.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype unwrap(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::atan2(std::sin(inValue), std::cos(inValue))); + } + + //============================================================================ + // Method Description: + /// Unwrap by changing deltas between values to 2*pi complement. + /// Unwraps to [-pi, pi]. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unwrap.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray unwrap(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return unwrap(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vander.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vander.hpp new file mode 100644 index 0000000000000000000000000000000000000000..72edd363e827404f05c265542760e56788b01b9b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vander.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Generate a Vandermonde matrix. + /// The columns of the output matrix are powers of the input vector. The order of the powers is determined by the + /// increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector + /// raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named + /// for Alexandre- Theophile Vandermonde. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vander.html + /// + /// @param x: 1-D input array, otherwise the array will be flattened + /// @param n: Number of columns in the output. If N is not specified, a square array is returned (N = len(x)). + /// @param increasing: Order of the powers of the columns. If True, the powers increase from left to right, if False + /// (the default) they are reversed. + /// + /// @return NdArray + /// + template + auto vander(const NdArray& x, uint32 n, bool increasing = true) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray(), uint32{ 0 }))> result(x.size(), n); + for (uint32 row = 0; row < x.size(); ++row) + { + for (uint32 col = 0; col < n; ++col) + { + result(row, col) = std::pow(x[row], col); + } + } + + if (!increasing) + { + return fliplr(result); + } + + return result; + } + + //============================================================================ + // Method Description: + /// Generate a Vandermonde matrix. + /// The columns of the output matrix are powers of the input vector. The order of the powers is determined by the + /// increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector + /// raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named + /// for Alexandre- Theophile Vandermonde. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vander.html + /// + /// @param x: 1-D input array, otherwise the array will be flattened + /// @param increasing: Order of the powers of the columns. If True, the powers increase from left to right, if False + /// (the default) they are reversed. + /// + /// @return NdArray + /// + template + auto vander(const NdArray& x, bool increasing = true) + { + return vander(x, x.size(), increasing); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/var.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/var.hpp new file mode 100644 index 0000000000000000000000000000000000000000..76f70ec17baa897753826ee64216016a754fdc96 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/var.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/stdev.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.var.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray var(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray stdValues = stdev(inArray, inAxis); + const auto function = [](double& value) -> void { value *= value; }; + + stl_algorithms::for_each(stdValues.begin(), stdValues.end(), function); + return stdValues; + } + + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.var.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> var(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray> stdValues = stdev(inArray, inAxis); + const auto function = [](std::complex& value) -> void { value *= value; }; + + stl_algorithms::for_each(stdValues.begin(), stdValues.end(), function); + return stdValues; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vsplit.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vsplit.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0077c5ee717b9adcfd6e3cd2632161ff5b0875f4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vsplit.hpp @@ -0,0 +1,105 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/split.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays vertically (row-wise). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html + /// + /// @param inArray + /// @param indices: the indices to split + /// + /// @return NdArray + /// + template = 0> + std::vector> vsplit(const NdArray& inArray, const Indices& indices) + { + const auto numRows = static_cast(inArray.numRows()); + NdArray uniqueIndices(1, indices.size()); + stl_algorithms::transform(indices.begin(), + indices.end(), + uniqueIndices.begin(), + [numRows](auto index) noexcept -> int32 + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index = std::max(index + numRows, int32{ 0 }); + } + } + if (index > numRows - 1) + { + index = numRows - 1; + } + + return static_cast(index); + }); + uniqueIndices = unique(uniqueIndices); + + std::vector> splits{}; + splits.reserve(uniqueIndices.size() + 1); + + const auto cSlice = inArray.cSlice(); + int32 lowerIdx = 0; + for (const auto index : uniqueIndices) + { + if (index == 0) + { + splits.push_back(NdArray(Shape(0, inArray.numCols()))); + continue; + } + else + { + splits.push_back(inArray(Slice(lowerIdx, index), cSlice)); + } + + lowerIdx = index; + } + + if (lowerIdx < numRows - 1) + { + splits.push_back(inArray(Slice(lowerIdx, numRows), cSlice)); + } + else + { + splits.push_back(inArray(-1, cSlice)); + } + + return splits; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vstack.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vstack.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bda447ee859bf39abc53c55ebb2cbbb0670e8c30 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/vstack.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.vstack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray vstack(std::initializer_list> inArrayList) + { + return detail::row_stack(inArrayList.begin(), inArrayList.end()); + } + + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.vstack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray vstack(std::vector> inArrayList) + { + return detail::row_stack(inArrayList.begin(), inArrayList.end()); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/where.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/where.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c8e0e54d468a1c9376fee33f9f6c824d7b51577b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/where.hpp @@ -0,0 +1,203 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, const NdArray& inA, const NdArray& inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeA = inA.shape(); + if (shapeA != inB.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input inA and inB must be the same shapes."); + } + + if (shapeMask != shapeA) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA[idx]; + } + else + { + outArray[idx] = inB[idx]; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, const NdArray& inA, dtype inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeA = inA.shape(); + if (shapeMask != shapeA) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA[idx]; + } + else + { + outArray[idx] = inB; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, dtype inA, const NdArray& inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeB = inB.shape(); + if (shapeMask != shapeB) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA; + } + else + { + outArray[idx] = inB[idx]; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, dtype inA, dtype inB) + { + auto outArray = NdArray(inMask.shape()); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA; + } + else + { + outArray[idx] = inB; + } + ++idx; + } + + return outArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap.hpp new file mode 100644 index 0000000000000000000000000000000000000000..13a62bd2945cc2b1e13b00d04475299a9e0310b8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NdArray Functions +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" + +namespace nc +{ + /** + * @brief Wrap the input angle to [-pi, pi] + * + * @param inAngle: in radians + * @return Wrapped angle + */ + template + double wrap(dtype inAngle) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + auto angle = std::fmod(static_cast(inAngle) + constants::pi, constants::twoPi); + if (angle < 0.) + { + angle += constants::twoPi; + } + + return angle - constants::pi; + } + + /** + * @brief Wrap the input angle to [-pi, pi] + * + * @param inAngles: in radians + * @return Wrapped angles + */ + template + NdArray wrap(const NdArray& inAngles) noexcept + { + NdArray returnArray(inAngles.size()); + stl_algorithms::transform(inAngles.begin(), + inAngles.end(), + returnArray.begin(), + [](const auto angle) noexcept -> double { return wrap(angle); }); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap2Pi.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap2Pi.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4110b2cf329e3ab582b4523f30a78962c764179c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/wrap2Pi.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NdArray Functions +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" + +namespace nc +{ + /** + * @brief Wrap the input angle to [0, 2*pi] + * + * @param inAngle: in radians + * @returns Wrapped angle + */ + template + double wrap2Pi(dtype inAngle) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + auto angle = std::fmod(static_cast(inAngle), constants::twoPi); + if (angle < 0.) + { + angle += constants::twoPi; + } + + return angle; + } + + /** + * @brief Wrap the input angle to [0, 2*pi] + * + * @param inAngles: in radians + * @returns Wrapped angles + */ + template + NdArray wrap2Pi(const NdArray& inAngles) noexcept + { + NdArray returnArray(inAngles.size()); + stl_algorithms::transform(inAngles.begin(), + inAngles.end(), + returnArray.begin(), + [](const auto angle) noexcept -> double { return wrap2Pi(angle); }); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fbc9fbf39407a44d7495c4c6c49a282da2a19086 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inSquareSize + /// @return NdArray + /// + template + NdArray zeros(uint32 inSquareSize) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inSquareSize, dtype{ 0 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray zeros(uint32 inNumRows, uint32 inNumCols) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inNumRows, inNumCols, dtype{ 0 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray zeros(const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inShape, dtype{ 0 }); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros_like.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros_like.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3a771295c6d112e14fee435854096e7c32e13a86 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Functions/zeros_like.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray zeros_like(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + returnArray.zeros(); + return returnArray; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing.hpp new file mode 100644 index 0000000000000000000000000000000000000000..78b54a4e92ff4fae553477260aba9224473c436e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing.hpp @@ -0,0 +1,39 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for basic image processing +/// +#pragma once + +#include "NumCpp/ImageProcessing/Centroid.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/ImageProcessing/ClusterMaker.hpp" +#include "NumCpp/ImageProcessing/Pixel.hpp" +#include "NumCpp/ImageProcessing/applyThreshold.hpp" +#include "NumCpp/ImageProcessing/centroidClusters.hpp" +#include "NumCpp/ImageProcessing/clusterPixels.hpp" +#include "NumCpp/ImageProcessing/generateCentroids.hpp" +#include "NumCpp/ImageProcessing/generateThreshold.hpp" +#include "NumCpp/ImageProcessing/windowExceedances.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Centroid.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Centroid.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d231cc01ecec7dddeaaf7bb8c35ba631db72e273 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Centroid.hpp @@ -0,0 +1,340 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// holds the information for a centroid +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/centerOfMass.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// holds the information for a centroid + template + class Centroid + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + using accumulator_t = typename std::conditional::value, int64, double>::type; + + //============================================================================= + // Description: + /// defualt constructor needed by containers + /// + Centroid() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inCluster + /// + explicit Centroid(const Cluster& inCluster) : + intensity_(inCluster.intensity()), + eod_(inCluster.eod()) + { + centerOfMass(inCluster); + setEllipseProperties(inCluster); + } + + //============================================================================= + // Description: + /// gets the centroid row + /// + /// @return centroid row + /// + [[nodiscard]] double row() const noexcept + { + return row_; + } + + //============================================================================= + // Description: + /// gets the centroid col + /// + /// @return centroid col + /// + [[nodiscard]] double col() const noexcept + { + return col_; + } + + //============================================================================= + // Description: + /// gets the centroid intensity + /// + /// @return centroid intensity + /// + [[nodiscard]] accumulator_t intensity() const noexcept + { + return intensity_; + } + + //============================================================================= + // Description: + /// returns the estimated eod of the centroid + /// + /// @return star id + /// + [[nodiscard]] double eod() const noexcept + { + return eod_; + } + + //============================================================================= + // Description: + /// returns the ellipse semi-major axis a + /// + /// @return a + /// + [[nodiscard]] double a() const noexcept + { + return a_; + } + + //============================================================================= + + // Description: + /// returns the ellipse semi-minor axis b + /// + /// @return b + /// + [[nodiscard]] double b() const noexcept + { + return b_; + } + + //============================================================================= + // Description: + /// returns the ellipse eccentricity + /// + /// @return eccentricity + /// + [[nodiscard]] double eccentricity() const noexcept + { + return eccentricity_; + } + + //============================================================================= + + // Description: + /// returns the ellipse semi-minor axis orientation + /// + /// @return orientation + /// + [[nodiscard]] double orientation() const noexcept + { + return orientation_; + } + + //============================================================================= + // Description: + /// returns the centroid as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "row = " + utils::num2str(row_) + " col = " + utils::num2str(col_) + + " intensity = " + utils::num2str(intensity_) + " eod = " + utils::num2str(eod_) + + " a = " + utils::num2str(a_) + " b = " + utils::num2str(b_) + + " eccentricity = " + utils::num2str(eccentricity_) + + " orientation = " + utils::num2str(orientation_) + '\n'; + + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Centroid object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator==(const Centroid& rhs) const noexcept + { + return (utils::essentiallyEqual(row_, rhs.row_) && utils::essentiallyEqual(col_, rhs.col_) && + utils::essentiallyEqual(intensity_, rhs.intensity_) && utils::essentiallyEqual(eod_, rhs.eod_) && + utils::essentiallyEqual(a_, rhs.a_) && utils::essentiallyEqual(b_, rhs.b_) && + utils::essentiallyEqual(eccentricity_, rhs.eccentricity_) && + utils::essentiallyEqual(orientation_, rhs.orientation_)); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator!=(const Centroid& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// less than operator for std::sort algorithm; + /// NOTE: std::sort sorts in ascending order. Since I want to sort + /// the centroids in descensing order, I am purposefully defining + /// this operator backwards! + /// + /// @param rhs + /// + /// @return bool + /// + bool operator<(const Centroid& rhs) const noexcept + { + return intensity_ < rhs.intensity_ ? false : true; + } + + //============================================================================= + // Description: + /// ostream operator + /// + /// @param inStream + /// @param inCentriod + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Centroid& inCentriod) + { + inStream << inCentriod.str(); + return inStream; + } + + private: + //==================================Attributes================================/// + double row_{ 0. }; + double col_{ 0. }; + accumulator_t intensity_{ 0 }; + double eod_{ 0. }; + /// The ellipse semi-major axis a + double a_{}; + /// The ellipse semi-minor axis b + double b_{}; + /// The centriod eccentricity + double eccentricity_{}; + /// The centriod ellipse orientation in radians. Measured counter-clockwise from +x axis + double orientation_{}; + + //============================================================================= + // Description: + /// center of mass algorithm; + /// WARNING: if both positive and negative values are present in the cluster, + /// it can lead to an undefined COM. + /// + /// @param inCluster + /// + void centerOfMass(const Cluster& inCluster) + { + const Shape clusterShape(inCluster.height(), inCluster.width()); + NdArray clusterArray(clusterShape); + clusterArray.zeros(); + + const uint32 rowMin = inCluster.rowMin(); + const uint32 colMin = inCluster.colMin(); + + for (auto& pixel : inCluster) + { + clusterArray(pixel.row - rowMin, pixel.col - colMin) = pixel.intensity; + } + + const auto rowCol = nc::centerOfMass(clusterArray); + row_ = rowCol.front() + rowMin; + col_ = rowCol.back() + colMin; + } + + //============================================================================= + // Description: + /// Sets the cluster ellipse properties + /// + /// @param inCluster + /// + void setEllipseProperties(const Cluster& inCluster) noexcept + { + constexpr auto two = static_cast(2.); + + auto m20 = static_cast(0.); + auto m02 = static_cast(0.); + auto m11 = static_cast(0.); + + for (typename Cluster::const_iterator iter = inCluster.begin(); iter != inCluster.end(); ++iter) + { + const auto& pixel = *iter; + const double deltaX = pixel.col - col_; + const double deltaY = pixel.row - row_; + + m11 += deltaX * deltaY; + m20 += utils::sqr(deltaX); + m02 += utils::sqr(deltaY); + } + + const auto numPixels = static_cast(inCluster.size()); + m11 /= numPixels; + m20 /= numPixels; + m02 /= numPixels; + + double piece1 = m20 + m02; + piece1 /= two; + + double piece2 = std::sqrt(static_cast(4.) * utils::sqr(m11) + utils::sqr(m20 - m02)); + piece2 /= two; + + const double lambda1 = piece1 - piece2; + const double lambda2 = piece1 + piece2; + + eccentricity_ = std::sqrt(static_cast(1.) - lambda1 / lambda2); + orientation_ = static_cast(-0.5) * std::atan2(two * m11, m20 - m02); + a_ = two * std::sqrt(lambda2); + b_ = two * std::sqrt(lambda1); + } + }; +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Cluster.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Cluster.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ab3015482e7d96aa6e5a0407b611e56efd2ce17c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Cluster.hpp @@ -0,0 +1,371 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds the information for a cluster of pixels +/// + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Pixel.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// Holds the information for a cluster of pixels + template + class Cluster + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //================================Typedefs=============================== + using const_iterator = typename std::vector>::const_iterator; + using accumulator_t = typename std::conditional::value, int64, double>::type; + + //============================================================================= + // Description: + /// default constructor needed by containers + /// + Cluster() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inClusterId + /// + explicit Cluster(uint32 inClusterId) noexcept : + clusterId_(inClusterId) + { + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator==(const Cluster& rhs) const noexcept + { + if (pixels_.size() != rhs.pixels_.size()) + { + return false; + } + + return stl_algorithms::equal(begin(), end(), rhs.begin()); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator!=(const Cluster& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// access operator, no bounds checking + /// + /// @param inIndex + /// + /// @return Pixel + /// + const Pixel& operator[](uint32 inIndex) const noexcept + { + return pixels_[inIndex]; + } + + //============================================================================= + // Description: + /// access method with bounds checking + /// + /// @param inIndex + /// + /// @return Pixel + /// + [[nodiscard]] const Pixel& at(uint32 inIndex) const + { + if (inIndex >= pixels_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("index exceeds cluster size."); + } + return pixels_[inIndex]; + } + + //============================================================================= + // Description: + /// returns in iterator to the beginning pixel of the cluster + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return pixels_.cbegin(); + } + + //============================================================================= + // Description: + /// returns in iterator to the 1 past the end pixel of the cluster + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return pixels_.cend(); + } + + //============================================================================= + // Description: + /// returns the number of pixels in the cluster + /// + /// @return number of pixels in the cluster + /// + [[nodiscard]] uint32 size() const noexcept + { + return static_cast(pixels_.size()); + } + + //============================================================================= + // Description: + /// returns the minimum row number of the cluster + /// + /// @return minimum row number of the cluster + /// + [[nodiscard]] uint32 clusterId() const noexcept + { + return clusterId_; + } + + //============================================================================= + // Description: + /// returns the minimum row number of the cluster + /// + /// @return minimum row number of the cluster + /// + [[nodiscard]] uint32 rowMin() const noexcept + { + return rowMin_; + } + + //============================================================================= + // Description: + /// returns the maximum row number of the cluster + /// + /// @return maximum row number of the cluster + /// + [[nodiscard]] uint32 rowMax() const noexcept + { + return rowMax_; + } + + //============================================================================= + // Description: + /// returns the minimum column number of the cluster + /// + /// @return minimum column number of the cluster + /// + [[nodiscard]] uint32 colMin() const noexcept + { + return colMin_; + } + + //============================================================================= + // Description: + /// returns the maximum column number of the cluster + /// + /// @return maximum column number of the cluster + /// + [[nodiscard]] uint32 colMax() const noexcept + { + return colMax_; + } + + //============================================================================= + // Description: + /// returns the number of rows the cluster spans + /// + /// @return number of rows + /// + [[nodiscard]] uint32 height() const noexcept + { + return rowMax_ - rowMin_ + 1; + } + + //============================================================================= + // Description: + /// returns the number of columns the cluster spans + /// + /// @return number of columns + /// + [[nodiscard]] uint32 width() const noexcept + { + return colMax_ - colMin_ + 1; + } + + //============================================================================= + // Description: + /// returns the summed intensity of the cluster + /// + /// @return summed cluster intensity + /// + [[nodiscard]] accumulator_t intensity() const noexcept + { + return intensity_; + } + + //============================================================================= + // Description: + /// returns the intensity of the peak pixel in the cluster + /// + /// @return peak pixel intensity + /// + [[nodiscard]] dtype peakPixelIntensity() const noexcept + { + return peakPixelIntensity_; + } + + //============================================================================= + // Description: + /// returns the cluster estimated energy on detector (EOD) + /// + /// @return eod + /// + [[nodiscard]] double eod() const noexcept + { + return eod_; + } + + //============================================================================= + // Description: + /// adds a pixel to the cluster + /// + /// @param inPixel + /// + void addPixel(const Pixel& inPixel) + { + pixels_.push_back(inPixel); + intensity_ += static_cast(inPixel.intensity); + + // adjust the cluster bounds + rowMin_ = std::min(rowMin_, inPixel.row); + rowMax_ = std::max(rowMax_, inPixel.row); + colMin_ = std::min(colMin_, inPixel.col); + colMax_ = std::max(colMax_, inPixel.col); + peakPixelIntensity_ = std::max(peakPixelIntensity_, inPixel.intensity); + + // calculate the energy on detector estimate + eod_ = static_cast(peakPixelIntensity_) / static_cast(intensity_); + } + + //============================================================================= + // Description: + /// returns a string representation of the cluster + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + std::string out; + uint32 counter = 0; + std::for_each(begin(), + end(), + [&](const Pixel& pixel) + { out += "Pixel " + utils::num2str(counter++) + ":" + pixel.str(); }); + + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Cluster object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// osstream operator + /// + /// @param inStream + /// @param inCluster + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Cluster& inCluster) + { + inStream << inCluster.str(); + return inStream; + } + + private: + //================================Attributes=============================== + /// The cluster id + int32 clusterId_{ -1 }; + /// The pixels that make up the cluster + std::vector> pixels_{}; + /// The bounding box minimum row of the cluster. + uint32 rowMin_{ std::numeric_limits::max() }; // largest possible number + /// The bounding box maximum row of the cluster. + uint32 rowMax_{ 0 }; + /// The bounding box minimum col of the cluster. + uint32 colMin_{ std::numeric_limits::max() }; // largest possible number + /// The bounding box maximum row of the cluster. + uint32 colMax_{ 0 }; + /// The total summed intensity of the pixels in the cluster. + accumulator_t intensity_{ 0 }; + /// The peak pixel intensity of the cluster + dtype peakPixelIntensity_{ 0 }; + /// The minimum pixel count value of the cluster + dtype minPixel{}; + /// The maximum pixel count value of the cluster + dtype maxPixel{}; + /// The cluster energy on detector + double eod_{ 1. }; + }; +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4bb29b2a7018bee10d217d00299f411039790208 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp @@ -0,0 +1,365 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Clusters exceedance data into contiguous groups +/// + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================= + // Class Description: + /// Clusters exceedance data into contiguous groups + template + class ClusterMaker + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //================================Typedefs===================================== + using const_iterator = typename std::vector>::const_iterator; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inXcdArrayPtr: pointer to exceedance array + /// @param inIntensityArrayPtr: pointer to intensity array + /// @param inBorderWidth: border to apply around exceedance pixels post clustering (default 0) + /// + /// @return None + /// + ClusterMaker(const NdArray* const inXcdArrayPtr, + const NdArray* const inIntensityArrayPtr, + uint8 inBorderWidth = 0) : + xcds_(inXcdArrayPtr), + intensities_(inIntensityArrayPtr) + { + if (xcds_->shape() != intensities_->shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input xcd and intensity arrays must be the same shape."); + } + + shape_ = xcds_->shape(); + + // convert the NdArray of booleans to a vector of exceedances + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + if (xcds_->operator()(row, col)) + { + const Pixel thePixel(row, col, intensities_->operator()(row, col)); + xcdsVec_.push_back(thePixel); + } + } + } + + runClusterMaker(); + + for (uint8 i = 0; i < inBorderWidth; ++i) + { + expandClusters(); + } + } + + //============================================================================= + // Description: + /// returns the number of clusters in the frame + /// + /// @return number of clusters + /// + uint32 size() noexcept + { + return static_cast(clusters_.size()); + } + + //============================================================================= + // Description: + /// access operator, no bounds checking + /// + /// @param inIndex + /// + /// @return Cluster + /// + const Cluster& operator[](uint32 inIndex) const noexcept + { + return clusters_[inIndex]; + } + + //============================================================================= + // Description: + /// access method with bounds checking + /// + /// @param inIndex + /// + /// @return Cluster + /// + [[nodiscard]] const Cluster& at(uint32 inIndex) const + { + if (inIndex >= clusters_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("index exceeds cluster size."); + } + return clusters_[inIndex]; + } + + //============================================================================= + // Description: + /// returns in iterator to the beginning cluster of the container + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return clusters_.cbegin(); + } + + //============================================================================= + // Description: + /// returns in iterator to the 1 past the end cluster of the container + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return clusters_.cend(); + } + + private: + //==================================Attributes================================= + const NdArray* const xcds_{}; + const NdArray* const intensities_{}; + std::vector> xcdsVec_{}; + + Shape shape_{}; + + std::vector> clusters_{}; + + //============================================================================= + // Description: + /// checks that the input row and column have not fallen off of the edge + /// + /// @param inRow + /// @param inCol + /// + /// @return returns a pixel object clipped to the image boundaries + /// + Pixel makePixel(int32 inRow, int32 inCol) noexcept + { + // Make sure that on the edges after i've added or subtracted 1 from the row and col that + // i haven't gone over the edge + const uint32 row = std::min(static_cast(std::max(inRow, 0)), shape_.rows - 1); + const uint32 col = std::min(static_cast(std::max(inCol, 0)), shape_.cols - 1); + const dtype intensity = intensities_->operator()(row, col); + + return Pixel(row, col, intensity); + } + + //============================================================================= + // Description: + /// finds all of the neighboring pixels to the input pixel + /// + /// @param inPixel + /// @param outNeighbors + /// @return None + /// + void findNeighbors(const Pixel& inPixel, std::set>& outNeighbors) + { + // using a set will auto take care of adding duplicate pixels on the edges + + // the 8 surrounding neighbors + const auto row = static_cast(inPixel.row); + const auto col = static_cast(inPixel.col); + + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col)); + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col + 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row, col + 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col + 1)); + } + + //============================================================================= + // Description: + /// finds all of the neighboring pixels to the input pixel that are NOT exceedances + /// + /// @param inPixel + /// @param outNeighbors + /// + /// @return vector of non exceedance neighboring pixels + /// + void findNeighborNotXcds(const Pixel& inPixel, std::vector>& outNeighbors) + { + std::set> neighbors; + findNeighbors(inPixel, neighbors); + + // check if the neighboring pixels are exceedances and insert into the xcd vector + for (auto& pixel : neighbors) + { + if (!xcds_->operator()(pixel.row, pixel.col)) + { + outNeighbors.push_back(pixel); + } + } + } + + //============================================================================= + // Description: + /// finds the pixel index of neighboring pixels + /// + /// @param inPixel + /// @param outNeighbors + /// + /// @return vector of neighboring pixel indices + /// + void findNeighborXcds(const Pixel& inPixel, std::vector& outNeighbors) + { + std::set> neighbors; + findNeighbors(inPixel, neighbors); + std::vector> neighborXcds; + + // check if the neighboring pixels are exceedances and insert into the xcd vector + for (auto& pixel : neighbors) + { + if (xcds_->operator()(pixel.row, pixel.col)) + { + neighborXcds.push_back(pixel); + } + } + + // loop through the neighbors and find the cooresponding index into exceedances_ + for (auto& pixel : neighborXcds) + { + auto theExceedanceIter = std::find(xcdsVec_.begin(), xcdsVec_.end(), pixel); + outNeighbors.push_back(static_cast(theExceedanceIter - xcdsVec_.begin())); + } + } + + //============================================================================= + // Description: + /// workhorse method that performs the clustering algorithm + /// + void runClusterMaker() + { + uint32 clusterId = 0; + + for (auto& currentPixel : xcdsVec_) + { + // not already visited + if (currentPixel.clusterId == -1) + { + Cluster newCluster(clusterId); // a new cluster + currentPixel.clusterId = clusterId; + newCluster.addPixel(currentPixel); // assign pixel to cluster + + // get the neighbors + std::vector neighborIds; + findNeighborXcds(currentPixel, neighborIds); + if (neighborIds.empty()) + { + clusters_.push_back(newCluster); + ++clusterId; + continue; + } + + // loop through the neighbors + for (uint32 neighborsIdx = 0; neighborsIdx < neighborIds.size(); ++neighborsIdx) + { + Pixel& currentNeighborPixel = xcdsVec_[neighborIds[neighborsIdx]]; + + // go to neighbors + std::vector newNeighborIds; + findNeighborXcds(currentNeighborPixel, newNeighborIds); + + // loop through the new neighbors and add them to neighbors + for (auto newNeighborId : newNeighborIds) + { + // not already in neighbors + if (std::find(neighborIds.begin(), neighborIds.end(), newNeighborId) == neighborIds.end()) + { + neighborIds.push_back(newNeighborId); + } + } + + // not already assigned to a cluster + if (currentNeighborPixel.clusterId == -1) + { + currentNeighborPixel.clusterId = clusterId; + newCluster.addPixel(currentNeighborPixel); + } + } + + clusters_.push_back(std::move(newCluster)); + ++clusterId; + } + } + } + + //============================================================================= + // Description: + /// 3x3 dialates the clusters + /// + void expandClusters() + { + // loop through the clusters + for (auto& theCluster : clusters_) + { + // loop through the pixels of the cluster + for (auto& thePixel : theCluster) + { + std::vector> neighborsNotXcds; + findNeighborNotXcds(thePixel, neighborsNotXcds); + + // loop through the neighbors and if they haven't already been added to the cluster, add them + for (auto& newPixel : neighborsNotXcds) + { + if (std::find(theCluster.begin(), theCluster.end(), newPixel) == theCluster.end()) + { + theCluster.addPixel(newPixel); + } + } + } + } + } + }; +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Pixel.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Pixel.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fca9d2cb81452aa1f94b76782852976f4d506353 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/Pixel.hpp @@ -0,0 +1,166 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds the information for a single pixel +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// Holds the information for a single pixel + template + class Pixel + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //==================================Attributes================================ + mutable int32 clusterId{ -1 }; + uint32 row{ 0 }; + uint32 col{ 0 }; + dtype intensity{ 0 }; + + //============================================================================= + // Description: + /// defualt constructor needed by containers + /// + constexpr Pixel() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inRow: pixel row + /// @param inCol: pixel column + /// @param inIntensity: pixel intensity + /// + constexpr Pixel(uint32 inRow, uint32 inCol, dtype inIntensity) noexcept : + row(inRow), + col(inCol), + intensity(inIntensity) + { + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + constexpr bool operator==(const Pixel& rhs) const noexcept + { + return utils::essentiallyEqual(row, rhs.row) && utils::essentiallyEqual(col, rhs.col) && + utils::essentiallyEqual(intensity, rhs.intensity); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + constexpr bool operator!=(const Pixel& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// less than operator for std::sort algorithm and std::set<>; + /// NOTE: std::sort sorts in ascending order. Since I want to sort + /// the centroids in descensing order, I am purposefully defining + /// this operator backwards! + /// + /// @param rhs + /// + /// @return bool + /// + bool operator<(const Pixel& rhs) const noexcept + { + if (row < rhs.row) + { + return true; + } + if (row == rhs.row) + { + return static_cast(col < rhs.col); + } + + return false; + } + + //============================================================================= + // Description: + /// returns the pixel information as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "row = " + utils::num2str(row) + " col = " + utils::num2str(col); + out += " intensity = " + utils::num2str(intensity) + '\n'; + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Pixel object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// osstream operator + /// + /// @param inStream + /// @param inPixel + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Pixel& inPixel) + { + inStream << inPixel.str(); + return inStream; + } + }; +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d9a63533094dd71b14fdfde8adfdf8cfcf300ef7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Applies a threshold to an image +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Applies a threshold to an image + /// + /// @param inImageArray + /// @param inThreshold + /// @return NdArray of booleans of pixels that exceeded the threshold + /// + template + NdArray applyThreshold(const NdArray& inImageArray, dtype inThreshold) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inImageArray > inThreshold; + } +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2f22f48eb2d1d86a17a4a63f2117e4856d2744ab --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Center of Mass centroids clusters +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/ImageProcessing/Centroid.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Center of Mass centroids clusters + /// + /// @param inClusters + /// @return std::vector + /// + template + std::vector> centroidClusters(const std::vector>& inClusters) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::vector> centroids(inClusters.size()); + stl_algorithms::transform(inClusters.begin(), + inClusters.end(), + centroids.begin(), + [](const auto& cluster) -> Centroid { return Centroid(cluster); }); + return centroids; + } +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp new file mode 100644 index 0000000000000000000000000000000000000000..88982ca78fc86c81c0334178950836fc77583d80 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp @@ -0,0 +1,59 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Clusters exceedance pixels from an image +/// + +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/ImageProcessing/ClusterMaker.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Clusters exceedance pixels from an image + /// + /// @param inImageArray + /// @param inExceedances + /// @param inBorderWidth: border to apply around exceedance pixels post clustering (default 0) + /// @return std::vector + /// + template + std::vector> + clusterPixels(const NdArray& inImageArray, const NdArray& inExceedances, uint8 inBorderWidth = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + ClusterMaker clusterMaker(&inExceedances, &inImageArray, inBorderWidth); + return std::vector>(clusterMaker.begin(), clusterMaker.end()); + } +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a4b2b9504f7c621febc01ff0b3e03571647d6598 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Generates a list of centroids givin an input exceedance rate +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/applyThreshold.hpp" +#include "NumCpp/ImageProcessing/centroidClusters.hpp" +#include "NumCpp/ImageProcessing/clusterPixels.hpp" +#include "NumCpp/ImageProcessing/generateThreshold.hpp" +#include "NumCpp/ImageProcessing/windowExceedances.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Generates a list of centroids givin an input exceedance + /// rate + /// + /// @param inImageArray + /// @param inRate: exceedance rate + /// @param inWindowType: (string "pre", or "post" for where to apply the exceedance windowing) + /// @param inBorderWidth: border to apply (default 0) + /// @return std::vector + /// + template + std::vector> generateCentroids(const NdArray& inImageArray, + double inRate, + const std::string& inWindowType, + uint8 inBorderWidth = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + uint8 borderWidthPre = 0; + uint8 borderWidthPost = 0; + if (inWindowType == "pre") + { + borderWidthPre = inBorderWidth; + } + else if (inWindowType == "post") + { + borderWidthPost = inBorderWidth; + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input window type options are ['pre', 'post']"); + } + + // generate the threshold + dtype threshold = generateThreshold(inImageArray, inRate); + + // apply the threshold to get xcds + NdArray xcds = applyThreshold(inImageArray, threshold); + + // window around the xcds + if (borderWidthPre > 0) + { + xcds = windowExceedances(xcds, borderWidthPre); + } + + // cluster the exceedances + std::vector> clusters = clusterPixels(inImageArray, xcds, borderWidthPost); + + // centroid the clusters + return centroidClusters(clusters); + } +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp new file mode 100644 index 0000000000000000000000000000000000000000..72429b4a859f024dfd9f2b33aae20420a7a7ea95 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp @@ -0,0 +1,142 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Generates a threshold +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Calculates a threshold such that the input rate of pixels + /// exceeds the threshold. Really should only be used for integer + /// input array values. If using floating point data, user beware... + /// + /// @param inImageArray + /// @param inRate + /// @return dtype + /// + template + dtype generateThreshold(const NdArray& inImageArray, double inRate) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inRate < 0. || inRate > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input rate must be of the range [0, 1]"); + } + + // first build a histogram + auto minValue = static_cast(std::floor(inImageArray.min().item())); + auto maxValue = static_cast(std::floor(inImageArray.max().item())); + + if (utils::essentiallyEqual(inRate, 0.)) + { + return static_cast(maxValue); + } + + if (utils::essentiallyEqual(inRate, 1.)) + { + if (DtypeInfo::isSigned()) + { + return static_cast(minValue - 1); + } + + return dtype{ 0 }; + } + + const auto histSize = static_cast(maxValue - minValue + 1); + + NdArray histogram(1, histSize); + histogram.zeros(); + for (auto intensity : inImageArray) + { + const auto bin = static_cast(static_cast(std::floor(intensity)) - minValue); + ++histogram[bin]; + } + + // integrate the normalized histogram from right to left to make a survival function (1 - CDF) + const auto dNumPixels = static_cast(inImageArray.size()); + NdArray survivalFunction(1, histSize + 1); + survivalFunction[-1] = 0.; + for (int32 i = histSize - 1; i > -1; --i) + { + double histValue = histogram[i] / dNumPixels; + survivalFunction[i] = survivalFunction[i + 1] + histValue; + } + + // binary search through the survival function to find the rate + uint32 indexLow = 0; + uint32 indexHigh = histSize - 1; + uint32 index = indexHigh / 2; // integer division + + constexpr bool keepGoing = true; + while (keepGoing) + { + const double value = survivalFunction[index]; + if (value < inRate) + { + indexHigh = index; + } + else if (value > inRate) + { + indexLow = index; + } + else + { + const int32 thresh = static_cast(index) + minValue - 1; + if (DtypeInfo::isSigned()) + { + return static_cast(thresh); + } + + return thresh < 0 ? 0 : static_cast(thresh); + } + + if (indexHigh - indexLow < 2) + { + return static_cast(static_cast(indexHigh) + minValue - 1); + } + + index = indexLow + (indexHigh - indexLow) / 2; + } + + // shouldn't ever get here but stop the compiler from throwing a warning + return static_cast(histSize - 1); + } + +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8352d89edafd286428fb0169bde0250a78058401 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Window expand around exceedance pixels +/// + +#pragma once + +#include + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Window expand around exceedance pixels + /// + /// @param inExceedances + /// @param inBorderWidth + /// @return NdArray + /// + inline NdArray windowExceedances(const NdArray& inExceedances, uint8 inBorderWidth) noexcept + { + // not the most efficient way to do things, but the easist... + NdArray xcds(inExceedances); + const Shape inShape = xcds.shape(); + for (uint8 border = 0; border < inBorderWidth; ++border) + { + for (int32 row = 0; row < static_cast(inShape.rows); ++row) + { + for (int32 col = 0; col < static_cast(inShape.cols); ++col) + { + if (inExceedances(row, col)) + { + xcds(std::max(row - 1, 0), std::max(col - 1, 0)) = true; + xcds(std::max(row - 1, 0), col) = true; + xcds(std::max(row - 1, 0), std::min(col + 1, inShape.cols - 1)) = true; + + xcds(row, std::max(col - 1, 0)) = true; + xcds(row, std::min(col + 1, inShape.cols - 1)) = true; + + xcds(std::min(row + 1, inShape.rows - 1), std::max(col - 1, 0)) = true; + xcds(std::min(row + 1, inShape.rows - 1), col) = true; + xcds(std::min(row + 1, inShape.rows - 1), std::min(col + 1, inShape.cols - 1)) = + true; + } + } + } + } + + return xcds; + } +} // namespace nc::imageProcessing diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b4eedc6a2d8bc1900c6345cce679b0a733619e38 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate.hpp @@ -0,0 +1,33 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration routines +/// +#pragma once + +#include "NumCpp/Integrate/gauss_legendre.hpp" +#include "NumCpp/Integrate/romberg.hpp" +#include "NumCpp/Integrate/simpson.hpp" +#include "NumCpp/Integrate/trapazoidal.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/gauss_legendre.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/gauss_legendre.hpp new file mode 100644 index 0000000000000000000000000000000000000000..dc5b5f1df073acb8b98e2170fefc50998e9d2d37 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/gauss_legendre.hpp @@ -0,0 +1,201 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/25/numerical-methods-in-c-part-2-gauss-legendre-integration/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Class Description: + /// Legendre Polynomial class + /// + class LegendrePolynomial + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param numIterations: the number of iterations to perform + /// + explicit LegendrePolynomial(const uint32 numIterations) noexcept : + numIterations_(numIterations), + weight_(numIterations + 1), + root_(numIterations + 1) + { + calculateWeightAndRoot(); + } + + //============================================================================ + // Method Description: + /// Returns the weights vector + /// + /// @return weights vector + /// + [[nodiscard]] const std::vector& getWeight() const noexcept + { + return weight_; + } + + //============================================================================ + // Method Description: + /// Returns the roots vector + /// + /// @return roots vector + /// + [[nodiscard]] const std::vector& getRoot() const noexcept + { + return root_; + } + + private: + //============================================================================ + // Class Description: + /// Simple class to hold the results + /// + struct Result + { + double value{ 0. }; + double derivative{ 0. }; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param val: the value + /// @param deriv: the derivative + /// + Result(const double val, const double deriv) noexcept : + value(val), + derivative(deriv) + { + } + }; + + //============================================================================ + // Method Description: + /// Calculates the weights and roots vectors + /// + void calculateWeightAndRoot() noexcept + { + const auto numIterationsDouble = static_cast(numIterations_); + for (uint32 step = 0; step <= numIterations_; ++step) + { + double root = + std::cos(constants::pi * (static_cast(step) - 0.25) / (numIterationsDouble + 0.5)); + Result result = calculatePolynomialValueAndDerivative(root); + + double newtonRaphsonRatio; + do + { + newtonRaphsonRatio = result.value / result.derivative; + root -= newtonRaphsonRatio; + result = calculatePolynomialValueAndDerivative(root); + } while (std::fabs(newtonRaphsonRatio) > EPSILON); + + root_[step] = root; + weight_[step] = 2. / ((1. - utils::sqr(root)) * result.derivative * result.derivative); + } + } + + //============================================================================ + // Method Description: + /// Calculates the weights and roots vectors + /// + /// @param x + /// @return Result + /// + Result calculatePolynomialValueAndDerivative(const double x) noexcept + { + Result result(x, 0.); + + double value_minus_1 = 1.; + const double f = 1. / (utils::sqr(x) - 1.); + for (uint32 step = 2; step <= numIterations_; ++step) + { + const auto stepDouble = static_cast(step); + const double value = + ((2. * stepDouble - 1.) * x * result.value - (stepDouble - 1.) * value_minus_1) / stepDouble; + result.derivative = stepDouble * f * (x * value - result.value); + + value_minus_1 = result.value; + result.value = value; + } + + return result; + } + + //===================================Attributes============================== + const double EPSILON{ 1e-15 }; + + const uint32 numIterations_{}; + std::vector weight_{}; + std::vector root_{}; + }; + + //============================================================================ + // Method Description: + /// Performs Gauss-Legendre integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of iterations to perform + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double + gauss_legendre(const double low, const double high, const uint32 n, const std::function& f) + { + const LegendrePolynomial legendrePolynomial(n); + const std::vector& weight = legendrePolynomial.getWeight(); + const std::vector& root = legendrePolynomial.getRoot(); + + const double width = 0.5 * (high - low); + const double mean = 0.5 * (low + high); + + double gaussLegendre = 0.; + for (uint32 step = 1; step <= n; ++step) + { + gaussLegendre += weight[step] * f(width * root[step] + mean); + } + + return gaussLegendre * width; + } +} // namespace nc::integrate diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/romberg.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/romberg.hpp new file mode 100644 index 0000000000000000000000000000000000000000..26a0ca6730c5a556f5fea0086858f29a9637f926 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/romberg.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Integrate/trapazoidal.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes Romberg integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of iterations + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double romberg(const double low, const double high, const uint8 n, const std::function& f) + { + NdArray rombergIntegral(n); + + // R(0,0) Start with trapezoidal integration with N = 1 + rombergIntegral(0, 0) = trapazoidal(low, high, 1, f); + + double h = high - low; + for (uint8 step = 1; step < n; step++) + { + h *= 0.5; + + // R(step, 0) Improve trapezoidal integration with decreasing h + double trapezoidal_integration = 0.; + const uint32 stepEnd = utils::power(2, step - 1); + for (uint32 tzStep = 1; tzStep <= stepEnd; ++tzStep) + { + const double deltaX = (2. * static_cast(tzStep - 1)) * h; + trapezoidal_integration += f(low + deltaX); + } + + rombergIntegral(step, 0) = 0.5 * rombergIntegral(step - 1, 0); + rombergIntegral(step, 0) += trapezoidal_integration * h; + + // R(m,n) Romberg integration with R(m,1) -> Simpson rule, R(m,2) -> Boole's rule + for (uint8 rbStep = 1; rbStep <= step; ++rbStep) + { + const double k = utils::power(4, rbStep); + rombergIntegral(step, rbStep) = k * rombergIntegral(step, rbStep - 1); + rombergIntegral(step, rbStep) -= rombergIntegral(step - 1, rbStep - 1); + rombergIntegral(step, rbStep) /= (k - 1.); + } + } + + return rombergIntegral.back(); + } +} // namespace nc::integrate diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/simpson.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/simpson.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ab655069d4643b6d90f553c7021281c70d64fd9f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/simpson.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes Simpson integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of subdivisions + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double + simpson(const double low, const double high, const uint32 n, const std::function& f) noexcept + { + const double width = (high - low) / static_cast(n); + + double simpson_integral = 0.; + for (uint32 step = 0; step < n; ++step) + { + const double x1 = low + static_cast(step) * width; + const double x2 = low + static_cast(step + 1) * width; + + simpson_integral += (x2 - x1) / 6. * (f(x1) + 4. * f(0.5 * (x1 + x2)) + f(x2)); + } + + return simpson_integral; + } +} // namespace nc::integrate diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/trapazoidal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/trapazoidal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6cd98d3f776c4d3718eb03b513a960630d010883 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Integrate/trapazoidal.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes trapazoidal integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of subdivisions + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double trapazoidal(const double low, + const double high, + const uint32 n, + const std::function& f) noexcept + { + const double width = (high - low) / static_cast(n); + + double trapezoidal_integral = 0.; + for (uint32 step = 0; step < n; ++step) + { + const double x1 = low + static_cast(step) * width; + const double x2 = low + static_cast(step + 1) * width; + + trapezoidal_integral += 0.5 * (x2 - x1) * (f(x1) + f(x2)); + } + + return trapezoidal_integral; + } +} // namespace nc::integrate diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg.hpp new file mode 100644 index 0000000000000000000000000000000000000000..814b36dda5fc7514cdcf1b578038d6ea7a2a27f9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg.hpp @@ -0,0 +1,42 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Module for doing linear algebra operations +/// +#pragma once + +#include "NumCpp/Linalg/cholesky.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/Linalg/gaussNewtonNlls.hpp" +#include "NumCpp/Linalg/hat.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/Linalg/lstsq.hpp" +#include "NumCpp/Linalg/lu_decomposition.hpp" +#include "NumCpp/Linalg/matrix_power.hpp" +#include "NumCpp/Linalg/multi_dot.hpp" +#include "NumCpp/Linalg/pinv.hpp" +#include "NumCpp/Linalg/pivotLU_decomposition.hpp" +#include "NumCpp/Linalg/solve.hpp" +#include "NumCpp/Linalg/svd.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/cholesky.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/cholesky.hpp new file mode 100644 index 0000000000000000000000000000000000000000..62c4873a3075141d4deacdb3312f4a072e11dcf6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/cholesky.hpp @@ -0,0 +1,100 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix cholesky decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix cholesky decomposition A = L * L.transpose() + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.cholesky.html#numpy.linalg.cholesky + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return NdArray of the decomposed L matrix + /// + template + NdArray cholesky(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + auto lMatrix = inMatrix.template astype(); + + for (uint32 row = 0; row < shape.rows; ++row) + { + for (uint32 col = row + 1; col < shape.cols; ++col) + { + lMatrix(row, col) = 0.; + } + } + + for (uint32 k = 0; k < shape.cols; ++k) + { + const double& a_kk = lMatrix(k, k); + + if (a_kk > 0.) + { + lMatrix(k, k) = std::sqrt(a_kk); + + for (uint32 i = k + 1; i < shape.rows; ++i) + { + lMatrix(i, k) /= lMatrix(k, k); + + for (uint32 j = k + 1; j <= i; ++j) + { + lMatrix(i, j) -= lMatrix(i, k) * lMatrix(j, k); + } + } + } + else + { + THROW_RUNTIME_ERROR("Matrix is not positive definite."); + } + } + + return lMatrix; + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/det.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/det.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2b1e3b009b5599639cb37bf91e0be2ff3a6bf5ad --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/det.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix determinant. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + namespace detail + { + //============================================================================ + // Method Description: + /// matrix determinant. + /// + /// @param inArray + /// @param order + /// @return matrix determinant + /// + template + auto det(const NdArray& inArray, uint32 order) + -> std::conditional_t, int64, double> + { + STATIC_ASSERT_ARITHMETIC(dtype); + + using ReturnType = std::conditional_t, int64, double>; + + if (order == 1) + { + return static_cast(inArray.front()); + } + + if (order == 2) + { + return static_cast(inArray(0, 0)) * static_cast(inArray(1, 1)) - + static_cast(inArray(0, 1)) * static_cast(inArray(1, 0)); + } + + if (order == 3) + { + const auto aei = static_cast(inArray(0, 0)) * static_cast(inArray(1, 1)) * + static_cast(inArray(2, 2)); + const auto bfg = static_cast(inArray(0, 1)) * static_cast(inArray(1, 2)) * + static_cast(inArray(2, 0)); + const auto cdh = static_cast(inArray(0, 2)) * static_cast(inArray(1, 0)) * + static_cast(inArray(2, 1)); + const auto ceg = static_cast(inArray(0, 2)) * static_cast(inArray(1, 1)) * + static_cast(inArray(2, 0)); + const auto bdi = static_cast(inArray(0, 1)) * static_cast(inArray(1, 0)) * + static_cast(inArray(2, 2)); + const auto afh = static_cast(inArray(0, 0)) * static_cast(inArray(1, 2)) * + static_cast(inArray(2, 1)); + + return aei + bfg + cdh - ceg - bdi - afh; + } + + ReturnType determinant = 0; + ReturnType sign = 1; + NdArray submat(order - 1); + + for (uint32 c = 0; c < order; ++c) + { + uint32 subi = 0; + for (uint32 i = 1; i < order; ++i) + { + uint32 subj = 0; + for (uint32 j = 0; j < order; ++j) + { + if (j == c) + { + continue; + } + + submat(subi, subj++) = inArray(i, j); + } + ++subi; + } + + determinant += (sign * static_cast(inArray(0, c)) * det(submat, order - 1)); + sign *= -1; + } + + return determinant; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// matrix determinant. + /// NOTE: can get verrrrry slow for large matrices (order > 10) + /// + /// SciPy Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.det.html#scipy.linalg.det + /// + /// @param inArray + /// @return matrix determinant + /// + template + auto det(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + if (!inShape.issquare()) + { + THROW_INVALID_ARGUMENT_ERROR("input array must be square."); + } + + return detail::det(inArray, inShape.rows); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4b2f2e8e3fc8895ead75074be9cea1ffed627645 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp @@ -0,0 +1,134 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// The Gauss�Newton algorithm is used to solve non-linear least squares problems. +/// It is a modification of Newton's method for finding a minimum of a function. +/// +/// https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/rms.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// The Gauss�Newton algorithm is used to solve non-linear least squares problems. + /// It is a modification of Newton's method for finding a minimum of a function. + /// https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm + /// + /// @param numIterations: the number of iterations to perform + /// @param coordinates: the coordinate values. The shape needs to be [n x d], where d is + /// the number of diminsions of the fit function (f(x) is one dimensional, + /// f(x, y) is two dimensions, etc), and n is the number of observations + /// that are being fit to. + /// @param measurements: the measured values that are being fit + /// @param function: a std::function of the function that is being fit. The function takes as + /// inputs an NdArray of a single set of the coordinate values, and an NdArray + /// of the current values of the fit parameters + /// @param derivatives: array of std::functions to calculate the function + /// derivatives. The function that is being fit. The function takes as + /// inputs an NdArray of a single set of the coordinate values, and an NdArray + /// of the current values of the fit parameters + /// @param initialGuess: the initial guess of the parameters to be solved for + /// + /// @return std::pair of NdArray of solved parameter values, and rms of the residuals value + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + std::pair, double> + gaussNewtonNlls(const uint32 numIterations, + const NdArray& coordinates, + const NdArray& measurements, + const std::function&, const NdArray&)>& function, + const std::array&, const NdArray&)>, + sizeof...(Params)>& derivatives, + Params... initialGuess) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto coordinatesShape = coordinates.shape(); + + if (coordinatesShape.rows != measurements.size()) + { + THROW_INVALID_ARGUMENT_ERROR("coordinates number of rows, and measurements size must be the same."); + } + + NdArray beta = NdArray({ initialGuess... }).template astype().transpose(); + NdArray residuals(coordinatesShape.rows, 1); + NdArray jacobian(coordinatesShape.rows, sizeof...(Params)); + + const auto colSlice = coordinates.cSlice(); + for (uint32 iteration = 1; iteration <= numIterations; ++iteration) + { + for (uint32 measIdx = 0; measIdx < coordinatesShape.rows; ++measIdx) + { + const auto coordinate = coordinates(measIdx, colSlice); + + residuals[measIdx] = + static_cast(measurements[measIdx]) - static_cast(function(coordinate, beta)); + + for (uint32 paramIdx = 0; paramIdx < sizeof...(Params); ++paramIdx) + { + const auto& derivative = derivatives[paramIdx]; + jacobian(measIdx, paramIdx) = static_cast(derivative(coordinate, beta)); + } + } + + // perform the gauss-newton linear algebra + const auto jacobianT = jacobian.transpose(); + const auto jacobianPsuedoInverse = linalg::inv(jacobianT.dot(jacobian)); + const auto intermediate = jacobianPsuedoInverse.dot(jacobianT); + const auto deltaBeta = intermediate.dot(residuals); + beta += deltaBeta; + } + + // calculate the final rms of the residuals + for (uint32 measIdx = 0; measIdx < coordinatesShape.rows; ++measIdx) + { + const auto coordinate = coordinates(measIdx, colSlice); + + residuals[measIdx] = + static_cast(measurements[measIdx]) - static_cast(function(coordinate, beta)); + } + + return std::make_pair(beta.flatten(), rms(residuals).item()); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/hat.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/hat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..955f4c43647d5bec365715d9ab58422400e4c3b2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/hat.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// vector hat operator +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inX + /// @param inY + /// @param inZ + /// @return 3x3 NdArray + /// + template + NdArray hat(dtype inX, dtype inY, dtype inZ) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(3); + returnArray(0, 0) = 0.; + returnArray(0, 1) = -inZ; + returnArray(0, 2) = inY; + returnArray(1, 0) = inZ; + returnArray(1, 1) = 0.; + returnArray(1, 2) = -inX; + returnArray(2, 0) = -inY; + returnArray(2, 1) = inX; + returnArray(2, 2) = 0.; + + return returnArray; + } + + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inVec (3x1, or 1x3 cartesian vector) + /// @return 3x3 NdArray + /// + template + NdArray hat(const NdArray& inVec) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inVec.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be a length 3 cartesian vector."); + } + + return hat(inVec[0], inVec[1], inVec[2]); + } + + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inVec + /// @return 3x3 NdArray + /// + inline NdArray hat(const Vec3& inVec) + { + return hat(inVec.x, inVec.y, inVec.z); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/inv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/inv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6acf606a83883c7d03f65872c9782254a97989bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/inv.hpp @@ -0,0 +1,132 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix inverse +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix inverse + /// + /// SciPy Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html#scipy.linalg.inv + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray inv(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + if (inShape.rows != inShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array must be square."); + } + + NdArray inArrayDouble = inArray.template astype(); + NdArray incidence = nc::zeros(inShape); + + for (uint32 k = 0; k < inShape.rows - 1; ++k) + { + if (utils::essentiallyEqual(inArrayDouble(k, k), 0.)) + { + uint32 l = k; + while (l < inShape.cols && utils::essentiallyEqual(inArrayDouble(k, l), 0.)) + { + ++l; + } + + inArrayDouble.swapRows(k, l); + incidence(k, k) = 1; + incidence(k, l) = 1; + } + } + + NdArray result(inShape); + + for (uint32 k = 0; k < inShape.rows; ++k) + { + result(k, k) = -1. / inArrayDouble(k, k); + for (uint32 i = 0; i < inShape.rows; ++i) + { + for (uint32 j = 0; j < inShape.cols; ++j) + { + if ((i - k) && (j - k)) + { + result(i, j) = inArrayDouble(i, j) + inArrayDouble(k, j) * inArrayDouble(i, k) * result(k, k); + } + else if ((i - k) && !(j - k)) + { + result(i, k) = inArrayDouble(i, k) * result(k, k); + } + else if (!(i - k) && (j - k)) + { + result(k, j) = inArrayDouble(k, j) * result(k, k); + } + } + } + + inArrayDouble = result; + } + + result *= -1.; + + for (int i = static_cast(inShape.rows) - 1; i >= 0; --i) + { + if (incidence(i, i) != 1) + { + continue; + } + + int k = 0; + for (; k < static_cast(inShape.cols); ++k) + { + if ((k - i) && incidence(i, k) != 0) + { + result.swapCols(i, k); + break; + } + } + } + + return result; + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lstsq.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lstsq.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2c4a2f62ed9e665788a61648baf81d1030c147ee --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lstsq.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// linear least squares +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Linalg/svd/SVDClass.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Solves the equation a x = b by computing a vector x + /// that minimizes the Euclidean 2-norm || b - a x ||^2. + /// The equation may be under-, well-, or over- determined + /// (i.e., the number of linearly independent rows of a can + /// be less than, equal to, or greater than its number of + /// linearly independent columns). If a is square and of + /// full rank, then x (but for round-off error) is the + /// "exact" solution of the equation. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html#scipy.linalg.lstsq + /// + /// @param inA: coefficient matrix + /// @param inB: Ordinate or "dependent variable" values + /// @param inTolerance (default 1e-12) + /// + /// @return NdArray + /// + template + NdArray lstsq(const NdArray& inA, const NdArray& inB, double inTolerance = 1e-12) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + SVD svdSolver(inA.template astype()); + const double threshold = inTolerance * svdSolver.s().front(); + + return svdSolver.solve(inB.template astype(), threshold); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lu_decomposition.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lu_decomposition.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ae1904711388822cdfc8c776ea5ee493051ceff5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/lu_decomposition.hpp @@ -0,0 +1,92 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix pivot LU decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros_like.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix LU decomposition A = LU + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return std::pair of the decomposed L and U matrices + /// + template + std::pair, NdArray> lu_decomposition(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + NdArray lMatrix = zeros_like(inMatrix); + NdArray uMatrix = inMatrix.template astype(); + + for (uint32 col = 0; col < shape.cols; ++col) + { + lMatrix(col, col) = 1; + + for (uint32 row = col + 1; row < shape.rows; ++row) + { + const double& divisor = uMatrix(col, col); + if (utils::essentiallyEqual(divisor, double{ 0. })) + { + THROW_RUNTIME_ERROR("Division by 0."); + } + + lMatrix(row, col) = uMatrix(row, col) / divisor; + + for (uint32 col2 = col; col2 < shape.cols; ++col2) + { + uMatrix(row, col2) -= lMatrix(row, col) * uMatrix(col, col2); + } + } + } + + return std::make_pair(lMatrix, uMatrix); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/matrix_power.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/matrix_power.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a3bbe2bb5cb18025b8408132b5b5a4b8cc72d8e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/matrix_power.hpp @@ -0,0 +1,105 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raise a square matrix to the (integer) power n. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/identity.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Raise a square matrix to the (integer) power n. + /// + /// For positive integers n, the power is computed by repeated + /// matrix squarings and matrix multiplications. If n == 0, + /// the identity matrix of the same shape as M is returned. + /// If n < 0, the inverse is computed and then raised to the abs(n). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.matrix_power.html#numpy.linalg.matrix_power + /// + /// @param inArray + /// @param inPower + /// + /// @return NdArray + /// + template + NdArray matrix_power(const NdArray& inArray, int16 inPower) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + if (inShape.rows != inShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input matrix must be square."); + } + + if (inPower == 0) + { + return identity(inShape.rows); + } + + if (inPower == 1) + { + return inArray.template astype(); + } + + if (inPower == -1) + { + return inv(inArray); + } + + if (inPower > 1) + { + NdArray inArrayDouble = inArray.template astype(); + NdArray returnArray = dot(inArrayDouble, inArrayDouble); + for (int16 i = 2; i < inPower; ++i) + { + returnArray = dot(returnArray, inArrayDouble); + } + return returnArray; + } + + NdArray inverse = inv(inArray); + NdArray returnArray = dot(inverse, inverse); + inPower *= -1; + for (int16 i = 2; i < inPower; ++i) + { + returnArray = dot(returnArray, inverse); + } + return returnArray; + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/multi_dot.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/multi_dot.hpp new file mode 100644 index 0000000000000000000000000000000000000000..af262d1888970ad813cba8e5e6a4eb975393bb3f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/multi_dot.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Compute the dot product of two or more arrays in a single function call. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Compute the dot product of two or more arrays in a single + /// function call. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.multi_dot.html#numpy.linalg.multi_dot + /// + /// @param inList: list of arrays + /// + /// @return NdArray + /// + template + NdArray multi_dot(const std::initializer_list>& inList) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + typename std::initializer_list>::iterator iter = inList.begin(); + + if (inList.size() == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input empty list of arrays."); + } + else if (inList.size() == 1) + { + return iter->copy(); + } + + NdArray returnArray = dot(*iter, *(iter + 1)); + iter += 2; + for (; iter < inList.end(); ++iter) + { + returnArray = dot(returnArray, *iter); + } + + return returnArray; + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pinv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pinv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a445dbe895f0c4e5726e36147e771bc6bfe3a263 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pinv.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix psuedo-inverse +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/svd.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix psuedo-inverse + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.linalg.pinv.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray pinv(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray u; + NdArray d; + NdArray v; + svd(inArray, u, d, v); + + const auto inShape = inArray.shape(); + auto dPlus = nc::zeros(inShape.cols, inShape.rows); // transpose + + for (uint32 i = 0; i < d.shape().rows; ++i) + { + dPlus(i, i) = 1. / d(i, i); + } + + return v.transpose().dot(dPlus).dot(u.transpose()); + } +} // namespace nc::linalg \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp new file mode 100644 index 0000000000000000000000000000000000000000..038ffadf6d940d27fee31ea764a0d93f2fdc8ceb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix pivot LU decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/zeros_like.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix pivot LU decomposition PA = LU + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return std::tuple of the decomposed L, U, and P matrices + /// + template + std::tuple, NdArray, NdArray> pivotLU_decomposition(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + NdArray lMatrix = zeros_like(inMatrix); + NdArray uMatrix = inMatrix.template astype(); + NdArray pMatrix = eye(shape.rows); + + for (uint32 k = 0; k < shape.rows; ++k) + { + double max = 0.; + uint32 pk = 0; + for (uint32 i = k; i < shape.rows; ++i) + { + double s = 0.; + for (uint32 j = k; j < shape.cols; ++j) + { + s += std::fabs(uMatrix(i, j)); + } + + const double q = std::fabs(uMatrix(i, k)) / s; + if (q > max) + { + max = q; + pk = i; + } + } + + if (utils::essentiallyEqual(max, double{ 0. })) + { + THROW_RUNTIME_ERROR("Division by 0."); + } + + if (pk != k) + { + for (uint32 j = 0; j < shape.cols; ++j) + { + std::swap(pMatrix(k, j), pMatrix(pk, j)); + std::swap(lMatrix(k, j), lMatrix(pk, j)); + std::swap(uMatrix(k, j), uMatrix(pk, j)); + } + } + + for (uint32 i = k + 1; i < shape.rows; ++i) + { + lMatrix(i, k) = uMatrix(i, k) / uMatrix(k, k); + + for (uint32 j = k; j < shape.cols; ++j) + { + uMatrix(i, j) = uMatrix(i, j) - lMatrix(i, k) * uMatrix(k, j); + } + } + } + + for (uint32 k = 0; k < shape.rows; ++k) + { + lMatrix(k, k) = 1.; + } + + return std::make_tuple(lMatrix, uMatrix, pMatrix); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/solve.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/solve.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4e7ab21487152b3d944caba68494637708ee9bc2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/solve.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix svd +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Solve a linear matrix equation, or system of linear scalar equations. + /// Computes the “exact” solution, x, of the well-determined, i.e., full rank, + /// linear matrix equation ax = b. + /// + /// https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html + /// + /// @param inA + /// @param inB + /// @return NdArray Solution to the system a x = b. Returned shape is identical to b + /// + template + NdArray solve(const NdArray& inA, const NdArray& inB) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (!inA.issquare()) + { + THROW_INVALID_ARGUMENT_ERROR("input array a must be square."); + } + + if (!inB.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("input array b must be flat."); + } + + if (inA.numCols() != inB.size()) + { + THROW_INVALID_ARGUMENT_ERROR("input array b size must be the same as the square size of a."); + } + + return dot(inv(inA), inB.template astype().reshape(inB.size(), 1)).reshape(inB.shape()); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd.hpp new file mode 100644 index 0000000000000000000000000000000000000000..62a93051bf065567e1cca75deff0c6db2c0b8081 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix svd +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Linalg/svd/SVDClass.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix svd + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html#numpy.linalg.svd + /// + /// @param inArray: NdArray to be SVDed + /// @param outU: NdArray output U + /// @param outS: NdArray output S + /// @param outVt: NdArray output V transpose + /// + template + void svd(const NdArray& inArray, NdArray& outU, NdArray& outS, NdArray& outVt) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + SVD svdSolver(inArray.template astype()); + outU = svdSolver.u(); + + NdArray vt = svdSolver.v().transpose(); + outVt = std::move(vt); + + NdArray s = diagflat(svdSolver.s(), 0); + outS = std::move(s); + } +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp new file mode 100644 index 0000000000000000000000000000000000000000..744c630dc92f9b9007d4373c86db850ede0f42ad --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp @@ -0,0 +1,646 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2020 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Performs the singular value decomposition of a general matrix, +/// taken and adapted from Numerical Recipes Third Edition svd.h +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + // ============================================================================= + // Class Description: + /// performs the singular value decomposition of a general matrix, + /// taken and adapted from Numerical Recipes Third Edition svd.h + class SVD + { + public: + // ============================================================================= + // Description: + /// Constructor + /// + /// @param inMatrix: matrix to perform SVD on + /// + explicit SVD(const NdArray& inMatrix) : + m_(inMatrix.shape().rows), + n_(inMatrix.shape().cols), + u_(inMatrix), + v_(n_, n_), + s_(1, n_), + eps_(std::numeric_limits::epsilon()) + { + decompose(); + reorder(); + tsh_ = 0.5 * std::sqrt(m_ + n_ + 1.) * s_.front() * eps_; + } + + // ============================================================================= + // Description: + /// the resultant u matrix + /// + /// @return u matrix + /// + const NdArray& u() noexcept + { + return u_; + } + + // ============================================================================= + // Description: + /// the resultant v matrix + /// + /// @return v matrix + /// + const NdArray& v() noexcept + { + return v_; + } + + // ============================================================================= + // Description: + /// the resultant w matrix + /// + /// @return s matrix + /// + const NdArray& s() noexcept + { + return s_; + } + + // ============================================================================= + // Description: + /// solves the linear least squares problem + /// + /// @param inInput + /// @param inThresh (default -1.) + /// + /// @return NdArray + /// + NdArray solve(const NdArray& inInput, double inThresh = -1.) + { + double ss{}; + + if (inInput.size() != m_) + { + THROW_INVALID_ARGUMENT_ERROR("bad sizes."); + } + + NdArray returnArray(1, n_); + + NdArray tmp(1, n_); + + tsh_ = (inThresh >= 0. ? inThresh : 0.5 * sqrt(m_ + n_ + 1.) * s_.front() * eps_); + + for (uint32 j = 0; j < n_; j++) + { + ss = 0.; + if (s_[j] > tsh_) + { + for (uint32 i = 0; i < m_; i++) + { + ss += u_(i, j) * inInput[i]; + } + ss /= s_[j]; + } + tmp[j] = ss; + } + + for (uint32 j = 0; j < n_; j++) + { + ss = 0.; + for (uint32 jj = 0; jj < n_; jj++) + { + ss += v_(j, jj) * tmp[jj]; + } + + returnArray[j] = ss; + } + + return returnArray; + } + + private: + // ============================================================================= + // Description: + /// returns the SIGN of two values + /// + /// @param inA + /// @param inB + /// + /// @return value + /// + static double SIGN(double inA, double inB) noexcept + { + return inB >= 0 ? (inA >= 0 ? inA : -inA) : (inA >= 0 ? -inA : inA); + } + + // ============================================================================= + // Description: + /// decomposes the input matrix + /// + void decompose() + { + bool flag{}; + uint32 i{}; + uint32 its{}; + uint32 j{}; + uint32 jj{}; + uint32 k{}; + uint32 l{}; + uint32 nm{}; + + double anorm{}; + double c{}; + double f{}; + double g{}; + double h{}; + double ss{}; + double scale{}; + double x{}; + double y{}; + double z{}; + + NdArray rv1(n_, 1); + + for (i = 0; i < n_; ++i) + { + l = i + 2; + rv1[i] = scale * g; + g = ss = scale = 0.; + + if (i < m_) + { + for (k = i; k < m_; ++k) + { + scale += std::abs(u_(k, i)); + } + + if (!utils::essentiallyEqual(scale, 0.)) + { + for (k = i; k < m_; ++k) + { + u_(k, i) /= scale; + ss += u_(k, i) * u_(k, i); + } + + f = u_(i, i); + g = -SIGN(std::sqrt(ss), f); + h = f * g - ss; + u_(i, i) = f - g; + + for (j = l - 1; j < n_; ++j) + { + for (ss = 0., k = i; k < m_; ++k) + { + ss += u_(k, i) * u_(k, j); + } + + f = ss / h; + + for (k = i; k < m_; ++k) + { + u_(k, j) += f * u_(k, i); + } + } + + for (k = i; k < m_; ++k) + { + u_(k, i) *= scale; + } + } + } + + s_[i] = scale * g; + g = ss = scale = 0.; + + if (i + 1 <= m_ && i + 1 != n_) + { + for (k = l - 1; k < n_; ++k) + { + scale += std::abs(u_(i, k)); + } + + if (!utils::essentiallyEqual(scale, 0.)) + { + for (k = l - 1; k < n_; ++k) + { + u_(i, k) /= scale; + ss += u_(i, k) * u_(i, k); + } + + f = u_(i, l - 1); + g = -SIGN(std::sqrt(ss), f); + h = f * g - ss; + u_(i, l - 1) = f - g; + + for (k = l - 1; k < n_; ++k) + { + rv1[k] = u_(i, k) / h; + } + + for (j = l - 1; j < m_; ++j) + { + for (ss = 0., k = l - 1; k < n_; ++k) + { + ss += u_(j, k) * u_(i, k); + } + + for (k = l - 1; k < n_; ++k) + { + u_(j, k) += ss * rv1[k]; + } + } + + for (k = l - 1; k < n_; ++k) + { + u_(i, k) *= scale; + } + } + } + + anorm = std::max(anorm, (std::abs(s_[i]) + std::abs(rv1[i]))); + } + + for (i = n_ - 1; i != static_cast(-1); --i) + { + if (i < n_ - 1) + { + if (!utils::essentiallyEqual(g, 0.)) + { + for (j = l; j < n_; ++j) + { + v_(j, i) = (u_(i, j) / u_(i, l)) / g; + } + + for (j = l; j < n_; ++j) + { + for (ss = 0., k = l; k < n_; ++k) + { + ss += u_(i, k) * v_(k, j); + } + + for (k = l; k < n_; ++k) + { + v_(k, j) += ss * v_(k, i); + } + } + } + + for (j = l; j < n_; ++j) + { + v_(i, j) = v_(j, i) = 0.; + } + } + + v_(i, i) = 1.; + g = rv1[i]; + l = i; + } + + for (i = std::min(m_, n_) - 1; i != static_cast(-1); --i) + { + l = i + 1; + g = s_[i]; + + for (j = l; j < n_; ++j) + { + u_(i, j) = 0.; + } + + if (!utils::essentiallyEqual(g, 0.)) + { + g = 1. / g; + + for (j = l; j < n_; ++j) + { + for (ss = 0., k = l; k < m_; ++k) + { + ss += u_(k, i) * u_(k, j); + } + + f = (ss / u_(i, i)) * g; + + for (k = i; k < m_; ++k) + { + u_(k, j) += f * u_(k, i); + } + } + + for (j = i; j < m_; ++j) + { + u_(j, i) *= g; + } + } + else + { + for (j = i; j < m_; ++j) + { + u_(j, i) = 0.; + } + } + + ++u_(i, i); + } + + for (k = n_ - 1; k != static_cast(-1); --k) + { + for (its = 0; its < 30; ++its) + { + flag = true; + for (l = k; l != static_cast(-1); --l) + { + nm = l - 1; + if (l == 0 || std::abs(rv1[l]) <= eps_ * anorm) + { + flag = false; + break; + } + + if (std::abs(s_[nm]) <= eps_ * anorm) + { + break; + } + } + + if (flag) + { + c = 0.; + ss = 1.; + for (i = l; i < k + 1; ++i) + { + f = ss * rv1[i]; + rv1[i] = c * rv1[i]; + + if (std::abs(f) <= eps_ * anorm) + { + break; + } + + g = s_[i]; + h = pythag(f, g); + s_[i] = h; + h = 1. / h; + c = g * h; + ss = -f * h; + + for (j = 0; j < m_; ++j) + { + y = u_(j, nm); + z = u_(j, i); + u_(j, nm) = y * c + z * ss; + u_(j, i) = z * c - y * ss; + } + } + } + + z = s_[k]; + if (l == k) + { + if (z < 0.) + { + s_[k] = -z; + for (j = 0; j < n_; ++j) + { + v_(j, k) = -v_(j, k); + } + } + break; + } + + if (its == 29) + { + THROW_INVALID_ARGUMENT_ERROR("no convergence in 30 svdcmp iterations"); + } + + x = s_[l]; + nm = k - 1; + y = s_[nm]; + g = rv1[nm]; + h = rv1[k]; + f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2. * h * y); + g = pythag(f, 1.); + f = ((x - z) * (x + z) + h * ((y / (f + SIGN(g, f))) - h)) / x; + c = ss = 1.; + + for (j = l; j <= nm; j++) + { + i = j + 1; + g = rv1[i]; + y = s_[i]; + h = ss * g; + g = c * g; + z = pythag(f, h); + rv1[j] = z; + c = f / z; + ss = h / z; + f = x * c + g * ss; + g = g * c - x * ss; + h = y * ss; + y *= c; + + for (jj = 0; jj < n_; ++jj) + { + x = v_(jj, j); + z = v_(jj, i); + v_(jj, j) = x * c + z * ss; + v_(jj, i) = z * c - x * ss; + } + + z = pythag(f, h); + s_[j] = z; + + if (!utils::essentiallyEqual(z, 0.)) + { + z = 1. / z; + c = f * z; + ss = h * z; + } + + f = c * g + ss * y; + x = c * y - ss * g; + + for (jj = 0; jj < m_; ++jj) + { + y = u_(jj, j); + z = u_(jj, i); + u_(jj, j) = y * c + z * ss; + u_(jj, i) = z * c - y * ss; + } + } + rv1[l] = 0.; + rv1[k] = f; + s_[k] = x; + } + } + } + + // ============================================================================= + // Description: + /// reorders the input matrix + /// + void reorder() + { + uint32 i = 0; + uint32 j = 0; + uint32 k = 0; + uint32 ss = 0; + uint32 inc = 1; + + double sw{}; + NdArray su(m_, 1); + NdArray sv(n_, 1); + + do + { + inc *= 3; + ++inc; + } while (inc <= n_); + + do + { + inc /= 3; + for (i = inc; i < n_; ++i) + { + sw = s_[i]; + for (k = 0; k < m_; ++k) + { + su[k] = u_(k, i); + } + + for (k = 0; k < n_; ++k) + { + sv[k] = v_(k, i); + } + + j = i; + while (s_[j - inc] < sw) + { + s_[j] = s_[j - inc]; + + for (k = 0; k < m_; ++k) + { + u_(k, j) = u_(k, j - inc); + } + + for (k = 0; k < n_; ++k) + { + v_(k, j) = v_(k, j - inc); + } + + j -= inc; + + if (j < inc) + { + break; + } + } + + s_[j] = sw; + + for (k = 0; k < m_; ++k) + { + u_(k, j) = su[k]; + } + + for (k = 0; k < n_; ++k) + { + v_(k, j) = sv[k]; + } + } + } while (inc > 1); + + for (k = 0; k < n_; ++k) + { + ss = 0; + + for (i = 0; i < m_; i++) + { + if (u_(i, k) < 0.) + { + ss++; + } + } + + for (j = 0; j < n_; ++j) + { + if (v_(j, k) < 0.) + { + ss++; + } + } + + if (ss > (m_ + n_) / 2) + { + for (i = 0; i < m_; ++i) + { + u_(i, k) = -u_(i, k); + } + + for (j = 0; j < n_; ++j) + { + v_(j, k) = -v_(j, k); + } + } + } + } + + // ============================================================================= + // Description: + /// performs pythag of input values + /// + /// @param inA + /// @param inB + /// + /// @return resultant value + /// + static double pythag(double inA, double inB) noexcept + { + const double absa = std::abs(inA); + const double absb = std::abs(inB); + return (absa > absb + ? absa * std::sqrt(1. + utils::sqr(absb / absa)) + : (utils::essentiallyEqual(absb, 0.) ? 0. : absb * std::sqrt(1. + utils::sqr(absa / absb)))); + } + + private: + // ===============================Attributes==================================== + const uint32 m_{}; + const uint32 n_{}; + NdArray u_{}; + NdArray v_{}; + NdArray s_{}; + double eps_{}; + double tsh_{}; + }; +} // namespace nc::linalg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fe79ae507e274d30c750542d443a643f6ade1b0b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Image and signal filtering module +/// +#pragma once + +#include "NumCpp/Logging/BinaryLogger.hpp" +#include "NumCpp/Logging/Logger.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/BinaryLogger.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/BinaryLogger.hpp new file mode 100644 index 0000000000000000000000000000000000000000..67256c1202f76ddb612a2e710801a885b9fe29c6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/BinaryLogger.hpp @@ -0,0 +1,344 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Binary data logger +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "boost/algorithm/string.hpp" +#include "boost/core/demangle.hpp" + +namespace nc::logger +{ + namespace detail + { + namespace type_traits + { + /** + * @brief type trait to check if a type has a serialize method with the correct signature + */ + template + using serialize_t = decltype(std::declval().serialize()); + + /** + * @brief type trait to check if a type has a serialize method with the correct signature + */ + template> + class has_serialize : std::false_type + { + public: + static constexpr bool value = false; + }; + + /** + * @brief type trait to check if a type has a serialize method with the correct signature + */ + template + class has_serialize, std::string>, int>>> + { + public: + static constexpr bool value = true; + }; + + /** + * @brief type trait to check if a type has a serialize method with the correct signature + */ + template + inline constexpr bool has_serialize_v = has_serialize::value; + } // namespace type_traits + + /** + * @brief Binary Logger + */ + template + class BinaryDataLogger + { + public: + using value_type = DataType; + using const_pointer = const DataType* const; + using const_reference = const DataType&; + + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays, hicpp-avoid-c-arrays, modernize-avoid-c-arrays) + static constexpr char LOG_EXT[] = ".log"; + static constexpr auto DATA_ELEMENT_SIZE = sizeof(value_type); + static constexpr auto DATE_TYPE_HAS_SERIALIZE_METHOD = type_traits::has_serialize_v; + + /** + * @brief Default constructor + */ + BinaryDataLogger() { } + + /** + * @brief Constructor + * @param outputDir: the directory to place the output log + */ + explicit BinaryDataLogger(std::filesystem::path outputDir) + { + setOutputDir(outputDir); + } + + /** + * @brief Constructor + * @param outputDir: the directory to place the output log + */ + explicit BinaryDataLogger(std::string_view outputDir) : + BinaryDataLogger(std::filesystem::path(outputDir)) + { + } + + /** + * @brief Destructor + */ + ~BinaryDataLogger() + { + ofile_.close(); + } + + // explicitly delete + BinaryDataLogger(const BinaryDataLogger&) = delete; + BinaryDataLogger(BinaryDataLogger&&) = delete; + BinaryDataLogger& operator=(const BinaryDataLogger&) = delete; + BinaryDataLogger& operator=(BinaryDataLogger&&) = delete; + + /** + * @brief The log file path + */ + const std::filesystem::path& filepath() const noexcept + { + return filepath_; + } + + /** + * @brief Sets the output log directory. + * + * @param outputDir: the output directory + */ + void setOutputDir(std::filesystem::path outputDir) + { + if (std::filesystem::is_directory(outputDir)) + { + auto dataTypeName = boost::core::demangle(typeid(DataType).name()); + boost::algorithm::replace_all(dataTypeName, "::", "_"); + boost::algorithm::replace_all(dataTypeName, "<", "_"); + boost::algorithm::replace_all(dataTypeName, ">", "_"); + const auto filename = std::filesystem::path(dataTypeName).replace_extension(LOG_EXT); + filepath_ = std::filesystem::canonical(outputDir) / filename; + + ofile_ = std::ofstream(filepath_.c_str(), std::ios::out | std::ios::binary); + if (!ofile_.good()) + { + throw std::runtime_error("Unable to open the log file:\n\t" + filepath_.string()); + } + } + else + { + throw std::runtime_error("The provided output log directory is not valid:\n\t" + + outputDir.string()); + } + } + + /** + * @brief Sets the output log directory. + * + * @param outputDir: the output directory + */ + void setOutputDir(std::string_view outputDir) + { + setOutputDir(std::filesystem::path(outputDir)); + } + + /** + * @brief Enable the logger + */ + void enable() noexcept + { + enabled_ = true; + } + + /** + * @brief Disable the logger + */ + void disable() noexcept + { + enabled_ = false; + } + + /** + * @brief Checks whether logger is enabled + */ + bool isEnabled() noexcept + { + return enabled_; + } + + /** + * @brief Force a flush of the output stream + */ + void flush() + { + ofile_.flush(); + } + + /** + * @brief Logs the data element + * @param dataElement: the data element + */ + void log(const_reference dataElement) + { + if (!enabled_) + { + return; + } + + if (filepath_.empty()) + { + throw std::runtime_error("The output log directory does not exist"); + } + + if constexpr (DATE_TYPE_HAS_SERIALIZE_METHOD) + { + const auto serializedData = dataElement.serialize(); + ofile_.write(serializedData.data(), serializedData.size()); + } + else + { + ofile_.write(reinterpret_cast(&dataElement), DATA_ELEMENT_SIZE); + } + } + + /** + * @brief Logs the data elements + * @param dataElements: the data element pointer + * @param numElements: the number of data elements to log + */ + void log(const_pointer dataElements, std::size_t numElements) + { + if (!enabled_) + { + return; + } + + if (filepath_.empty()) + { + throw std::runtime_error("The output log directory does not exist"); + } + + std::for_each(dataElements, + dataElements + numElements, + [this](const_reference dataElement) { log(dataElement); }); + } + + private: + std::filesystem::path filepath_{}; + std::ofstream ofile_; + bool enabled_{ true }; + }; + } // namespace detail + + /** + * @brief Binary Logger Singleton + */ + class BinaryLogger + { + public: + // explicitly delete + BinaryLogger(const BinaryLogger&) = delete; + BinaryLogger(BinaryLogger&&) = delete; + BinaryLogger& operator=(const BinaryLogger&) = delete; + BinaryLogger& operator=(BinaryLogger&&) = delete; + + /** + * @brief Singleton instance getter + * + * @returns: singleton instance of BinaryLogger + */ + static BinaryLogger& getInstance() noexcept + { + static BinaryLogger binaryLogger; + return binaryLogger; + } + + /** + * @brief Sets the output directory. This should be called BEFORE any type loggers + * have been created, and will NOT reset the output directory afterwards! + * + * @param outputDir: the output directory + */ + void setOutputDir(const std::filesystem::path& outputDir) + { + if (!std::filesystem::is_directory(outputDir)) + { + throw std::runtime_error("outputDir does not exist"); + } + + outputDir_ = outputDir; + } + + /** + * @brief Sets the output directory. This should be called BEFORE any type loggers + * have been created, and will NOT reset the output directory afterwards! + * + * @param outputDir: the output directory + */ + void setOutputDir(std::string_view outputDir) + { + setOutputDir(std::filesystem::path(outputDir)); + } + + /** + * @brief Gets the logger instance for the specific data type + * + * @returns data type logger instance + */ + template + detail::BinaryDataLogger& getTypeLogger() + { + static detail::BinaryDataLogger typeLogger(outputDir_); + return typeLogger; + } + + private: + std::filesystem::path outputDir_{ "." }; + + /** + * @brief Constructor + */ + BinaryLogger() = default; + }; +} // namespace nc::logger + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/Logger.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/Logger.hpp new file mode 100644 index 0000000000000000000000000000000000000000..29232587448fe328f657955aa7ec34b8bf4bd2b0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Logging/Logger.hpp @@ -0,0 +1,220 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Text file loggger +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include + +#include "boost/core/null_deleter.hpp" +#include "boost/log/attributes.hpp" +#include "boost/log/core/core.hpp" +#include "boost/log/expressions.hpp" +#include "boost/log/expressions/formatters/date_time.hpp" +#include "boost/log/sinks/sync_frontend.hpp" +#include "boost/log/sinks/text_ostream_backend.hpp" +#include "boost/log/sources/global_logger_storage.hpp" +#include "boost/log/sources/severity_logger.hpp" +#include "boost/log/support/date_time.hpp" +#include "boost/log/trivial.hpp" +#include "boost/log/utility/manipulators/add_value.hpp" +#include "boost/log/utility/setup/common_attributes.hpp" +#include "boost/make_shared.hpp" +#include "boost/shared_ptr.hpp" + +namespace nc::logger +{ + /** + * @brief Register a global logger + */ + BOOST_LOG_GLOBAL_LOGGER(fileLogger, boost::log::sources::severity_logger_mt) + + /** + * Boost log attributes + */ + BOOST_LOG_ATTRIBUTE_KEYWORD(lineId, "LineID", uint32_t) + BOOST_LOG_ATTRIBUTE_KEYWORD(timestamp, "TimeStamp", boost::posix_time::ptime) + BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", boost::log::trivial::severity_level) + BOOST_LOG_ATTRIBUTE_KEYWORD(filename, "Filename", std::string) + BOOST_LOG_ATTRIBUTE_KEYWORD(functionName, "FunctionName", std::string) + BOOST_LOG_ATTRIBUTE_KEYWORD(lineNumber, "LineNumber", uint32_t) + + namespace detail + { + // just log messages with severity >= SEVERITY_THRESHOLD are written + constexpr boost::log::trivial::severity_level INIT_LOGLEVEL{ boost::log::trivial::severity_level::trace }; + + // log file extension + constexpr char OUTPUT_LOG_FILE_EXT[] = "log"; + + // typedefs + using text_sink = boost::log::sinks::synchronous_sink; + + /** + * @brief local variables to hold the sink pointers + */ + inline boost::shared_ptr sinkConsole{}; + inline boost::shared_ptr sinkFile{}; + + /** + * @brief function to define the format of the output + */ + [[nodiscard]] inline boost::log::formatter createOutputFormat() + { + // specify the format of the log message + constexpr auto counterWidth = 7; + boost::log::formatter formatter = + boost::log::expressions::stream + << std::setw(counterWidth) << std::setfill('0') << lineId << std::setfill(' ') << " [" + << boost::log::expressions::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f") << "] " + << "[" << boost::log::trivial::severity << "] " + << "[" << filename << ":" << functionName << "():" << lineNumber << "] " + << boost::log::expressions::smessage; + return formatter; + } + } // namespace detail + + /** + * @brief Global intializer and constructor for the global logger + * Sets the initial sink to console backend and sets the default severity level + */ + [[nodiscard]] inline BOOST_LOG_GLOBAL_LOGGER_INIT(fileLogger, boost::log::sources::severity_logger_mt) + { + boost::log::sources::severity_logger_mt logger; + + // add attributes + logger.add_attribute("LineID", boost::log::attributes::counter(1)); + logger.add_attribute("TimeStamp", boost::log::attributes::local_clock()); + + detail::sinkConsole = boost::make_shared(); + + // add "console" output stream to our sink + detail::sinkConsole->locked_backend()->add_stream( + boost::shared_ptr(&std::clog, boost::null_deleter())); + + // specify the format of the log message + const auto formatter = detail::createOutputFormat(); + + // set the formatting + detail::sinkConsole->set_formatter(formatter); + + // just log messages with severity >= INIT_LOGLEVEL are written + detail::sinkConsole->set_filter(severity >= detail::INIT_LOGLEVEL); + + // "register" our sink + boost::log::core::get()->add_sink(detail::sinkConsole); + + return logger; + } + + /** + * @brief Function to add the name of the output log file + * @note This function will attempt to create any parent directories, if necessary + * @throws std::runtime_error if it cannot create the appropiate directories + * + * @param logFileName path of log file to write to + */ + inline void addOutputFileLog(std::filesystem::path logFileName) + { + logFileName = std::filesystem::absolute(logFileName.replace_extension(detail::OUTPUT_LOG_FILE_EXT)); + + // create the parent directories as needed + const auto errorCode = [&] + { + auto error = std::error_code{}; + std::filesystem::create_directories(logFileName.parent_path(), error); + return error; + }(); + if (errorCode) + { + auto ss = std::stringstream{}; + ss << "Failed to create " << logFileName << " -- " << errorCode.message(); + throw std::runtime_error{ ss.str() }; + } + + // add a text sink + detail::sinkFile = boost::make_shared(); + + // add a logfile stream to our sink + detail::sinkFile->locked_backend()->add_stream(boost::make_shared(logFileName)); + + // specify the format of the log message + const auto formatter = detail::createOutputFormat(); + + // set the formatting + detail::sinkFile->set_formatter(formatter); + + // just log messages with severity >= INIT_LOGLEVEL are written + detail::sinkFile->set_filter(severity >= detail::INIT_LOGLEVEL); + + // "register" our sink + boost::log::core::get()->add_sink(detail::sinkFile); + } + + /** + * @brief Function to set the severity level to report back to console and log file + * + * @param level: level at which to report the logs + */ + inline void setLogLevel(boost::log::trivial::severity_level level) + { + detail::sinkConsole->set_filter(severity >= level); + if (detail::sinkFile) + { + detail::sinkFile->set_filter(severity >= level); + } + } +} // namespace nc::logger + +// just a helper macro used by the macros below - don't use it in your code +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define BOOST_LOGGER(severity) \ + BOOST_LOG_SEV(nc::logger::fileLogger::get(), boost::log::trivial::severity) \ + << boost::log::add_value("Filename", std::filesystem::path(__FILE__).filename().stem().string()) \ + << boost::log::add_value("FunctionName", __FUNCTION__) \ + << boost::log::add_value("LineNumber", uint32_t{ __LINE__ }) + +// ===== log macros ===== +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_TRACE BOOST_LOGGER(trace) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_DEBUG BOOST_LOGGER(debug) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_INFO BOOST_LOGGER(info) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_WARNING BOOST_LOGGER(warning) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_ERROR BOOST_LOGGER(error) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define LOG_FATAL BOOST_LOGGER(fatal) + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray.hpp new file mode 100644 index 0000000000000000000000000000000000000000..117d9f71682b7795d9b46c073c597b58cc209045 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds 1D and 2D arrays, the main work horse of the NumCpp library +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" +#include "NumCpp/NdArray/NdArrayOperators.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3bbbc51f5628c89ae4aa6a9e47bdab30e2fb1a57 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp @@ -0,0 +1,289 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Broadcasting for NdArray functions +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc::broadcast +{ + //============================================================================ + // Method Description: + /// Broadcasting template function for in-place operations + /// + /// @param function + /// @param inArray1 + /// @param inArray2 + /// @param additionalFunctionArgs + /// + /// @return NdArray + /// + template + NdArray& broadcaster(NdArray& inArray1, + const NdArray& inArray2, + const Function& function, + const AdditionalFunctionArgs&&... additionalFunctionArgs) + { + if (inArray1.shape() == inArray2.shape()) + { + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + inArray1.begin(), + [&function, &additionalFunctionArgs...](const auto& inValue1, const auto& inValue2) -> dtypeIn1 { + return function(inValue1, + inValue2, + std::forward(additionalFunctionArgs)...); + }); + } + else if (inArray2.isscalar()) + { + const auto value = inArray2.item(); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray1.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 + { return function(inValue, value, std::forward(additionalFunctionArgs)...); }); + } + else if (inArray2.isflat()) + { + if (inArray2.numRows() > 1 && inArray2.numRows() == inArray1.numRows()) + { + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + const auto value = inArray2[row]; + stl_algorithms::transform( + inArray1.cbegin(row), + inArray1.cend(row), + inArray1.begin(row), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + } + else if (inArray2.numCols() > 1 && inArray2.numCols() == inArray1.numCols()) + { + for (uint32 col = 0; col < inArray1.numCols(); ++col) + { + const auto value = inArray2[col]; + stl_algorithms::transform( + inArray1.ccolbegin(col), + inArray1.ccolend(col), + inArray1.colbegin(col), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + + return inArray1; + } + + //============================================================================ + // Method Description: + /// Broadcasting template function + /// + /// @param function + /// @param inArray1 + /// @param inArray2 + /// @param additionalFunctionArgs + /// + /// @return NdArray + /// + template + NdArray broadcaster(const NdArray& inArray1, + const NdArray& inArray2, + const Function& function, + const AdditionalFunctionArgs&&... additionalFunctionArgs) + { + if (inArray1.shape() == inArray2.shape()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [&function, &additionalFunctionArgs...](const auto& inValue1, const auto& inValue2) -> dtypeOut { + return function(inValue1, + inValue2, + std::forward(additionalFunctionArgs)...); + }); + + return returnArray; + }(); + } + else if (inArray1.isscalar()) + { + const auto value = inArray1.item(); + return [&inArray2, &value, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray2.shape()); + stl_algorithms::transform( + inArray2.cbegin(), + inArray2.cend(), + returnArray.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + return returnArray; + }(); + } + else if (inArray2.isscalar()) + { + const auto value = inArray2.item(); + return [&inArray1, &value, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + returnArray.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + return returnArray; + }(); + } + else if (inArray1.isflat() && inArray2.isflat()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + const auto numRows = std::max(inArray1.numRows(), inArray2.numRows()); + const auto numCols = std::max(inArray1.numCols(), inArray2.numCols()); + NdArray returnArray(numRows, numCols); + if (inArray1.numRows() > 1) + { + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + for (uint32 col = 0; col < inArray2.numCols(); ++col) + { + returnArray(row, col) = + function(inArray1[row], + inArray2[col], + std::forward(additionalFunctionArgs)...); + } + } + } + else + { + for (uint32 row = 0; row < inArray2.numRows(); ++row) + { + for (uint32 col = 0; col < inArray1.numCols(); ++col) + { + returnArray(row, col) = + function(inArray1[col], + inArray2[row], + std::forward(additionalFunctionArgs)...); + } + } + } + return returnArray; + }(); + } + else if (inArray1.isflat()) + { + return broadcaster(inArray2, + inArray1, + function, + std::forward(additionalFunctionArgs)...); + } + else if (inArray2.isflat()) + { + if (inArray2.numRows() > 1 && inArray2.numRows() == inArray1.numRows()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + const auto value = inArray2[row]; + stl_algorithms::transform( + inArray1.cbegin(row), + inArray1.cend(row), + returnArray.begin(row), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + return returnArray; + }(); + } + else if (inArray2.numCols() > 1 && inArray2.numCols() == inArray1.numCols()) + { + return broadcaster(inArray1.transpose(), + inArray2.transpose(), + function, + std::forward(additionalFunctionArgs)...) + .transpose(); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + + return {}; // get rid of compiler warning + } +} // namespace nc::broadcast diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayCore.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayCore.hpp new file mode 100644 index 0000000000000000000000000000000000000000..bceb27caac4283ddbbddcf5de50f1709da3ec87c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayCore.hpp @@ -0,0 +1,4943 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds 1D and 2D arrays, the main work horse of the NumCpp library +/// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Endian.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray/NdArrayIterators.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/essentiallyEqualComplex.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Utils/value2str.hpp" + +namespace nc +{ + namespace type_traits + { + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index type for NdArray + /// + template + struct is_ndarray_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index typefor NdArray + /// + + template + struct is_ndarray_int> + { + static constexpr bool value = std::is_integral_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_int_v = is_ndarray_int::value; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is an unsigned integer type + /// + template + struct is_ndarray_signed_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is an unsigned integer type + /// + + template + struct is_ndarray_signed_int> + { + static constexpr bool value = std::is_signed_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_signed_int_v = is_ndarray_signed_int::value; + + //============================================================================ + // Class Description: + /// is_ndarray_int + /// + template + using ndarray_int_concept = std::enable_if_t, int>; + } // namespace type_traits + + //================================================================================ + // Class Description: + /// Holds 1D and 2D arrays, the main work horse of the NumCpp library + template> + class NdArray + { + private: + STATIC_ASSERT_VALID_DTYPE(dtype); + static_assert(std::is_same_v, + "value_type and Allocator::value_type must match"); + + using AllocType = typename std::allocator_traits::template rebind_alloc; + using AllocTraits = std::allocator_traits; + + public: + using self_type = NdArray; + using value_type = dtype; + using allocator_type = Allocator; + using pointer = typename AllocTraits::pointer; + using const_pointer = typename AllocTraits::const_pointer; + using reference = dtype&; + using const_reference = const dtype&; + using size_type = uint32; + using index_type = int32; + using difference_type = typename AllocTraits::difference_type; + + using iterator = NdArrayIterator; + using const_iterator = NdArrayConstIterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + using column_iterator = NdArrayColumnIterator; + using const_column_iterator = NdArrayConstColumnIterator; + using reverse_column_iterator = std::reverse_iterator; + using const_reverse_column_iterator = std::reverse_iterator; + + //============================================================================ + // Method Description: + /// Defualt Constructor, not very usefull... + /// + NdArray() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inSquareSize: square number of rows and columns + /// + explicit NdArray(size_type inSquareSize) : + shape_(inSquareSize, inSquareSize), + size_(inSquareSize * inSquareSize) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inNumRows + /// @param inNumCols + /// + NdArray(size_type inNumRows, size_type inNumCols) : + shape_(inNumRows, inNumCols), + size_(inNumRows * inNumCols) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inShape + /// + explicit NdArray(const Shape& inShape) : + shape_(inShape), + size_(shape_.size()) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + NdArray(std::initializer_list inList) : + shape_(1, static_cast(inList.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inList.begin(), inList.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList: 2D initializer list + /// + NdArray(const std::initializer_list>& inList) : + shape_(static_cast(inList.size()), 0) + { + for (const auto& list : inList) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(list.size()); + } + else if (list.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR( + "All rows of the initializer list needs to have the same number of elements"); + } + } + + size_ = shape_.size(); + newArray(); + uint32 row = 0; + for (const auto& list : inList) + { + const auto ptr = begin() += row * shape_.cols; + stl_algorithms::copy(list.begin(), list.end(), ptr); + ++row; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template, int> = 0> + NdArray(std::array& inArray, bool copy = true) : + shape_(1, static_cast(ArraySize)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inArray.begin(), inArray.end(), begin()); + } + } + else + { + array_ = inArray.data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template + NdArray(std::array, Dim0Size>& in2dArray, bool copy = true) : + shape_(static_cast(Dim0Size), static_cast(Dim1Size)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + const auto start = in2dArray.front().begin(); + stl_algorithms::copy(start, start + size_, begin()); + } + } + else + { + array_ = in2dArray.front().data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template, int> = 0> + NdArray(std::vector& inVector, bool copy = true) : + shape_(1, static_cast(inVector.size())), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inVector.begin(), inVector.end(), begin()); + } + } + else + { + array_ = inVector.data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dVector + /// + explicit NdArray(const std::vector>& in2dVector) : + shape_(static_cast(in2dVector.size()), 0) + { + for (const auto& row : in2dVector) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(row.size()); + } + else if (row.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("All rows of the 2d vector need to have the same number of elements"); + } + } + + size_ = shape_.size(); + + newArray(); + auto currentPosition = begin(); + for (const auto& row : in2dVector) + { + stl_algorithms::copy(row.begin(), row.end(), currentPosition); + currentPosition += shape_.cols; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template + NdArray(std::vector>& in2dArray, bool copy = true) : + shape_(static_cast(in2dArray.size()), static_cast(Dim1Size)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + const auto start = in2dArray.front().begin(); + stl_algorithms::copy(start, start + size_, begin()); + } + } + else + { + array_ = in2dArray.front().data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inDeque + /// + template, int> = 0> + explicit NdArray(const std::deque& inDeque) : + shape_(1, static_cast(inDeque.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inDeque.begin(), inDeque.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dDeque + /// + explicit NdArray(const std::deque>& in2dDeque) : + shape_(static_cast(in2dDeque.size()), 0) + { + for (const auto& row : in2dDeque) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(row.size()); + } + else if (row.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("All rows of the 2d vector need to have the same number of elements"); + } + } + + size_ = shape_.size(); + + newArray(); + auto currentPosition = begin(); + for (const auto& row : in2dDeque) + { + stl_algorithms::copy(row.begin(), row.end(), currentPosition); + currentPosition += shape_.cols; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + explicit NdArray(const std::list& inList) : + shape_(1, static_cast(inList.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inList.begin(), inList.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inFirst + /// @param inLast + /// + template::value_type, dtype>, int> = 0> + NdArray(Iterator inFirst, Iterator inLast) : + shape_(1, static_cast(std::distance(inFirst, inLast))), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inFirst, inLast, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Copies the contents of the buffer into + /// the array. + /// + /// @param inPtr: const_pointer to beginning of buffer + /// @param size: number of elements in buffer + /// + NdArray(const_pointer inPtr, size_type size) : + shape_(1, size), + size_(size) + { + newArray(); + if (inPtr != nullptr && size_ > 0) + { + stl_algorithms::copy(inPtr, inPtr + size_, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Copies the contents of the buffer into + /// the array. + /// + /// @param inPtr: const_pointer to beginning of buffer + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// + template, int> = 0, + std::enable_if_t, int> = 0> + NdArray(const_pointer inPtr, UIntType1 numRows, UIntType2 numCols) : + shape_(numRows, numCols), + size_(shape_.size()) + { + newArray(); + if (inPtr != nullptr && size_ > 0) + { + stl_algorithms::copy(inPtr, inPtr + size_, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Operates as a shell around an already existing + /// array of data. + /// + /// @param inPtr: pointer to beginning of the array + /// @param size: the number of elements in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// + template, int> = 0> + NdArray(pointer inPtr, size_type size, BoolType takeOwnership) noexcept : + shape_(1, size), + size_(size), + array_(inPtr), + ownsPtr_(takeOwnership) + { + } + + //============================================================================ + // Method Description: + /// Constructor. Operates as a shell around an already existing + /// array of data. + /// + /// @param inPtr: pointer to beginning of the array + /// @param numRows: the number of rows in the array + /// @param numCols: the nubmer of column in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// + template, int> = 0> + NdArray(pointer inPtr, size_type numRows, size_type numCols, BoolType takeOwnership) noexcept : + shape_(numRows, numCols), + size_(numRows * numCols), + array_(inPtr), + ownsPtr_(takeOwnership) + { + } + + //============================================================================ + // Method Description: + /// Copy Constructor + /// + /// @param inOtherArray + /// + NdArray(const self_type& inOtherArray) : + shape_(inOtherArray.shape_), + size_(inOtherArray.size_), + endianess_(inOtherArray.endianess_) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inOtherArray.cbegin(), inOtherArray.cend(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Move Constructor + /// + /// @param inOtherArray + /// + NdArray(self_type&& inOtherArray) noexcept : + shape_(inOtherArray.shape_), + size_(inOtherArray.size_), + endianess_(inOtherArray.endianess_), + array_(inOtherArray.array_), + ownsPtr_(inOtherArray.ownsPtr_) + { + inOtherArray.shape_.rows = inOtherArray.shape_.cols = 0; + inOtherArray.size_ = 0; + inOtherArray.ownsPtr_ = false; + inOtherArray.array_ = nullptr; + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~NdArray() noexcept + { + deleteArray(); + } + + //============================================================================ + // Method Description: + /// Cast to bool operator + /// @returns bool false if empty, otherwise true + /// + explicit operator bool() const noexcept + { + return isempty(); + } + + //============================================================================ + // Method Description: + /// Assignment operator, performs a deep copy + /// + /// @param rhs + /// @return NdArray + /// + self_type& operator=(const self_type& rhs) + { + if (&rhs != this) + { + if (rhs.size_ > 0) + { + newArray(rhs.shape_); + endianess_ = rhs.endianess_; + + stl_algorithms::copy(rhs.cbegin(), rhs.cend(), begin()); + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Assignment operator, sets the entire array to a single + /// scalar value. + /// + /// @param inValue + /// @return NdArray + /// + self_type& operator=(value_type inValue) noexcept + { + if (array_ != nullptr) + { + stl_algorithms::fill(begin(), end(), inValue); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Move operator, performs a deep move + /// + /// @param rhs + /// @return NdArray + /// + self_type& operator=(self_type&& rhs) noexcept + { + if (&rhs != this) + { + deleteArray(); + shape_ = rhs.shape_; + size_ = rhs.size_; + endianess_ = rhs.endianess_; + array_ = rhs.array_; + ownsPtr_ = rhs.ownsPtr_; + + rhs.shape_.rows = rhs.shape_.cols = rhs.size_ = 0; + rhs.array_ = nullptr; + rhs.ownsPtr_ = false; + } + + return *this; + } + + //============================================================================ + // Method Description: + /// 1D access operator with no bounds checking + /// + /// @param inIndex + /// @return value + /// + reference operator[](index_type inIndex) noexcept + { + return const_cast(const_cast(this)->operator[](inIndex)); + } + + //============================================================================ + // Method Description: + /// const 1D access operator with no bounds checking + /// + /// @param inIndex + /// @return value + /// + [[nodiscard]] const_reference operator[](index_type inIndex) const noexcept + { + if (inIndex < 0) + { + inIndex += size_; + } + + return array_[inIndex]; + } + + //============================================================================ + // Method Description: + /// 2D access operator with no bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + reference operator()(index_type inRowIndex, index_type inColIndex) noexcept + { + return const_cast(const_cast(this)->operator()(inRowIndex, inColIndex)); + } + + //============================================================================ + // Method Description: + /// const 2D access operator with no bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + [[nodiscard]] const_reference operator()(index_type inRowIndex, index_type inColIndex) const noexcept + { + if (inRowIndex < 0) + { + inRowIndex += shape_.rows; + } + + if (inColIndex < 0) + { + inColIndex += shape_.cols; + } + + return array_[inRowIndex * shape_.cols + inColIndex]; + } + + //============================================================================ + // Method Description: + /// 1D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator[](Slice inSlice) const + { + return operator[](toIndices(inSlice, Axis::NONE)); + } + + //============================================================================ + // Method Description: + /// Returns the values from the input mask with no bounds checking + /// + /// @param inMask + /// @return NdArray + /// + [[nodiscard]] self_type operator[](const NdArray& inMask) const + { + return operator[](inMask.flatnonzero()); + } + + //============================================================================ + // Method Description: + /// Returns the values from the input indices with no bounds checking + /// + /// @param inIndices + /// @return NdArray + /// + /// + template = 0> + [[nodiscard]] self_type operator[](const Indices& inIndices) const + { + auto outArray = self_type(1, static_cast(inIndices.size())); + size_type i = 0; + for (auto& index : inIndices) + { + outArray[i++] = operator[](static_cast(index)); + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowSlice + /// @param inColSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator()(Slice inRowSlice, Slice inColSlice) const + { + return operator()(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowSlice + /// @param inColIndex + /// @return NdArray + /// + [[nodiscard]] self_type operator()(Slice inRowSlice, index_type inColIndex) const + { + const NdArray colIndices = { inColIndex }; + return operator()(toIndices(inRowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowIndex + /// @param inColSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator()(index_type inRowIndex, Slice inColSlice) const + { + const NdArray rowIndices = { inRowIndex }; + return operator()(rowIndices, toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colIndex + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(const Indices& rowIndices, index_type colIndex) const + { + const NdArray colIndices = { colIndex }; + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colSlice + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(const Indices& rowIndices, Slice colSlice) const + { + return operator()(rowIndices, toIndices(colSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndex + /// @param colIndices + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(index_type rowIndex, const Indices& colIndices) const + { + const NdArray rowIndices = { rowIndex }; + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowSlice + /// @param colIndices + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(Slice rowSlice, const Indices& colIndices) const + { + return operator()(toIndices(rowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colIndices + /// @return NdArray + /// + template = 0, + type_traits::ndarray_int_concept = 0> + [[nodiscard]] self_type operator()(const RowIndices& rowIndices, const ColIndices& colIndices) const + { + self_type returnArray(rowIndices.size(), colIndices.size()); + + size_type rowCounter = 0; + for (auto rowIter = rowIndices.begin(); rowIter != rowIndices.end(); ++rowIter) + { + size_type colCounter = 0; + for (auto colIter = colIndices.begin(); colIter != colIndices.end(); ++colIter) + { + returnArray(rowCounter, colCounter++) = operator()(*rowIter, *colIter); + } + + ++rowCounter; + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns a Slice object for slicing a row to the end of + /// array. + /// + /// @param inStartIdx (default 0) + /// @param inStepSize (default 1) + /// @return Slice + /// + [[nodiscard]] Slice cSlice(index_type inStartIdx = 0, size_type inStepSize = 1) const + { + return Slice(inStartIdx, shape_.cols, inStepSize); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns a Slice object for slicing a column to the end + /// of the array. + /// + /// @param inStartIdx (default 0) + /// @param inStepSize (default 1) + /// @return Slice + /// + [[nodiscard]] Slice rSlice(index_type inStartIdx = 0, size_type inStepSize = 1) const + { + return Slice(inStartIdx, shape_.rows, inStepSize); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// 1D access method with bounds checking + /// + /// @param inIndex + /// @return value + /// + reference at(index_type inIndex) + { + return const_cast(const_cast(this)->at(inIndex)); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inIndex + /// @return value + /// + [[nodiscard]] const_reference at(index_type inIndex) const + { + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inIndex) > static_cast(size_ - 1)) + { + std::string errStr = "Input index " + utils::num2str(inIndex); + errStr += " is out of bounds for array of size " + utils::num2str(size_) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + return operator[](inIndex); // cppcheck-suppress returnTempReference + } + + //============================================================================ + // Method Description: + /// 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + reference at(index_type inRowIndex, index_type inColIndex) + { + return const_cast(const_cast(this)->at(inRowIndex, inColIndex)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + [[nodiscard]] const_reference at(index_type inRowIndex, index_type inColIndex) const + { + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inRowIndex) > static_cast(shape_.rows - 1)) + { + std::string errStr = "Row index " + utils::num2str(inRowIndex); + errStr += " is out of bounds for array of size " + utils::num2str(shape_.rows) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inColIndex) > static_cast(shape_.cols - 1)) + { + std::string errStr = "Column index " + utils::num2str(inColIndex); + errStr += " is out of bounds for array of size " + utils::num2str(shape_.cols) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + return operator()(inRowIndex, inColIndex); // cppcheck-suppress returnTempReference + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inSlice) const + { + return at(toIndices(inSlice, Axis::NONE)); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inMask + /// @return Ndarray + /// + [[nodiscard]] self_type at(const NdArray& inMask) const + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("Input mask must have the same dimensions as array."); + } + + return operator[](inMask); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& inIndices) const + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [this](auto index) + { + auto indexSigned = static_cast(index); + if (indexSigned < 0) + { + indexSigned += size_; + } + + if (indexSigned < 0 || indexSigned > static_cast(size_ - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions"); + } + }); + + return operator[](inIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowSlice + /// @param inColSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inRowSlice, const Slice& inColSlice) const + { + return at(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowSlice + /// @param inColIndex + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inRowSlice, index_type inColIndex) const + { + const NdArray colIndices = { inColIndex }; + return at(toIndices(inRowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(index_type inRowIndex, const Slice& inColSlice) const + { + const NdArray rowIndices = { inRowIndex }; + return at(rowIndices, toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colIndex + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& rowIndices, index_type colIndex) const + { + const NdArray colIndices = { colIndex }; + return at(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colSlice + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& rowIndices, Slice colSlice) const + { + return at(rowIndices, toIndices(colSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndex + /// @param colIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(index_type rowIndex, const Indices& colIndices) const + { + const NdArray rowIndices = { rowIndex }; + return at(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowSlice + /// @param colIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(Slice rowSlice, const Indices& colIndices) const + { + return at(toIndices(rowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colIndices + /// @return Ndarray + /// + template = 0, + type_traits::ndarray_int_concept = 0> + [[nodiscard]] self_type at(const RowIndices& rowIndices, const ColIndices& colIndices) const + { + stl_algorithms::for_each(rowIndices.begin(), + rowIndices.end(), + [this](auto row) + { + auto rowSigned = static_cast(row); + if (rowSigned < 0) + { + rowSigned += shape_.rows; + } + + if (rowSigned < 0 || rowSigned > static_cast(shape_.rows - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Row index exceeds matrix dimensions"); + } + }); + + stl_algorithms::for_each(colIndices.begin(), + colIndices.end(), + [this](auto col) + { + auto colSigned = static_cast(col); + if (colSigned < 0) + { + colSigned += shape_.cols; + } + + if (colSigned < 0 || colSigned > static_cast(shape_.cols - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Column index exceeds matrix dimensions"); + } + }); + + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// iterator to the beginning of the flattened array + /// @return iterator + /// + [[nodiscard]] iterator begin() noexcept + { + return iterator(array_); + } + + //============================================================================ + // Method Description: + /// iterator to the beginning of the input row + /// + /// @param inRow + /// @return iterator + /// + [[nodiscard]] iterator begin(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return begin() += (inRow * shape_.cols); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return cbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin(size_type inRow) const + { + return cbegin(inRow); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin() const noexcept + { + return const_iterator(array_); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return cbegin() += (inRow * shape_.cols); + } + + //============================================================================ + // Method Description: + /// column_iterator to the beginning of the flattened array + /// @return column_iterator + /// + [[nodiscard]] column_iterator colbegin() noexcept + { + return column_iterator(array_, shape_.rows, shape_.cols); + } + + //============================================================================ + // Method Description: + /// column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return column_iterator + /// + [[nodiscard]] column_iterator colbegin(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return colbegin() += (inCol * shape_.rows); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the beginning of the flattened array + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colbegin() const noexcept + { + return ccolbegin(); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colbegin(size_type inCol) const + { + return ccolbegin(inCol); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to the beginning of the flattened array + /// + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolbegin() const noexcept + { + return const_column_iterator(array_, shape_.rows, shape_.cols); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolbegin(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return ccolbegin() += (inCol * shape_.rows); + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the beginning of the flattened array + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the beginning of the input row + /// + /// @param inRow + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rbegin(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return rbegin() += (shape_.rows - inRow - 1) * shape_.cols; + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_reverse_iterator rbegin(size_type inRow) const + { + return crbegin(inRow); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the beginning of the flattened array + /// + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crbegin(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return crbegin() += (shape_.rows - inRow - 1) * shape_.cols; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the beginning of the flattened array + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolbegin() noexcept + { + return reverse_column_iterator(colend()); + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolbegin(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return rcolbegin() += (shape_.cols - inCol - 1) * shape_.rows; + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolbegin() const noexcept + { + return crcolbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolbegin(size_type inCol) const + { + return crcolbegin(inCol); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the beginning of the flattened array + /// + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolbegin() const noexcept + { + return const_reverse_column_iterator(ccolend()); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolbegin(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return crcolbegin() += (shape_.cols - inCol - 1) * shape_.rows; + } + + //============================================================================ + // Method Description: + /// iterator to 1 past the end of the flattened array + /// @return iterator + /// + [[nodiscard]] iterator end() noexcept + { + return begin() += size_; + } + + //============================================================================ + // Method Description: + /// iterator to the 1 past end of the row + /// + /// @param inRow + /// @return iterator + /// + [[nodiscard]] iterator end(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return begin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return cend(); + } + + //============================================================================ + // Method Description: + /// const iterator to the 1 past end of the row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator end(size_type inRow) const + { + return cend(inRow); + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the flattened array + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend() const noexcept + { + return cbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return cbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// reverse_iterator to 1 past the end of the flattened array + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rend() noexcept + { + return rbegin() += size_; + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the 1 past end of the row + /// + /// @param inRow + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rend(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return rbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the flattened array + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator rend() const noexcept + { + return crend(); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the 1 past end of the row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator rend(size_type inRow) const + { + return crend(inRow); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the flattened array + /// + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crend() const noexcept + { + return crbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the input row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crend(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return crbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// column_iterator to 1 past the end of the flattened array + /// @return column_iterator + /// + [[nodiscard]] column_iterator colend() noexcept + { + return colbegin() += size_; + } + + //============================================================================ + // Method Description: + /// column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return column_iterator + /// + [[nodiscard]] column_iterator colend(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return colbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// const column_iterator to 1 past the end of the flattened array + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colend() const noexcept + { + return ccolend(); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colend(size_type inCol) const + { + return ccolend(inCol); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to 1 past the end of the flattened array + /// + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolend() const noexcept + { + return ccolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_column_iterator to 1 past the end of the input col + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolend(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return ccolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to 1 past the end of the flattened array + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolend() noexcept + { + return rcolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolend(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return rcolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the flattened array + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolend() const noexcept + { + return crcolend(); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolend(size_type inCol) const + { + return crcolend(inCol); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the flattened array + /// + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolend() const noexcept + { + return crcolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the input col + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolend(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return crcolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// Returns True if all elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.all.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray all(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::all_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::all_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().all(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns True if any elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.any.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray any(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::any_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::any_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().any(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return indices of the maximum values along the given axis. + /// Only the first index is returned. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argmax.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argmax(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { static_cast( + stl_algorithms::max_element(cbegin(), cend(), comparitor) - cbegin()) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = static_cast( + stl_algorithms::max_element(cbegin(row), cend(row), comparitor) - cbegin(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().argmax(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return indices of the minimum values along the given axis. + /// Only the first index is returned. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argmin.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argmin(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { static_cast( + stl_algorithms::min_element(cbegin(), cend(), comparitor) - cbegin()) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = static_cast( + stl_algorithms::min_element(cbegin(row), cend(row), comparitor) - cbegin(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().argmin(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns the indices that would sort this array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argsort.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argsort(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector idx(size_); + std::iota(idx.begin(), idx.end(), 0); + + const auto function = [this](size_type i1, size_type i2) noexcept -> bool + { return (*this)[i1] < (*this)[i2]; }; + + stl_algorithms::stable_sort(idx.begin(), idx.end(), function); + return NdArray(idx); // NOLINT(modernize-return-braced-init-list) + } + case Axis::COL: + { + NdArray returnArray(shape_); + std::vector idx(shape_.cols); + + for (index_type row = 0; row < static_cast(shape_.rows); ++row) + { + std::iota(idx.begin(), idx.end(), 0); + + const auto function = [this, row](size_type i1, size_type i2) noexcept -> bool + { return operator()(row, i1) < operator()(row, i2); }; + + stl_algorithms::stable_sort(idx.begin(), idx.end(), function); + + for (index_type col = 0; col < static_cast(shape_.cols); ++col) + { + returnArray(row, col) = idx[static_cast(col)]; + } + } + return returnArray; + } + case Axis::ROW: + { + return transpose().argsort(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Arithmetic to Arithmetic + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + if constexpr (std::is_same_v) + { + return *this; + } + else + { + NdArray outArray(shape_); + stl_algorithms::transform(cbegin(), + cend(), + outArray.begin(), + [](dtype value) -> dtypeOut { return static_cast(value); }); + + return outArray; + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Arithmetic to Complex + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + NdArray outArray(shape_); + + const auto function = [](const_reference value) -> dtypeOut + { return std::complex(value); }; + + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Complex to Complex + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + if constexpr (std::is_same_v) + { + return *this; + } + else + { + const auto function = [](const_reference value) noexcept -> dtypeOut + { return complex_cast(value); }; + + NdArray outArray(shape_); + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + return outArray; + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Complex to Arithmetic + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + NdArray outArray(shape_); + + const auto function = [](const_reference value) -> dtypeOut { return static_cast(value.real()); }; + + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the last element of the flattened array. + /// + /// @return dtype + /// + [[nodiscard]] const_reference back() const noexcept + { + return *(cend() - 1); + } + + //============================================================================ + // Method Description: + /// Returns a reference the last element of the flattened array. + /// + /// @return dtype + /// + reference back() noexcept + { + return *(end() - 1); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the last element of the input row. + /// + /// @return dtype + /// + [[nodiscard]] const_reference back(size_type row) const + { + return *(cend(row) - 1); + } + + //============================================================================ + // Method Description: + /// Returns a reference the last element of the input row. + /// + /// @return dtype + /// + reference back(size_type row) + { + return *(end(row) - 1); + } + + //============================================================================ + // Method Description: + /// Swap the bytes of the array elements in place + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.byteswap.html + /// + /// @return NdArray + /// + self_type& byteswap() noexcept + { + STATIC_ASSERT_INTEGER(dtype); + + stl_algorithms::for_each(begin(), + end(), + [](dtype& value) noexcept -> void { value = endian::byteSwap(value); }); + + switch (endianess_) + { + case Endian::NATIVE: + { + endianess_ = endian::isLittleEndian() ? Endian::BIG : Endian::LITTLE; + break; + } + case Endian::LITTLE: + { + endianess_ = Endian::BIG; + break; + } + case Endian::BIG: + { + endianess_ = Endian::LITTLE; + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Returns an array whose values are limited to [min, max]. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.clip.html + /// + /// @param inMin: min value to clip to + /// @param inMax: max value to clip to + /// @return clipped value + /// + [[nodiscard]] self_type clip(value_type inMin, value_type inMax) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + self_type outArray(shape_); + stl_algorithms::transform(cbegin(), + cend(), + outArray.begin(), + [inMin, inMax](dtype value) noexcept -> dtype + { +#ifdef __cpp_lib_clamp + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; + + return std::clamp(value, inMin, inMax, comparitor); +#else + if (value < inMin) + { + return inMin; + } + else if (value > inMax) + { + return inMax; + } + + return value; +#endif + }); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns the full column of the array + /// + /// @param inColumn: the column index + /// @return self_type + /// + [[nodiscard]] self_type column(size_type inColumn) const + { + return operator()(rSlice(), inColumn); + } + + //============================================================================ + // Method Description: + /// Returns the full column of the array + /// + /// @param inCols: the column indices + /// @return self_type + /// + [[nodiscard]] self_type columns(const NdArray& inCols) const + { + auto returnArray = self_type(shape_.rows, inCols.size()); + const auto rSlice = returnArray.rSlice(); + + for (size_type i = 0; i < inCols.size(); ++i) + { + returnArray.put(rSlice, i, column(inCols[i])); + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// returns whether or not a value is included the array + /// + /// @param inValue + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + [[nodiscard]] NdArray contains(value_type inValue, Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::find(cbegin(), cend(), inValue) != cend() }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::find(cbegin(row), cend(row), inValue) != cend(row); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().contains(inValue, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return a copy of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.copy.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type copy() const + { + return self_type(*this); + } + + //============================================================================ + // Method Description: + /// Return the cumulative product of the elements along the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.cumprod.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type cumprod(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray(1, size_); + returnArray[0] = front(); + for (size_type i = 1; i < size_; ++i) + { + returnArray[i] = returnArray[i - 1] * array_[i]; + } + + return returnArray; + } + case Axis::COL: + { + self_type returnArray(shape_); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(row, 0) = operator()(row, 0); + for (uint32 col = 1; col < shape_.cols; ++col) + { + returnArray(row, col) = returnArray(row, col - 1) * operator()(row, col); + } + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().cumprod(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.cumsum.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type cumsum(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray(1, size_); + returnArray[0] = front(); + for (size_type i = 1; i < size_; ++i) + { + returnArray[i] = returnArray[i - 1] + array_[i]; + } + + return returnArray; + } + case Axis::COL: + { + self_type returnArray(shape_); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(row, 0) = operator()(row, 0); + for (uint32 col = 1; col < shape_.cols; ++col) + { + returnArray(row, col) = returnArray(row, col - 1) + operator()(row, col); + } + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().cumsum(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns the raw pointer to the underlying data + /// @return pointer + /// + [[nodiscard]] pointer data() noexcept + { + return array_; + } + + //============================================================================ + // Method Description: + /// Returns the raw pointer to the underlying data + /// @return const_pointer + /// + [[nodiscard]] const_pointer data() const noexcept + { + return array_; + } + + //============================================================================ + // Method Description: + /// Releases the internal data pointer so that the destructor + /// will not call delete on it, and returns the raw pointer + /// to the underlying data. + /// @return pointer + /// + [[nodiscard]] pointer dataRelease() noexcept + { + ownsPtr_ = false; + return data(); + } + + //============================================================================ + // Method Description: + /// Return specified diagonals. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.diagonal.html + /// + /// @param inOffset: Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults + /// to 0. + /// @param inAxis: (Optional, default ROW) axis the offset is applied to + /// @return NdArray + /// + [[nodiscard]] self_type diagonal(index_type inOffset = 0, Axis inAxis = Axis::ROW) const + { + switch (inAxis) + { + case Axis::COL: + { + std::vector diagnolValues; + size_type col = 0; + for (index_type row = inOffset; row < static_cast(shape_.rows); ++row) + { + if (row < 0) + { + ++col; + continue; + } + if (col >= shape_.cols) + { + break; + } + + diagnolValues.push_back(operator()(static_cast(row), col)); + ++col; + } + + return self_type(diagnolValues); + } + case Axis::ROW: + { + return transpose().diagonal(inOffset, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return size of the axis dimension + /// + /// @param inAxis: the array axis + /// @return size of the dimension + /// + [[nodiscard]] size_type dimSize(Axis inAxis) const noexcept + { + switch (inAxis) + { + case Axis::NONE: + { + return size(); + } + case Axis::ROW: + { + return numRows(); + } + case Axis::COL: + { + return numCols(); + } + default: + { + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inOtherArray + /// @return dot product + /// + [[nodiscard]] self_type dot(const self_type& inOtherArray) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (shape_ == inOtherArray.shape_ && (shape_.rows == 1 || shape_.cols == 1)) + { + dtype dotProduct = std::inner_product(cbegin(), cend(), inOtherArray.cbegin(), dtype{ 0 }); + self_type returnArray = { dotProduct }; + return returnArray; + } + if (shape_.cols == inOtherArray.shape_.rows) + { + // 2D array, use matrix multiplication + self_type returnArray(shape_.rows, inOtherArray.shape_.cols); + auto otherArrayT = inOtherArray.transpose(); + + for (uint32 i = 0; i < shape_.rows; ++i) + { + for (uint32 j = 0; j < otherArrayT.shape_.rows; ++j) + { + returnArray(i, j) = + std::inner_product(otherArrayT.cbegin(j), otherArrayT.cend(j), cbegin(i), dtype{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape_.rows) + ", " + utils::num2str(shape_.cols) + "]"; + errStr += " and [" + utils::num2str(inOtherArray.shape_.rows) + ", " + + utils::num2str(inOtherArray.shape_.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return self_type(); // get rid of compiler warning + } + + //============================================================================ + // Method Description: + /// Dump a binary file of the array to the specified file. + /// The array can be read back with nc::load. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dump.html + /// + /// @param inFilename + /// + void dump(const std::string& inFilename) const + { + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("bin"); + } + + std::ofstream ofile(f.c_str(), std::ios::binary); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Unable to open the input file:\n\t" + inFilename); + } + + if (array_ != nullptr) + { + ofile.write(reinterpret_cast(array_), size_ * sizeof(dtype)); + } + ofile.close(); + } + + //============================================================================ + // Method Description: + /// Return the NdArrays endianess + /// + /// @return Endian + /// + [[nodiscard]] Endian endianess() const noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return endianess_; + } + + //============================================================================ + // Method Description: + /// Fill the array with a scalar value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.fill.html + /// + /// @param inFillValue + /// @return None + /// + self_type& fill(value_type inFillValue) noexcept + { + stl_algorithms::fill(begin(), end(), inFillValue); + return *this; + } + + //============================================================================ + // Method Description: + /// Return the indices of the flattened array of the + /// elements that are non-zero. + /// + /// @return NdArray + /// + [[nodiscard]] NdArray flatnonzero() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::vector indices; + size_type idx = 0; + for (auto value : *this) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + indices.push_back(idx); + } + ++idx; + } + + return NdArray(indices); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Return a copy of the array collapsed into one dimension. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.flatten.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type flatten() const + { + self_type outArray(1, size_); + stl_algorithms::copy(cbegin(), cend(), outArray.begin()); + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the first element of the flattened array. + /// + /// @return dtype + /// + [[nodiscard]] const_reference front() const noexcept + { + return *cbegin(); + } + + //============================================================================ + // Method Description: + /// Returns a reference to the first element of the flattened array. + /// + /// @return dtype + /// + reference front() noexcept + { + return *begin(); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the first element of the input row. + /// + /// @return dtype + /// + [[nodiscard]] const_reference front(size_type row) const + { + return *cbegin(row); + } + + //============================================================================ + // Method Description: + /// Returns a reference to the first element of the input row. + /// + /// @return dtype + /// + reference front(size_type row) + { + return *begin(row); + } + + //============================================================================ + // Method Description: + /// Returns a new flat array with the givin flat input indices. + /// + /// @param inIndices + /// @return values + /// + [[nodiscard]] self_type getByIndices(const NdArray& inIndices) const + { + return operator[](inIndices); + } + + //============================================================================ + // Method Description: + /// Takes in a boolean mask the same size as the array + /// and returns a flattened array with the values cooresponding + /// to the input mask. + /// + /// @param inMask + /// @return values + /// + [[nodiscard]] self_type getByMask(const NdArray& inMask) const + { + return operator[](inMask); + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is empty. ie the default constructor + /// was used. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isempty() const noexcept + { + return size_ == 0; + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is flat. ie the number of columns or + /// rows is equal to one. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isflat() const noexcept + { + return !isscalar() && (shape_.rows == 1 || shape_.cols == 1); + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is scalar + /// + /// @return boolean + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isscalar() const noexcept + { + return size_ == 1; + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is sorted. + /// + /// @param inAxis + /// @return boolean + /// + [[nodiscard]] NdArray issorted(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + return { stl_algorithms::is_sorted(cbegin(), cend(), comparitor) }; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::is_sorted(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().issorted(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is square. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool issquare() const noexcept + { + return shape_.issquare(); + } + + //============================================================================ + // Method Description: + /// Copy an element of an array to a standard C++ scalar and return it. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.item.html + /// + /// @return array element + /// + [[nodiscard]] value_type item() const + { + if (!isscalar()) + { + THROW_INVALID_ARGUMENT_ERROR("Can only convert an array of size 1 to a C++ scalar"); + } + + return front(); + } + + //============================================================================ + // Method Description: + /// Return the maximum along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.max.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type max(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { *stl_algorithms::max_element(cbegin(), cend(), comparitor) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = *stl_algorithms::max_element(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().max(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the minimum along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.min.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type min(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { *stl_algorithms::min_element(cbegin(), cend(), comparitor) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = *stl_algorithms::min_element(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().min(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the median along a given axis. + /// If the dtype is floating point then the middle elements will be + /// averaged for arrays of even number of elements. + /// If the dtype is integral then the middle elements will be intager + /// averaged (rounded down to integer) for arrays of even number of elements. + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type median(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + if (size_ == 0) + { + THROW_RUNTIME_ERROR("Median is undefined for an array of size = 0."); + } + + switch (inAxis) + { + case Axis::NONE: + { + self_type copyArray(*this); + + const size_type middleIdx = size_ / 2; // integer division + stl_algorithms::nth_element(copyArray.begin(), + copyArray.begin() + middleIdx, + copyArray.end(), + comparitor); + + dtype medianValue = copyArray.array_[middleIdx]; + if (size_ % 2 == 0) + { + const size_type lhsIndex = middleIdx - 1; + stl_algorithms::nth_element(copyArray.begin(), + copyArray.begin() + lhsIndex, + copyArray.end(), + comparitor); + medianValue = + (medianValue + copyArray.array_[lhsIndex]) / dtype{ 2 }; // potentially integer division, ok + } + + return { medianValue }; + } + case Axis::COL: + { + self_type copyArray(*this); + self_type returnArray(1, shape_.rows); + + const bool isEven = shape_.cols % 2 == 0; + for (uint32 row = 0; row < shape_.rows; ++row) + { + const uint32 middleIdx = shape_.cols / 2; // integer division + stl_algorithms::nth_element(copyArray.begin(row), + copyArray.begin(row) + middleIdx, + copyArray.end(row), + comparitor); + + dtype medianValue = copyArray(row, middleIdx); + if (isEven) + { + const size_type lhsIndex = middleIdx - 1; + stl_algorithms::nth_element(copyArray.begin(row), + copyArray.begin(row) + lhsIndex, + copyArray.end(row), + comparitor); + medianValue = (medianValue + copyArray(row, lhsIndex)) / + dtype{ 2 }; // potentially integer division, ok + } + + returnArray(0, row) = medianValue; + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().median(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Fills the array with nans. + /// + /// + self_type& nans() noexcept + + { + STATIC_ASSERT_FLOAT(dtype); + + fill(constants::nan); + return *this; + } + + //============================================================================ + // Method Description: + /// Returns the number of bytes held by the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.nbytes.html + /// + /// @return number of bytes + /// + [[nodiscard]] uint64 nbytes() const noexcept + { + return static_cast(sizeof(dtype) * size_); + } + + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.newbyteorder.html + /// + /// @param inEndianess + /// @return NdArray + /// + [[nodiscard]] self_type newbyteorder(Endian inEndianess) const + { + STATIC_ASSERT_INTEGER(dtype); + + const bool nativeIsLittle = endian::isLittleEndian(); + + switch (endianess_) + { + case Endian::NATIVE: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + return NdArray(*this); + } + case Endian::BIG: + { + if (nativeIsLittle) + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::BIG; + return outArray; + } + else + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::BIG; + return outArray; + } + } + case Endian::LITTLE: + { + if (nativeIsLittle) + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + else + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + case Endian::BIG: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + if (nativeIsLittle) + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + else + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + } + case Endian::BIG: + { + return NdArray(*this); + } + case Endian::LITTLE: + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + case Endian::LITTLE: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + if (nativeIsLittle) + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + else + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + } + case Endian::BIG: + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::BIG; + return outArray; + } + case Endian::LITTLE: + { + return NdArray(*this); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns True if none elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.any.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray none(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::none_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::none_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().none(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the row/col indices of the array of the + /// elements that are non-zero. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.nonzero.html + /// + /// @return std::pair where first is the row indices and second is the + /// column indices + /// + [[nodiscard]] std::pair, NdArray> nonzero() const; + + //============================================================================ + // Method Description: + /// Returns the number of columns in the array + /// + /// + /// @return size_type + /// + [[nodiscard]] size_type numCols() const noexcept + { + return shape_.cols; + } + + //============================================================================ + // Method Description: + /// Returns the number of rows in the array + /// + /// + /// @return size_type + /// + [[nodiscard]] size_type numRows() const noexcept + { + return shape_.rows; + } + + //============================================================================ + // Method Description: + /// Fills the array with ones + /// + /// + self_type& ones() noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + fill(dtype{ 1 }); + return *this; + } + + //============================================================================ + // Method Description: + /// Returns whether or not the array object owns the underlying data + /// + /// @return bool + /// + bool ownsInternalData() noexcept + { + return ownsPtr_; + } + + //============================================================================ + // Method Description: + /// Rearranges the elements in the array in such a way that + /// value of the element in kth position is in the position it + /// would be in a sorted array. All elements smaller than the kth + /// element are moved before this element and all equal or greater + /// are moved behind it. The ordering of the elements in the two + /// partitions is undefined. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.partition.html + /// + /// @param inKth: kth element + /// @param inAxis (Optional, default NONE) + /// @return None + /// + self_type& partition(size_type inKth, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; // cppcheck-suppress returnTempReference + + switch (inAxis) + { + case Axis::NONE: + { + if (inKth >= size_) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(size_) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + stl_algorithms::nth_element(begin(), begin() + inKth, end(), comparitor); + break; + } + case Axis::COL: + { + if (inKth >= shape_.cols) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(shape_.cols) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + for (uint32 row = 0; row < shape_.rows; ++row) + { + stl_algorithms::nth_element(begin(row), begin(row) + inKth, end(row), comparitor); + } + break; + } + case Axis::ROW: + { + if (inKth >= shape_.rows) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(shape_.rows) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + self_type transposedArray = transpose(); + for (uint32 row = 0; row < transposedArray.shape_.rows; ++row) + { + stl_algorithms::nth_element(transposedArray.begin(row), + transposedArray.begin(row) + inKth, + transposedArray.end(row), + comparitor); + } + *this = transposedArray.transpose(); + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Prints the array to the console. + /// + /// + void print() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::cout << *this; + } + + //============================================================================ + // Method Description: + /// Return the product of the array elements over the given axis + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.prod.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type prod(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + dtype product = std::accumulate(cbegin(), cend(), dtype{ 1 }, std::multiplies()); + self_type returnArray = { product }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = + std::accumulate(cbegin(row), cend(row), dtype{ 1 }, std::multiplies()); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().prod(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Peak to peak (maximum - minimum) value along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.ptp.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type ptp(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + const auto result = stl_algorithms::minmax_element(cbegin(), cend(), comparitor); + self_type returnArray = { *result.second - *result.first }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + const auto result = stl_algorithms::minmax_element(cbegin(row), cend(row), comparitor); + returnArray(0, row) = *result.second - *result.first; + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().ptp(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// set the flat index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndex + /// @param inValue + /// + self_type& put(index_type inIndex, const value_type& inValue) + { + at(inIndex) = inValue; + + return *this; + } + + //============================================================================ + // Method Description: + /// set the 2D row/col index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRow + /// @param inCol + /// @param inValue + /// + self_type& put(index_type inRow, index_type inCol, const value_type& inValue) + { + at(inRow, inCol) = inValue; + + return *this; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inIndices, const value_type& inValue) + { + for (auto index : inIndices) + { + put(index, inValue); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values[n] for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inIndices, const self_type& inValues) + { + if (inValues.isscalar()) + { + return put(inIndices, inValues.item()); + } + else if (inIndices.size() != inValues.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input indices do not match values dimensions."); + } + + size_type counter = 0; + for (auto index : inIndices) + { + put(index, inValues[counter++]); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inSlice, const value_type& inValue) + { + return put(toIndices(inSlice, Axis::NONE), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(const Slice& inSlice, const self_type& inValues) + { + return put(toIndices(inSlice, Axis::NONE), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + self_type& put(const RowIndices& inRowIndices, const ColIndices& inColIndices, const value_type& inValue) + { + stl_algorithms::for_each(inRowIndices.begin(), + inRowIndices.end(), + [this, &inColIndices, &inValue](const auto row) + { + stl_algorithms::for_each(inColIndices.begin(), + inColIndices.end(), + [this, row, &inValue](const auto col) + { this->put(row, col, inValue); }); + }); + + return *this; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const RowIndices& inRowIndices, const Slice& inColSlice, const value_type& inValue) + { + return put(inRowIndices, toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Slice& inRowSlice, const ColIndices& inColIndices, const value_type& inValue) + { + return put(toIndices(inRowSlice, Axis::ROW), inColIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, const Slice& inColSlice, const value_type& inValue) + { + return put(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inRowIndices, index_type inColIndex, const value_type& inValue) + { + const NdArray colIndices = { inColIndex }; + return put(inRowIndices, colIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, index_type inColIndex, const value_type& inValue) + { + const NdArray colIndices = { inColIndex }; + return put(toIndices(inRowSlice, Axis::ROW), colIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(index_type inRowIndex, const Indices& inColIndices, const value_type& inValue) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, inColIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(index_type inRowIndex, const Slice& inColSlice, const value_type& inValue) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + self_type& put(const RowIndices& inRowIndices, const ColIndices& inColIndices, const self_type& inValues) + { + std::vector indices; + indices.reserve(inRowIndices.size() * inColIndices.size()); + std::for_each(inRowIndices.begin(), + inRowIndices.end(), + [this, &inColIndices, &indices](auto row) + { + if constexpr (std::is_signed_v) + { + if (row < 0) + { + row += shape_.rows; + } + // still + if (row < 0) + { + THROW_INVALID_ARGUMENT_ERROR("row index exceeds matrix dimensions"); + } + } + std::for_each(inColIndices.begin(), + inColIndices.end(), + [this, row, &indices](auto col) + { + if constexpr (std::is_signed_v) + { + if (col < 0) + { + col += shape_.cols; + } + // still + if (col < 0) + { + THROW_INVALID_ARGUMENT_ERROR( + "col index exceeds matrix dimensions"); + } + } + indices.push_back(row * shape_.cols + col); + }); + }); + + return put(NdArray(indices.data(), indices.size(), false), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const RowIndices& inRowIndices, Slice inColSlice, const self_type& inValues) + { + return put(inRowIndices, toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(Slice inRowSlice, const ColIndices& inColIndices, const self_type& inValues) + { + return put(toIndices(inRowSlice, Axis::ROW), inColIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(Slice inRowSlice, Slice inColSlice, const self_type& inValues) + { + return put(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inRowIndices, index_type inColIndex, const self_type& inValues) + { + const NdArray colIndices = { inColIndex }; + return put(inRowIndices, colIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, index_type inColIndex, const self_type& inValues) + { + const NdArray colIndices = { inColIndex }; + return put(toIndices(inRowSlice, Axis::ROW), colIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(index_type inRowIndex, const Indices& inColIndices, const self_type& inValues) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, inColIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(index_type inRowIndex, const Slice& inColSlice, const self_type& inValues) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the mask indices to the input value. + /// + /// @param inMask + /// @param inValue + /// + self_type& putMask(const NdArray& inMask, const value_type& inValue) + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the array it is masking."); + } + + return put(inMask.flatnonzero(), inValue); + } + + //============================================================================ + // Method Description: + /// Set the mask indices to the input values. + /// + /// @param inMask + /// @param inValues + /// + self_type& putMask(const NdArray& inMask, const self_type& inValues) + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the array it is masking."); + } + + if (inValues.isscalar()) + { + put(inMask.flatnonzero(), inValues.item()); + } + else + { + put(inMask.flatnonzero(), inValues); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Flattens the array but does not make a copy. + /// + /// Numpy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html + /// + /// @return NdArray + /// + self_type& ravel() + { + reshape(size_); + return *this; + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.repeat.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + [[nodiscard]] self_type repeat(size_type inNumRows, size_type inNumCols) const + { + self_type returnArray(shape_.rows * inNumRows, shape_.cols * inNumCols); + + for (size_type row = 0; row < inNumRows; ++row) + { + for (size_type col = 0; col < inNumCols; ++col) + { + std::vector indices(shape_.size()); + + const size_type rowStart = row * shape_.rows; + const size_type colStart = col * shape_.cols; + + const size_type rowEnd = (row + 1) * shape_.rows; + const size_type colEnd = (col + 1) * shape_.cols; + + size_type counter = 0; + for (size_type rowIdx = rowStart; rowIdx < rowEnd; ++rowIdx) + { + for (size_type colIdx = colStart; colIdx < colEnd; ++colIdx) + { + indices[counter++] = rowIdx * returnArray.shape_.cols + colIdx; + } + } + + returnArray.put(NdArray(indices), *this); + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.repeat.html + /// + /// @param inRepeatShape + /// @return NdArray + /// + [[nodiscard]] self_type repeat(const Shape& inRepeatShape) const + { + return repeat(inRepeatShape.rows, inRepeatShape.cols); + } + + //============================================================================ + // Method Description: + /// Replaces a value of the array with another value + /// + /// @param oldValue: the value to replace + /// @param newValue: the value to replace with + /// + self_type& replace(value_type oldValue, value_type newValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + stl_algorithms::replace(begin(), end(), oldValue, newValue); + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// NOTE: array shape is modified. If a copy is desired then the user should call the copy method: + /// auto aNew = a.reshape(newSize).copy() + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inSize + /// @returns reference to self + /// + self_type& reshape(size_type inSize) + { + if (inSize != size_) + { + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into shape "; + errStr += "[" + utils::num2str(1) + ", " + utils::num2str(inSize) + "]"; + THROW_RUNTIME_ERROR(errStr); + } + + shape_.rows = 1; + shape_.cols = inSize; + + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// NOTE: array shape is modified. If a copy is desired then the user should call the copy method: + /// auto aNew = a.reshape(newRows, newCols).copy() + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inNumRows + /// @param inNumCols + /// @returns reference to self + /// + self_type& reshape(index_type inNumRows, index_type inNumCols) + { + if (inNumRows < 0) + { + if (size_ % inNumCols == 0) + { + return reshape(size_ / inNumCols, inNumCols); + } + + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into a shape "; + errStr += "with " + utils::num2str(inNumCols) + " columns"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + if (inNumCols < 0) + { + if (size_ % inNumRows == 0) + { + return reshape(inNumRows, size_ / inNumRows); + } + + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into a shape "; + errStr += "with " + utils::num2str(inNumRows) + " rows"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + if (static_cast(inNumRows * inNumCols) != size_) + { + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into shape "; + errStr += "[" + utils::num2str(inNumRows) + ", " + utils::num2str(inNumCols) + "]"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + shape_.rows = static_cast(inNumRows); + shape_.cols = static_cast(inNumCols); + + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// NOTE: array shape is modified. If a copy is desired then the user should call the copy method: + /// auto aNew = a.reshape(newShape).copy() + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inShape + /// @returns reference to self + /// + self_type& reshape(const Shape& inShape) + { + return reshape(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inNumRows + /// @param inNumCols + /// + self_type& resizeFast(size_type inNumRows, size_type inNumCols) + { + newArray(Shape(inNumRows, inNumCols)); + return *this; + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inShape + /// + self_type& resizeFast(const Shape& inShape) + { + return resizeFast(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inNumRows + /// @param inNumCols + /// + self_type& resizeSlow(size_type inNumRows, size_type inNumCols) + { + std::vector oldData(size_); + stl_algorithms::copy(begin(), end(), oldData.begin()); + + const Shape inShape(inNumRows, inNumCols); + const Shape oldShape = shape_; + + newArray(inShape); + + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (row >= oldShape.rows || col >= oldShape.cols) + { + operator()(row, col) = dtype{ 0 }; // zero fill + } + else + { + operator()(row, col) = oldData[row * oldShape.cols + col]; + } + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inShape + /// + self_type& resizeSlow(const Shape& inShape) + { + return resizeSlow(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Return a with each element rounded to the given number + /// of decimals. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.round.html + /// + /// @param inNumDecimals (default 0) + /// @return NdArray + /// + [[nodiscard]] self_type round(uint8 inNumDecimals = 0) const + { + STATIC_ASSERT_FLOAT(dtype); + + self_type returnArray(shape_); + const double multFactor = utils::power(10., inNumDecimals); + const auto function = [multFactor](dtype value) noexcept -> dtype + { return static_cast(std::nearbyint(static_cast(value) * multFactor) / multFactor); }; + + stl_algorithms::transform(cbegin(), cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns the full row of the array + /// + /// @param inRow: the row index + /// @return self_type + /// + [[nodiscard]] self_type row(size_type inRow) const + { + return self_type(cbegin(inRow), cend(inRow)); + } + + //============================================================================ + // Method Description: + /// Returns the full row of the array + /// + /// @param inRows: the row indices + /// @return self_type + /// + [[nodiscard]] self_type rows(const NdArray& inRows) const + { + auto returnArray = self_type(inRows.size(), shape_.cols); + const auto cSlice = returnArray.cSlice(); + + for (size_type i = 0; i < inRows.size(); ++i) + { + returnArray.put(i, cSlice, row(inRows[i])); + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return the shape of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.shape.html + /// + /// @return Shape + /// + [[nodiscard]] const Shape& shape() const noexcept + { + return shape_; + } + + //============================================================================ + // Method Description: + /// Return the size of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.size.html + /// + /// @return size + /// + [[nodiscard]] size_type size() const noexcept + { + return size_; + } + + //============================================================================ + // Method Description: + /// Sort an array, in-place. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.sort.html + /// + /// @param inAxis (Optional, default NONE) + /// @return size + /// + self_type& sort(Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; // cppcheck-suppress returnTempReference + + switch (inAxis) + { + case Axis::NONE: + { + stl_algorithms::sort(begin(), end(), comparitor); + break; + } + case Axis::COL: + { + for (uint32 row = 0; row < shape_.rows; ++row) + { + stl_algorithms::sort(begin(row), end(row), comparitor); + } + break; + } + case Axis::ROW: + { + self_type transposedArray = transpose(); + for (uint32 row = 0; row < transposedArray.shape_.rows; ++row) + { + stl_algorithms::sort(transposedArray.begin(row), transposedArray.end(row), comparitor); + } + + *this = transposedArray.transpose(); + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// returns the NdArray as a string representation + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::string out; + out += "["; + for (uint32 row = 0; row < shape_.rows; ++row) + { + out += "["; + for (uint32 col = 0; col < shape_.cols; ++col) + { + out += utils::value2str(operator()(row, col)) + ", "; + } + + if (row == shape_.rows - 1) + { + out += "]"; + } + else + { + out += "]\n"; + } + } + out += "]\n"; + return out; + } + + //============================================================================ + // Method Description: + /// Return the sum of the array elements over the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.sum.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type sum(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { std::accumulate(cbegin(), cend(), dtype{ 0 }) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = std::accumulate(cbegin(row), cend(row), dtype{ 0 }); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().sum(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Interchange two axes of an array. Equivalent to transpose... + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.swapaxes.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type swapaxes() const + { + return transpose(); + } + + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param colIdx1 + /// @param colIdx2 + /// @return reference to self + /// + self_type& swapCols(index_type colIdx1, index_type colIdx2) noexcept + { + for (index_type row = 0; row < static_cast(shape_.rows); ++row) + { + std::swap(operator()(row, colIdx1), operator()(row, colIdx2)); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param rowIdx1 + /// @param rowIdx2 + /// + /// @return reference to self + self_type& swapRows(index_type rowIdx1, index_type rowIdx2) noexcept + { + for (index_type col = 0; col < static_cast(shape_.cols); ++col) + { + std::swap(operator()(rowIdx1, col), operator()(rowIdx2, col)); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Write array to a file as binary. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.tofile.html + /// + /// @param inFilename + /// @return None + /// + void tofile(const std::string& inFilename) const + { + dump(inFilename); + } + + //============================================================================ + // Method Description: + /// Write array to a file as text. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.tofile.html + /// + /// @param inFilename + /// @param inSep: Separator between array items for text output. + /// @return None + /// + void tofile(const std::string& inFilename, const char inSep) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("txt"); + } + + std::ofstream ofile(f.c_str()); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Input file could not be opened:\n\t" + inFilename); + } + + size_type counter = 0; + for (auto value : *this) + { + ofile << value; + if (counter++ != size_ - 1) + { + ofile << inSep; + } + } + ofile.close(); + } + + //============================================================================ + // Method Description: + /// Converts the slice object to an NdArray of indices for this array + /// + /// @param inSlice: the slice object + /// @param inAxis: the array axis + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toIndices(Slice inSlice, Axis inAxis = Axis::NONE) const + { + size_type numElements = 0; + switch (inAxis) + { + case Axis::NONE: + { + numElements = inSlice.numElements(size_); + break; + } + case Axis::ROW: + { + numElements = inSlice.numElements(shape_.rows); + break; + } + case Axis::COL: + { + numElements = inSlice.numElements(shape_.cols); + break; + } + default: + { + // not actually possible, getting rid of compiler warning + THROW_INVALID_ARGUMENT_ERROR("Invalid 'inAxis' option"); + } + } + + if (numElements == 0) + { + return {}; + } + + NdArray indices(1, numElements); + indices[0] = static_cast(inSlice.start); + for (size_type i = 1; i < indices.size(); ++i) + { + indices[static_cast(i)] = static_cast( + indices[static_cast(i - size_type{ 1 })] + static_cast(inSlice.step)); + } + + return indices; + } + + //============================================================================ + // Method Description: + /// Write flattened array to an STL vector + /// + /// @return std::vector + /// + [[nodiscard]] std::vector toStlVector() const + { + return std::vector(cbegin(), cend()); + } + + //============================================================================ + // Method Description: + /// Return the sum along diagonals of the array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.trace.html + /// + /// @param inOffset: Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults + /// to 0. + /// @param inAxis: (Optional, default ROW) Axis to offset from + /// + /// @return value + /// + [[nodiscard]] value_type trace(size_type inOffset = 0, Axis inAxis = Axis::ROW) const noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + size_type rowStart = 0; + size_type colStart = 0; + switch (inAxis) + { + case Axis::ROW: + { + rowStart += inOffset; + break; + } + case Axis::COL: + { + colStart += inOffset; + break; + } + default: + { + // if the user input NONE, override back to ROW + inAxis = Axis::ROW; + break; + } + } + + if (rowStart >= shape_.rows || colStart >= shape_.cols) + { + return dtype{ 0 }; + } + + size_type col = colStart; + dtype sum = 0; + for (size_type row = rowStart; row < shape_.rows; ++row) + { + if (col >= shape_.cols) + { + break; + } + sum += operator()(row, col++); + } + + return sum; + } + + //============================================================================ + // Method Description: + /// Tranpose the rows and columns of an array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.transpose.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type transpose() const + { + self_type transArray(shape_.cols, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + transArray(col, row) = operator()(row, col); + } + } + return transArray; + } + + //============================================================================ + // Method Description: + /// Fills the array with zeros + /// + /// + self_type& zeros() noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + fill(dtype{ 0 }); + return *this; + } + + private: + //====================================Attributes============================== + allocator_type allocator_{}; + Shape shape_{ 0, 0 }; + size_type size_{ 0 }; + Endian endianess_{ Endian::NATIVE }; + pointer array_{ nullptr }; + bool ownsPtr_{ false }; + + //============================================================================ + // Method Description: + /// Deletes the internal array + /// + void deleteArray() noexcept + { + if (ownsPtr_ && array_ != nullptr) + { + allocator_.deallocate(array_, size_); + } + + array_ = nullptr; + shape_.rows = shape_.cols = 0; + size_ = 0; + ownsPtr_ = false; + endianess_ = Endian::NATIVE; + } + + //============================================================================ + // Method Description: + /// Creates a new internal array + /// + void newArray() + { + if (size_ > 0) + { + array_ = allocator_.allocate(size_); + ownsPtr_ = true; + } + } + + //============================================================================ + // Method Description: + /// Creates a new internal array + /// + /// @param inShape + /// + void newArray(const Shape& inShape) + { + deleteArray(); + + shape_ = inShape; + size_ = inShape.size(); + newArray(); + } + }; + + // NOTE: this needs to be defined outside of the class to get rid of a compiler + // error in Visual Studio + template + [[nodiscard]] std::pair, NdArray> NdArray::nonzero() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::vector rowIndices; + std::vector colIndices; + + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + if (!utils::essentiallyEqual(operator()(row, col), dtype{ 0 })) + { + rowIndices.push_back(row); + colIndices.push_back(col); + } + } + } + + return std::make_pair(NdArray(rowIndices), NdArray(colIndices)); + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp new file mode 100644 index 0000000000000000000000000000000000000000..701b7aaab0b02287fcc09534901a4969411fcd36 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp @@ -0,0 +1,982 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Custom iterators for the NdArray class +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc +{ + //================================================================================ + // Class Description: + /// Custom const_iterator for NdArray + template + class NdArrayConstIterator + { + private: + using self_type = NdArrayConstIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using pointer = PointerType; + using reference = const value_type&; + using difference_type = DifferenceType; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + NdArrayConstIterator() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ptr: the iterator pointer + /// + explicit NdArrayConstIterator(pointer ptr) noexcept : + ptr_(ptr) + { + } + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return *ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + ++ptr_; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + ++*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + --ptr_; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + --*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + ptr_ += offset; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + return *this += -offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param rhs + /// @return difference_type + /// + difference_type operator-(const self_type& rhs) const noexcept + { + return ptr_ - rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return *(*this + offset); + } + + //============================================================================ + // Method Description: + /// Iterator equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const self_type& rhs) const noexcept + { + return ptr_ == rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator not-equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const self_type& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Iterator less than operator + /// + /// @param rhs + /// @return bool + /// + bool operator<(const self_type& rhs) const noexcept + { + return ptr_ < rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator greater than operator + /// + /// @param rhs + /// @return bool + /// + bool operator>(const self_type& rhs) const noexcept + { + return rhs < *this; + } + + //============================================================================ + // Method Description: + /// Iterator less than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator<=(const self_type& rhs) const noexcept + { + return !(rhs < *this); + } + + //============================================================================ + // Method Description: + /// Iterator greater than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator>=(const self_type& rhs) const noexcept + { + return !(*this < rhs); + } + + private: + pointer ptr_{ nullptr }; + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayConstIterator + operator+(typename NdArrayConstIterator::difference_type offset, + NdArrayConstIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom iterator for NdArray + template + class NdArrayIterator : public NdArrayConstIterator + { + private: + using MyBase = NdArrayConstIterator; + using self_type = NdArrayIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using pointer = PointerType; + using reference = value_type&; + using difference_type = DifferenceType; + + using MyBase::MyBase; + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return const_cast(MyBase::operator*()); + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return const_cast(MyBase::operator->()); + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + MyBase::operator++(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + MyBase:: operator++(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + MyBase::operator--(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + MyBase:: operator--(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + MyBase::operator+=(offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + MyBase::operator-=(offset); + return *this; + } + + using MyBase::operator-; + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return const_cast(MyBase::operator[](offset)); + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return NdArrayIterator + /// + template + NdArrayIterator + operator+(typename NdArrayIterator::difference_type offset, + NdArrayIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom column const_iterator for NdArray + template + class NdArrayConstColumnIterator + { + private: + using self_type = NdArrayConstColumnIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using size_type = SizeType; + using pointer = PointerType; + using reference = const value_type&; + using difference_type = DifferenceType; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + NdArrayConstColumnIterator() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ptr: the iterator pointer + /// @param numRows: the number of rows in the array + /// @param numCols: the number of cols in the array + /// + NdArrayConstColumnIterator(pointer ptr, SizeType numRows, SizeType numCols) noexcept : + ptr_(ptr), + currPtr_(ptr), + numRows_(static_cast(numRows)), + numCols_(static_cast(numCols)), + size_(numRows_ * numCols_) + { + } + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return *currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + return *this += 1; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + ++*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + return *this -= 1; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + --*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + currPtr_ = colIdx2Ptr(ptr2ColIdx(currPtr_) + offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + return *this += -offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param rhs + /// @return difference_type + /// + difference_type operator-(const self_type& rhs) const noexcept + { + return ptr2ColIdx(currPtr_) - ptr2ColIdx(rhs.currPtr_); + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return *(*this + offset); + } + + //============================================================================ + // Method Description: + /// Iterator equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const self_type& rhs) const noexcept + { + return currPtr_ == rhs.currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator not-equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const self_type& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Iterator less than operator + /// + /// @param rhs + /// @return bool + /// + bool operator<(const self_type& rhs) const noexcept + { + return *this - rhs < 0; + } + + //============================================================================ + // Method Description: + /// Iterator greater than operator + /// + /// @param rhs + /// @return bool + /// + bool operator>(const self_type& rhs) const noexcept + { + return *this - rhs > 0; + } + + //============================================================================ + // Method Description: + /// Iterator less than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator<=(const self_type& rhs) const noexcept + { + return !(rhs < *this); + } + + //============================================================================ + // Method Description: + /// Iterator greater than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator>=(const self_type& rhs) const noexcept + { + return !(*this < rhs); + } + + private: + pointer ptr_{}; + pointer currPtr_{}; + difference_type numRows_{ 0 }; + difference_type numCols_{ 0 }; + difference_type size_{ 0 }; + + //============================================================================ + // Method Description: + /// Converts a pointer to column order index + /// + /// @param ptr + /// @return difference_type + /// + difference_type ptr2ColIdx(pointer ptr) const noexcept + { + if (ptr == nullptr) + { + return size_; + } + + const auto rowIdx = ptr - ptr_; + if (rowIdx >= size_) + { + return size_; + } + + const auto row = rowIdx / numCols_; + const auto col = rowIdx % numCols_; + return row + col * numRows_; + } + + //============================================================================ + // Method Description: + /// Converts column order index to a pointer + /// + /// @param colIdx + /// @return pointer + /// + pointer colIdx2Ptr(difference_type colIdx) const noexcept + { + if (colIdx >= size_) + { + return nullptr; + } + + const auto row = colIdx % numRows_; + const auto col = colIdx / numRows_; + const auto rowIdx = col + row * numCols_; + return ptr_ + rowIdx; + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayConstColumnIterator operator+( + typename NdArrayConstColumnIterator::difference_type offset, + NdArrayConstColumnIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom column iterator for NdArray + template + class NdArrayColumnIterator : public NdArrayConstColumnIterator + { + private: + using MyBase = NdArrayConstColumnIterator; + using self_type = NdArrayColumnIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using size_type = SizeType; + using pointer = PointerType; + using reference = value_type&; + using difference_type = DifferenceType; + + using MyBase::MyBase; + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return const_cast(MyBase::operator*()); + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return const_cast(MyBase::operator->()); + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + MyBase::operator++(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + MyBase:: operator++(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + MyBase::operator--(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + MyBase:: operator--(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + MyBase::operator+=(offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + MyBase::operator-=(offset); + return *this; + } + + using MyBase::operator-; + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return const_cast(MyBase::operator[](offset)); + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayColumnIterator + operator+(typename NdArrayColumnIterator::difference_type offset, + NdArrayColumnIterator next) noexcept + { + return next += offset; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp new file mode 100644 index 0000000000000000000000000000000000000000..145673e63f975299219f22a72c4ade1fdc7ab2fa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp @@ -0,0 +1,2022 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Operators for the NdArray class +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Functions/complex.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" +#include "NumCpp/NdArray/NdArrayCore.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/essentiallyEqualComplex.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator+=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::plus()); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator+=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 + val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator+=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value += rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator+=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value += rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::plus()); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 + val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray>& lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(NdArray lhs, dtype rhs) + { + lhs += rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(dtype lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value + rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const std::complex& lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(NdArray> lhs, dtype rhs) + { + lhs += rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(dtype lhs, const NdArray>& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator-=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::minus()); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator-=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 - val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator-=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value -= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator-=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value -= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::minus()); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 - val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 - val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(NdArray lhs, dtype rhs) + { + lhs -= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(dtype lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [lhs](dtype value) -> dtype { return lhs - value; }; + + NdArray returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value - rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const std::complex& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](dtype value) -> std::complex { return lhs - value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(NdArray> lhs, dtype rhs) + { + lhs -= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(dtype lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](std::complex value) -> std::complex { return lhs - value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Negative Operator + /// + /// @return NdArray + /// + template + NdArray operator-(const NdArray& inArray) + { + const auto function = [](dtype value) -> dtype { return -value; }; + + auto returnArray = NdArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator*=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::multiplies()); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator*=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 * val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator*=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value *= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator*=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value *= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::multiplies()); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 * val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray>& lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(NdArray lhs, dtype rhs) + { + lhs *= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(dtype lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value * rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const std::complex& lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(NdArray> lhs, dtype rhs) + { + lhs *= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(dtype lhs, const NdArray>& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator/=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::divides()); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator/=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 / val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator/=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value /= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator/=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value /= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::divides()); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 / val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 / val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(NdArray lhs, dtype rhs) + { + lhs /= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(dtype lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [lhs](dtype value) -> dtype { return lhs / value; }; + + NdArray returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value / rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const std::complex& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](dtype value) -> std::complex { return lhs / value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(NdArray> lhs, dtype rhs) + { + lhs /= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(dtype lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](const std::complex& value) -> std::complex { return lhs / value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Modulus the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray& operator%=(NdArray& lhs, const NdArray& rhs) + { + if constexpr (std::is_integral_v) + { + return broadcast::broadcaster(lhs, rhs, std::modulus()); + } + else + { + const auto function = [](const dtype value1, const dtype value2) -> dtype + { return std::fmod(value1, value2); }; + return broadcast::broadcaster(lhs, rhs, function); + } + } + + //============================================================================ + // Method Description: + /// Modulus the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray& operator%=(NdArray& lhs, dtype rhs) + { + if constexpr (std::is_integral_v) + { + const auto function = [rhs](dtype& value) -> dtype { return value %= rhs; }; + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + } + else + { + const auto function = [rhs](dtype& value) -> void { value = std::fmod(value, rhs); }; + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + } + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the modulus of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray operator%(const NdArray& lhs, const NdArray& rhs) + { + if constexpr (std::is_integral_v) + { + return broadcast::broadcaster(lhs, rhs, std::modulus()); + } + else + { + const auto function = [](dtype value1, dtype value2) -> dtype { return std::fmod(value1, value2); }; + return broadcast::broadcaster(lhs, rhs, function); + } + } + + //============================================================================ + // Method Description: + /// Modulus of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator%(NdArray lhs, dtype rhs) + { + lhs %= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Modulus of the scalar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template, int> = 0> + NdArray operator%(dtype lhs, const NdArray& rhs) + { + NdArray returnArray(rhs.shape()); + stl_algorithms::transform(rhs.begin(), + rhs.end(), + returnArray.begin(), + [lhs](dtype value) -> dtype { return lhs % value; }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Modulus of the scalar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template, int> = 0> + NdArray operator%(dtype lhs, const NdArray& rhs) + { + NdArray returnArray(rhs.shape()); + stl_algorithms::transform(rhs.begin(), + rhs.end(), + returnArray.begin(), + [lhs](dtype value) -> dtype { return std::fmod(lhs, value); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitwise or the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator|=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_or()); + } + + //============================================================================ + // Method Description: + /// Bitwise or the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator|=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value |= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_or()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(NdArray lhs, dtype rhs) + { + lhs |= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(dtype lhs, const NdArray& rhs) + { + return rhs | lhs; + } + + //============================================================================ + // Method Description: + /// Bitwise and the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator&=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_and()); + } + + //============================================================================ + // Method Description: + /// Bitwise and the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator&=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value &= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_and()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(NdArray lhs, dtype rhs) + { + lhs &= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(dtype lhs, const NdArray& rhs) + { + return rhs & lhs; + } + + //============================================================================ + // Method Description: + /// Bitwise xor the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator^=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_xor()); + } + + //============================================================================ + // Method Description: + /// Bitwise xor the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator^=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value ^= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_xor()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(NdArray lhs, dtype rhs) + { + lhs ^= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(dtype lhs, const NdArray& rhs) + { + return rhs ^ lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise not of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray operator~(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [](dtype value) -> dtype { return ~value; }; + + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the and of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype value1, dtype value2) -> bool + { return !utils::essentiallyEqual(value1, dtype{ 0 }) && !utils::essentiallyEqual(value2, dtype{ 0 }); }; + + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Takes the and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(const NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [rhs](dtype value) -> bool { return value && rhs; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(dtype lhs, const NdArray& rhs) + { + return rhs && lhs; + } + + //============================================================================ + // Method Description: + /// Takes the or of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype value1, dtype value2) -> bool + { return !utils::essentiallyEqual(value1, dtype{ 0 }) || !utils::essentiallyEqual(value2, dtype{ 0 }); }; + + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Takes the or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(const NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [rhs](dtype value) -> bool { return value || rhs; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(dtype lhs, const NdArray& rhs) + { + return rhs || lhs; + } + + //============================================================================ + // Method Description: + /// Takes the not of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray operator!(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [](dtype value) -> dtype { return !value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator==(const NdArray& lhs, const NdArray& rhs) + { + const auto equalTo = [](dtype lhs_, dtype rhs_) noexcept -> bool + { return utils::essentiallyEqual(lhs_, rhs_); }; + + return broadcast::broadcaster(lhs, rhs, equalTo); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator==(const NdArray& lhs, dtype inValue) + { + NdArray returnArray(lhs.shape()); + + const auto equalTo = [inValue](dtype value) noexcept -> bool + { return utils::essentiallyEqual(inValue, value); }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), equalTo); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator==(dtype inValue, const NdArray& inArray) + { + return inArray == inValue; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator!=(const NdArray& lhs, const NdArray& rhs) + { + const auto notEqualTo = [](dtype lhs_, dtype rhs_) noexcept -> bool + { return !utils::essentiallyEqual(lhs_, rhs_); }; + + return broadcast::broadcaster(lhs, rhs, notEqualTo); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator!=(const NdArray& lhs, dtype inValue) + { + NdArray returnArray(lhs.shape()); + + const auto notEqualTo = [inValue](dtype value) noexcept -> bool + { return !utils::essentiallyEqual(inValue, value); }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), notEqualTo); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator!=(dtype inValue, const NdArray& inArray) + { + return inArray != inValue; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator<(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ < rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator<(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value < inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator<(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue < value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator>(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ > rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator>(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value > inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator>(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue > value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator<=(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ <= rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator<=(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value <= inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator<=(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue <= value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator>=(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ >= rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator>=(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value >= inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator>=(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue >= value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitshifts left the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray& operator<<=(NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [inNumBits](dtype& value) -> void { value <<= inNumBits; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Bitshifts left the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray operator<<(const NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(lhs); + returnArray <<= inNumBits; + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitshifts right the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray& operator>>=(NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [inNumBits](dtype& value) -> void { value >>= inNumBits; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Bitshifts right the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray operator>>(const NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(lhs); + returnArray >>= inNumBits; + return returnArray; + } + + //============================================================================ + // Method Description: + /// prefix incraments the elements of an array + /// + /// @return NdArray + /// + template + NdArray& operator++(NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype& value) -> void { ++value; }; + + stl_algorithms::for_each(rhs.begin(), rhs.end(), function); + + return rhs; + } + + //============================================================================ + // Method Description: + /// postfix increments the elements of an array + /// + /// @param lhs + /// @return NdArray + /// + template + NdArray operator++(NdArray& lhs, int) + { + auto copy = NdArray(lhs); + ++lhs; + return copy; + } + + //============================================================================ + // Method Description: + /// prefix decrements the elements of an array + /// + /// @return NdArray + /// + template + NdArray& operator--(NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype& value) -> void { --value; }; + + stl_algorithms::for_each(rhs.begin(), rhs.end(), function); + + return rhs; + } + + //============================================================================ + // Method Description: + /// postfix decrements the elements of an array + /// + /// @param lhs + /// @return NdArray + /// + template + NdArray operator--(NdArray& lhs, int) + { + auto copy = NdArray(lhs); + --lhs; + return copy; + } + + //============================================================================ + // Method Description: + /// io operator for the NdArray class + /// + /// @param inOStream + /// @param inArray + /// @return std::ostream + /// + template + std::ostream& operator<<(std::ostream& inOStream, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + inOStream << inArray.str(); + return inOStream; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3c407e1412f864f83e194c218efd03c7ba6e7699 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial.hpp @@ -0,0 +1,37 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Polynomial/Poly1d.hpp" +#include "NumCpp/Polynomial/chebyshev_t.hpp" +#include "NumCpp/Polynomial/chebyshev_u.hpp" +#include "NumCpp/Polynomial/hermite.hpp" +#include "NumCpp/Polynomial/laguerre.hpp" +#include "NumCpp/Polynomial/legendre_p.hpp" +#include "NumCpp/Polynomial/legendre_q.hpp" +#include "NumCpp/Polynomial/spherical_harmonic.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/Poly1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/Poly1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..df1c18a88a1204a188d53adda0d16c659a99b7cc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/Poly1d.hpp @@ -0,0 +1,645 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Class for dealing with 1D polynomials +/// +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc::polynomial +{ + //================================================================================ + /// A one-dimensional polynomial class. + /// A convenience class, used to encapsulate "natural" + /// operations on polynomials + template + class Poly1d + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //============================================================================ + // Method Description: + /// Default Constructor (not very usefull, but needed for other + /// containers. + /// + Poly1d() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inValues: (polynomial coefficients in ascending order of power if second input is false, + /// polynomial roots if second input is true) + /// @param isRoots + /// + Poly1d(const NdArray& inValues, bool isRoots = false) + { + if (inValues.size() > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR("can only make a polynomial of order " + + utils::num2str(DtypeInfo::max())); + } + + if (isRoots) + { + coefficients_.push_back(1); + for (auto value : inValues) + { + NdArray coeffs = { -(value), static_cast(1) }; + *this *= Poly1d(coeffs, !isRoots); + } + } + else + { + coefficients_.resize(inValues.size()); + stl_algorithms::copy(inValues.begin(), inValues.end(), coefficients_.begin()); + } + } + + //============================================================================ + // Method Description: + /// Returns the area under the curve between the two bounds + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return double + /// + [[nodiscard]] double area(double a, double b) const + { + if (a > b) + { + std::swap(a, b); + } + + auto polyIntegral = integ(); + return polyIntegral(b) - polyIntegral(a); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the polynomial of the new type + /// + /// @return Poly1d + /// + template + Poly1d astype() const + { + auto newCoefficients = NdArray(1, static_cast(coefficients_.size())); + + const auto function = [](dtype value) -> dtypeOut { return static_cast(value); }; + + stl_algorithms::transform(coefficients_.begin(), coefficients_.end(), newCoefficients.begin(), function); + + return Poly1d(newCoefficients); + } + + //============================================================================ + // Method Description: + /// Returns the Poly1d coefficients + /// + /// @return NdArray + /// + [[nodiscard]] NdArray coefficients() const + { + auto coefficientsCopy = coefficients_; + return NdArray(coefficientsCopy); + } + + //============================================================================ + // Method Description: + /// Takes the derivative of the polynomial + /// + /// @return Poly1d + [[nodiscard]] Poly1d deriv() const + { + const auto numCoefficients = static_cast(coefficients_.size()); + if (numCoefficients == 0) + { + return {}; + } + if (numCoefficients == 1) + { + return Poly1d({ 0 }); + } + + NdArray derivativeCofficients(1, numCoefficients - 1); + + uint32 counter = 0; + for (uint32 i = 1; i < numCoefficients; ++i) + { + derivativeCofficients[counter++] = coefficients_[i] * i; + } + + return Poly1d(derivativeCofficients); + } + + //============================================================================ + // Method Description: + /// Evaluates the Poly1D object for the input value + /// + /// @param xValue + /// @return predicted yValue + /// + dtype eval(dtype xValue) const noexcept + { + return operator()(xValue); + } + + //============================================================================ + // Method Description: + /// Evaluates the Poly1D object for the input value + /// + /// @param xValues + /// @return predicted yValues + /// + NdArray eval(const NdArray& xValues) const noexcept + { + return operator()(xValues); + } + + //============================================================================ + // Method Description: + /// Polynomial linear least squares regression: Ax = b + /// + /// @param xValues: the x measurements [1, n] or [n, 1] array + /// @param yValues: the y measurements [n, 1] array + /// @param polyOrder: the order of the poly nomial to fit + /// @return Poly1d + static Poly1d fit(const NdArray& xValues, const NdArray& yValues, uint8 polyOrder) + { + const auto numMeasurements = xValues.size(); + + if (yValues.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size."); + } + + if (!xValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array."); + } + + if (!yValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array."); + } + + NdArray a(numMeasurements, polyOrder + 1); + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto xDouble = static_cast(xValues[measIdx]); + for (uint8 order = 0; order < a.numCols(); ++order) + { + a(measIdx, order) = utils::power(xDouble, order); + } + } + + NdArray aInv; + if (a.issquare()) + { + aInv = linalg::inv(a); + } + else + { + // psuedo-inverse + auto aT = a.transpose(); + auto aTaInv = linalg::inv(aT.dot(a)); + aInv = aTaInv.dot(aT); + } + + auto x = aInv.dot(yValues.template astype()); + return Poly1d(x); + } + + //============================================================================ + // Method Description: + /// Polynomial linear least squares regression: Ax = b + /// + /// @param xValues: the x measurements [1, n] or [n, 1] array + /// @param yValues: the y measurements [n, 1] array + /// @param weights: the measurement weights [1, n] or [n, 1] array + /// @param polyOrder: the order of the poly nomial to fit + /// @return Poly1d + static Poly1d fit(const NdArray& xValues, + const NdArray& yValues, + const NdArray& weights, + uint8 polyOrder) + { + const auto numMeasurements = xValues.size(); + + if (yValues.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size."); + } + + if (weights.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and weights arrays must be of equal size."); + } + + if (!xValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array."); + } + + if (!yValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array."); + } + + if (!weights.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input weights must be a flattened [1, n] or [n, 1] array."); + } + + NdArray a(numMeasurements, polyOrder + 1); + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto xDouble = static_cast(xValues[measIdx]); + for (uint8 order = 0; order < a.numCols(); ++order) + { + a(measIdx, order) = utils::power(xDouble, order); + } + } + + NdArray aWeighted(a.shape()); + NdArray yWeighted(yValues.shape()); + + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto weight = static_cast(weights[measIdx]); + + yWeighted[measIdx] = yValues[measIdx] * weight; + for (uint8 order = 0; order < a.numCols(); ++order) + { + aWeighted(measIdx, order) = a(measIdx, order) * weight; + } + } + + NdArray aInv; + if (aWeighted.issquare()) + { + aInv = linalg::inv(aWeighted); + } + else + { + // psuedo-inverse + auto aT = a.transpose(); + auto aTaInv = linalg::inv(aT.dot(aWeighted)); + aInv = aTaInv.dot(aT); + } + + auto x = aInv.dot(yWeighted); + return Poly1d(x); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Calculates the integral of the polynomial + /// + /// @return Poly1d + [[nodiscard]] Poly1d integ() const + { + const auto numCoefficients = static_cast(coefficients_.size()); + if (numCoefficients == 0) + { + return {}; + } + + NdArray integralCofficients(1, numCoefficients + 1); + integralCofficients[0] = 0.; + + for (uint32 i = 0; i < numCoefficients; ++i) + { + integralCofficients[i + 1] = static_cast(coefficients_[i]) / static_cast(i + 1); + } + + return Poly1d(integralCofficients); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the order of the Poly1d + /// + /// @return NdArray + /// + [[nodiscard]] uint32 order() const noexcept + { + return static_cast(coefficients_.size() - 1); + } + + //============================================================================ + // Method Description: + /// Prints the string representation of the Poly1d object + /// to the console + /// + void print() const + { + std::cout << *this << std::endl; + } + + //============================================================================ + // Method Description: + /// Converts the polynomial to a string representation + /// + /// @return Poly1d + /// + [[nodiscard]] std::string str() const + { + const auto numCoeffients = static_cast(coefficients_.size()); + + std::string repr = "Poly1d<"; + uint32 power = 0; + for (auto& coefficient : coefficients_) + { + if (utils::essentiallyEqual(coefficient, static_cast(0))) + { + ++power; + continue; + } + + repr += utils::num2str(coefficient); + + if (power > 1) + { + repr += "x^" + utils::num2str(power); + } + else if (power == 1) + { + repr += "x"; + } + + ++power; + + if (power < numCoeffients) + { + repr += " + "; + } + } + + return repr + ">"; + } + + //============================================================================ + // Method Description: + /// Evaluates the Poly1D object for the input value + /// + /// @param inValue + /// @return dtype scalar + /// + dtype operator()(dtype inValue) const noexcept + { + uint8 power = 0; + return std::accumulate(coefficients_.begin(), + coefficients_.end(), + dtype{ 0 }, + [&power, inValue](dtype polyValue, const auto& coefficient) noexcept -> dtype + { return polyValue + coefficient * utils::power(inValue, power++); }); + } + + //============================================================================ + // Method Description: + /// Evaluates the Poly1D object for the input value + /// + /// @param xValues + /// @return predicted yValues + /// + NdArray operator()(const NdArray& xValues) const noexcept + { + NdArray returnArray(xValues.shape()); + + stl_algorithms::transform(xValues.begin(), + xValues.end(), + returnArray.begin(), + [this](const auto xValue) { return this->operator()(xValue); }); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Adds the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator+(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) += inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Adds the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator+=(const Poly1d& inOtherPoly) + { + if (this->coefficients_.size() < inOtherPoly.coefficients_.size()) + { + for (size_t i = 0; i < coefficients_.size(); ++i) + { + coefficients_[i] += inOtherPoly.coefficients_[i]; + } + for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_.push_back(inOtherPoly.coefficients_[i]); + } + } + else + { + for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_[i] += inOtherPoly.coefficients_[i]; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator-(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) -= inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Subtracts the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator-=(const Poly1d& inOtherPoly) + { + if (this->coefficients_.size() < inOtherPoly.coefficients_.size()) + { + for (size_t i = 0; i < coefficients_.size(); ++i) + { + coefficients_[i] -= inOtherPoly.coefficients_[i]; + } + for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_.push_back(-inOtherPoly.coefficients_[i]); + } + } + else + { + for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_[i] -= inOtherPoly.coefficients_[i]; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Multiplies the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator*(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) *= inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Multiplies the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator*=(const Poly1d& inOtherPoly) + { + const uint32 finalCoefficientsSize = order() + inOtherPoly.order() + 1; + std::vector coeffsA(finalCoefficientsSize, 0); + std::vector coeffsB(finalCoefficientsSize, 0); + stl_algorithms::copy(coefficients_.begin(), coefficients_.end(), coeffsA.begin()); + stl_algorithms::copy(inOtherPoly.coefficients_.cbegin(), inOtherPoly.coefficients_.cend(), coeffsB.begin()); + + // now multiply out the coefficients + std::vector finalCoefficients(finalCoefficientsSize, 0); + for (uint32 i = 0; i < finalCoefficientsSize; ++i) + { + for (uint32 k = 0; k <= i; ++k) + { + finalCoefficients[i] += coeffsA[k] * coeffsB[i - k]; + } + } + + this->coefficients_ = finalCoefficients; + return *this; + } + + //============================================================================ + // Method Description: + /// Raise the Poly1d to an integer power + /// + /// @param inPower + /// @return Poly1d + /// + Poly1d operator^(uint32 inPower) const + { + return Poly1d(*this) ^= inPower; + } + + //============================================================================ + // Method Description: + /// Raise the Poly1d to an integer power + /// + /// @param inPower + /// @return Poly1d + /// + Poly1d& operator^=(uint32 inPower) + { + if (inPower == 0) + { + coefficients_.clear(); + coefficients_.push_back(1); + return *this; + } + if (inPower == 1) + { + return *this; + } + + auto thisPoly(*this); + for (uint32 power = 1; power < inPower; ++power) + { + *this *= thisPoly; + } + + return *this; + } + + //============================================================================ + // Method Description: + /// io operator for the Poly1d class + /// + /// @param inOStream + /// @param inPoly + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Poly1d& inPoly) + { + inOStream << inPoly.str() << std::endl; + return inOStream; + } + + private: + std::vector coefficients_{}; + }; +} // namespace nc::polynomial diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d79f6ce5c72714a308c08c83197191e51268b5df --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/chebyshev.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param x: the input value + /// @return double + /// + template + double chebyshev_t(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::chebyshev_t(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray chebyshev_t(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return chebyshev_t(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp new file mode 100644 index 0000000000000000000000000000000000000000..db34aa0a13ba752f276ed47cda0a102770f0a7e7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/chebyshev.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param x: the input value + /// @return double + /// + template + double chebyshev_u(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::chebyshev_u(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray chebyshev_u(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return chebyshev_u(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/hermite.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/hermite.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f46423d9fdaa92dca54988c48835ea86ae4f5ce6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/hermite.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/hermite.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Hermite Polynomial + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the hermite polynomial + /// @param x: the input value + /// @return double + /// + template + double hermite(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::hermite(n, static_cast(x)); +#else + return boost::math::hermite(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Hermite Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the hermite polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray hermite(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return hermite(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/laguerre.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/laguerre.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cb0334013109bb1d85af33146bbcae50423eb537 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/laguerre.hpp @@ -0,0 +1,135 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/laguerre.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param x: the input value + /// @return double + /// + template + double laguerre(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::laguerre(n, static_cast(x)); +#else + return boost::math::laguerre(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Associated Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param m: the degree of the legendre polynomial + /// @param x: the input value + /// @return double + /// + template + double laguerre(uint32 n, uint32 m, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::assoc_laguerre(m, n, static_cast(x)); +#else + return boost::math::laguerre(m, n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray laguerre(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return laguerre(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Associated Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param m: the degree of the legendre polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray laguerre(uint32 n, uint32 m, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n, m](dtype x) -> double { return laguerre(n, m, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_p.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_p.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ab609a6bcbec6d02f257bf53d45a6aafb83ff670 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_p.hpp @@ -0,0 +1,176 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/legendre.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the degree of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_p(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + +#ifdef __cpp_lib_math_special_functions + return std::legendre(n, static_cast(x)); +#else + return boost::math::legendre_p(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Associated Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param m: the order of the legendre polynomial + /// @param n: the degree of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_p(uint32 m, uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + +#ifdef __cpp_lib_math_special_functions + + auto value = std::assoc_legendre(n, m, static_cast(x)); + +#ifdef __GNUC__ +#if __GNUC__ != 7 && __GNUC__ != 8 + + // gcc std::assoc_legendre is not standard compliant + value *= n % 2 == 0 ? 1 : -1; + +#endif // #if __GNUC__ != 7 && __GNUC__ != 8 +#endif // #ifdef __GNUC__ + +#ifdef __clang__ +#if __clang_major__ != 7 && __clang_major__ != 8 + + // clang uses gcc headers where std::assoc_legendre is not standard compliant + value *= n % 2 == 0 ? 1 : -1; + +#endif // #if __clang_major__ != 6 && __clang_major__ != 7 && __clang_major__ != 8 +#endif // #ifdef __clang__ + +#ifdef _MSC_VER + + value *= n % 2 == 0 ? 1 : -1; + +#endif // #ifdef _MSC_VER + + return value; + +#else // #ifdef __cpp_lib_math_special_functions + + return boost::math::legendre_p(n, m, static_cast(x)); + +#endif // #ifdef __cpp_lib_math_special_functions + } + + //============================================================================ + // Method Description: + /// Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the degree of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_p(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return legendre_p(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Associated Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param m: the order of the legendre polynomial + /// @param n: the degree of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_p(uint32 m, uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [m, n](dtype x) -> double { return legendre_p(m, n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_q.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_q.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d62f5ed6ca4eb0bf4c8f89aac2c3676bf1f6c379 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/legendre_q.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/legendre.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Legendre Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_q(int32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + + return boost::math::legendre_q(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Legendre Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_q(int32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return legendre_q(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp new file mode 100644 index 0000000000000000000000000000000000000000..25f0b3f674bc46c5fa1cd0080417f155ee22f9cc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/spherical_harmonic.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Returns the value of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + std::complex spherical_harmonic(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic(m, n, static_cast(phi), static_cast(theta)); + } + + //============================================================================ + // Method Description: + /// Returns the real part of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + double spherical_harmonic_r(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic_r(m, n, static_cast(phi), static_cast(theta)); + } + + //============================================================================ + // Method Description: + /// Returns the imaginary part of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + double spherical_harmonic_i(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic_i(m, n, static_cast(phi), static_cast(theta)); + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6c4e0441d5a35d7f7bb177ec08fa282421b6a553 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python +/// +#pragma once + +#include "NumCpp/PythonInterface/BoostInterface.hpp" +#include "NumCpp/PythonInterface/PybindInterface.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b15f844ea05f2ca48f1fdae3ec376d4cc1a9535d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp @@ -0,0 +1,169 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python with boost interface +/// +#pragma once + +#if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) + +#include +#include + +#include "boost/python.hpp" +#include "boost/python/numpy.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp" + +namespace nc +{ + namespace boostPythonInterface + { + //============================================================================ + /// Converts from a boost ndarray to a NumCpp NdArray + /// + /// @param inArray + /// + /// @return NdArray + /// + template + inline NdArray boost2Nc(const boost::python::numpy::ndarray& inArray) + { + BoostNdarrayHelper helper(inArray); + if (helper.numDimensions() > 2) + { + THROW_RUNTIME_ERROR("Can only convert 1 and 2 dimensional arrays."); + } + + Shape arrayShape; + if (helper.numDimensions() == 1) + { + arrayShape.rows = 1; + arrayShape.cols = static_cast(helper.shape().front()); + + NdArray returnArray(arrayShape); + for (uint32 i = 0; i < arrayShape.size(); ++i) + { + returnArray[i] = helper(i); + } + + return returnArray; + } + + arrayShape.rows = static_cast(helper.shape().front()); + arrayShape.cols = static_cast(helper.shape()[1]); + + NdArray returnArray(arrayShape); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + for (uint32 col = 0; col < arrayShape.cols; ++col) + { + returnArray(row, col) = helper(row, col); + } + } + + return returnArray; + } + + //============================================================================ + /// Converts from a NumCpp NdArray to a boost ndarray + /// + /// @param inArray + /// + /// @return ndarray + /// + template + inline boost::python::numpy::ndarray nc2Boost(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + boost::python::tuple shape = boost::python::make_tuple(inShape.rows, inShape.cols); + BoostNdarrayHelper newNdArrayHelper(shape); + + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 0; col < inShape.cols; ++col) + { + newNdArrayHelper(row, col) = inArray(row, col); + } + } + return newNdArrayHelper.getArray(); + } + + //============================================================================ + /// converts a boost python list to a std::vector + /// + /// @param inList + /// + /// @return std::vector + /// + template + inline std::vector list2vector(const boost::python::list& inList) + { + return std::vector(boost::python::stl_input_iterator(inList), boost::python::stl_input_iterator()); + } + + //============================================================================ + /// converts a std::vector to a boost python list + /// + /// @param inVector + /// + /// @return boost::python::list + /// + template + inline boost::python::list vector2list(std::vector& inVector) + { + boost::python::list outList; + for (auto& value : inVector) + { + outList.append(value); + } + + return outList; + } + + //============================================================================ + /// converts a std::map in to a boost python dictionary + /// + /// @param inMap + /// + /// @return boost::python::dict + /// + template + inline boost::python::dict map2dict(const std::map& inMap) + { + boost::python::dict dictionary; + for (auto& keyValue : inMap) + { + dictionary[keyValue.first] = keyValue.second; + } + return dictionary; + } + } // namespace boostPythonInterface +} // namespace nc + +#endif // #if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp new file mode 100644 index 0000000000000000000000000000000000000000..1430411b891f65cb1f689b4bbc97a0aabd738617 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp @@ -0,0 +1,339 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A wrapper class for interacting with the boost numpy arrays +/// +#pragma once + +#if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) + +#include +#include +#include +#include +#include + +#include "boost/python.hpp" +#include "boost/python/numpy.hpp" + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + namespace boostPythonInterface + { + //================================================================================ + /// Helper class for ndarray + template + class BoostNdarrayHelper + { + public: + //================================================================================ + /// C or Fortran ordering from python + enum class Order + { + F, + C + }; + + //============================================================================ + /// Constructor + /// + /// @param inArray: ndarray + /// + explicit BoostNdarrayHelper(const boost::python::numpy::ndarray& inArray) : + theArray_(inArray.astype(boost::python::numpy::dtype::get_builtin())), + numDimensions_(static_cast(inArray.get_nd())), + shape_(numDimensions_), + strides_(numDimensions_), + order_(Order::C) + + { + Py_intptr_t const* shapePtr = inArray.get_shape(); + for (uint8 i = 0; i < numDimensions_; ++i) + { + strides_[i] = static_cast(theArray_.strides(i)); + shape_[i] = shapePtr[i]; + } + + if (numDimensions_ > 1 && inArray.strides(0) < inArray.strides(1)) + { + order_ = Order::F; + } + } + + //============================================================================ + /// Constructor + /// + /// @param inShape + /// + explicit BoostNdarrayHelper(boost::python::tuple inShape) : + theArray_(boost::python::numpy::zeros(inShape, boost::python::numpy::dtype::get_builtin())), + numDimensions_(static_cast(theArray_.get_nd())), + shape_(numDimensions_), + strides_(numDimensions_), + order_(Order::C) + { + Py_intptr_t const* shapePtr = theArray_.get_shape(); + for (uint8 i = 0; i < numDimensions_; ++i) + { + strides_[i] = static_cast(theArray_.strides(i)); + shape_[i] = shapePtr[i]; + } + + if (numDimensions_ > 1 && theArray_.strides(0) < theArray_.strides(1)) + { + order_ = Order::F; + } + } + + //============================================================================ + /// Returns the internaly held ndarray + /// + /// @return reference to the held ndarray + /// + const boost::python::numpy::ndarray& getArray() noexcept + { + return theArray_; + } + + //============================================================================ + /// Returns the internaly held ndarray as a numpy matrix + /// + /// @return matrix + /// + boost::python::numpy::matrix getArrayAsMatrix() + { + return boost::python::numpy::matrix(theArray_); + } + + //============================================================================ + /// Returns the number of dimensions of the array + /// + /// @return num dimensions + /// + uint8 numDimensions() noexcept + { + return numDimensions_; + } + + //============================================================================ + /// Returns the shape of the array + /// + /// @return vector + /// + const std::vector& shape() noexcept + { + return shape_; + } + + //============================================================================ + /// Returns the size of the array + /// + /// @return size + /// + uint32 size() + { + uint32 theSize = 1; + for (auto dimSize : shape_) + { + theSize *= static_cast(dimSize); + } + return theSize; + } + + //============================================================================ + /// Returns the strides of the array + /// + /// @return vector + /// + const std::vector& strides() + { + return strides_; + } + + //============================================================================ + /// Returns the memory order of the array (C or Fortran) + /// + /// @return Order + /// + Order order() + { + return order_; + } + + //============================================================================ + /// Returns if the shapes of the two array helpers are equal + /// + /// @param otherNdarrayHelper + /// + /// @return boolean + /// + bool shapeEqual(BoostNdarrayHelper& otherNdarrayHelper) + { + if (shape_.size() != otherNdarrayHelper.shape_.size()) + { + return false; + } + + return stl_algorithms::equal(shape_.begin(), shape_.end(), otherNdarrayHelper.shape_.begin()); + } + + //============================================================================ + /// 1D access operator + /// + /// @param index + /// + /// @return dtype + /// + dtype& operator()(uint32 index) + { + checkIndices1D(index); + + return *reinterpret_cast(theArray_.get_data() + strides_.front() * index); + } + + //============================================================================ + /// 2D access operator + /// + /// @param index1 + /// @param index2 + /// + /// @return dtype + /// + dtype& operator()(uint32 index1, uint32 index2) + { + checkIndices2D(index1, index2); + + return *reinterpret_cast(theArray_.get_data() + strides_.front() * index1 + + strides_[1] * index2); + } + + //============================================================================ + /// Prints a 1D array + /// + void printArray1D() + { + printf("array = \n"); + if (numDimensions_ != 1) + { + std::cout << "printArray1D can only be used on a 1D array." << std::endl; + return; + } + + for (int32 i = 0; i < shape_.front(); ++i) + { + printf("\t%f\n", operator()(i)); + } + } + + //============================================================================ + /// Prints a 2D array + /// + void printArray2D() + { + printf("array = \n"); + if (numDimensions_ != 2) + { + std::cout << "printArray2D can only be used on a 2D array." << std::endl; + return; + } + + for (int32 index1 = 0; index1 < shape_.front(); ++index1) + { + for (int32 index2 = 0; index2 < shape_.back(); ++index2) + { + printf("\t%f", operator()(index1, index2)); + } + printf('\n'); + } + } + + private: + //====================================Attributes============================== + boost::python::numpy::ndarray theArray_; + uint8 numDimensions_; + std::vector shape_; + std::vector strides_; + Order order_; + + //============================================================================ + /// Generic check of input indices + /// + /// @param indices + /// + void checkIndicesGeneric(boost::python::tuple indices) + { + if (boost::python::len(indices) != numDimensions_) + { + std::string errStr = + "Error: BoostNdarrayHelper::checkIndicesGeneric: Array has " + utils::num2str(numDimensions_); + errStr += " dimensions, you asked for " + + utils::num2str(static_cast(boost::python::len(indices))) + "!"; + PyErr_SetString(PyExc_RuntimeError, errStr.c_str()); + } + + for (int i = 0; i < numDimensions_; ++i) + { + int index = boost::python::extract(indices[i]); + if (index > shape_[i]) + { + std::string errStr = + "Error: BoostNdarrayHelper::checkIndicesGeneric: Input index [" + utils::num2str(index); + errStr += "] is larger than the size of the array [" + utils::num2str(shape_[i]) + "]."; + PyErr_SetString(PyExc_RuntimeError, errStr.c_str()); + } + } + } + + //============================================================================ + /// Checks 1D input indices + /// + /// @param index + /// + void checkIndices1D(uint32 index) + { + boost::python::tuple indices = boost::python::make_tuple(index); + checkIndicesGeneric(indices); + } + + //============================================================================ + /// Checks 2D input indices + /// + /// @param index1 + /// @param index2 + /// + void checkIndices2D(uint32 index1, uint32 index2) + { + boost::python::tuple indices = boost::python::make_tuple(index1, index2); + checkIndicesGeneric(indices); + } + }; + } // namespace boostPythonInterface +} // namespace nc + +#endif // #if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp new file mode 100644 index 0000000000000000000000000000000000000000..940fc789257722763e4e9fb0e7bfd523f7550e3c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp @@ -0,0 +1,201 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python with pybind11 interface +/// +#pragma once + +#ifdef NUMCPP_INCLUDE_PYBIND_PYTHON_INTERFACE + +#include "pybind11/numpy.h" +#include "pybind11/pybind11.h" + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::pybindInterface +{ + /// Enum for the pybind array return policy + enum class ReturnPolicy + { + COPY, + REFERENCE, + TAKE_OWNERSHIP + }; + + static const std::map returnPolicyStringMap = { { ReturnPolicy::COPY, "COPY" }, + { ReturnPolicy::REFERENCE, "REFERENCE" }, + { ReturnPolicy::TAKE_OWNERSHIP, + "TAKE_OWNERSHIP" } }; + + template + using pbArray = pybind11::array_t; + using pbArrayGeneric = pybind11::array; + + //============================================================================ + /// converts a numpy array to a numcpp NdArray using pybind bindings + /// Python will still own the underlying data. + /// + /// @param numpyArray + /// + /// @return NdArray + /// + template + NdArray pybind2nc(pbArray& numpyArray) + { + const auto dataPtr = numpyArray.mutable_data(); + switch (numpyArray.ndim()) + { + case 0: + { + return NdArray(dataPtr, 0, 0, false); + } + case 1: + { + const auto size = static_cast(numpyArray.size()); + return NdArray(dataPtr, 1, size, false); + } + case 2: + { + const auto numRows = static_cast(numpyArray.shape(0)); + const auto numCols = static_cast(numpyArray.shape(1)); + return NdArray(dataPtr, numRows, numCols, false); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input array must be no more than 2 dimensional."); + return {}; + } + } + } + + //============================================================================ + /// converts a numpy array to a numcpp NdArray using pybind bindings + /// Python will still own the underlying data. + /// + /// @param numpyArray + /// + /// @return NdArray + /// + template + NdArray pybind2nc_copy(const pbArray& numpyArray) + { + const auto dataPtr = numpyArray.data(); + switch (numpyArray.ndim()) + { + case 0: + { + return NdArray(dataPtr, 0, 0); + } + case 1: + { + const auto size = static_cast(numpyArray.size()); + return NdArray(dataPtr, 1, size); + } + case 2: + { + const auto numRows = static_cast(numpyArray.shape(0)); + const auto numCols = static_cast(numpyArray.shape(1)); + return NdArray(dataPtr, numRows, numCols); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input array must be no more than 2 dimensional."); + return {}; + } + } + } + + //============================================================================ + /// converts a numcpp NdArray to numpy array using pybind bindings + /// + /// @param inArray: the input array + /// + /// @return pybind11::array_t + /// + template + pbArrayGeneric nc2pybind(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + const std::vector shape{ static_cast(inShape.rows), + static_cast(inShape.cols) }; + const std::vector strides{ static_cast(inShape.cols * sizeof(dtype)), + static_cast(sizeof(dtype)) }; + return pbArrayGeneric(shape, strides, inArray.data()); + } + + //============================================================================ + /// converts a numcpp NdArray to numpy array using pybind bindings + /// + /// @param inArray: the input array + /// @param returnPolicy: the return policy + /// + /// @return pybind11::array_t + /// + template + pbArrayGeneric nc2pybind(NdArray& inArray, ReturnPolicy returnPolicy) + { + const Shape inShape = inArray.shape(); + const std::vector shape{ static_cast(inShape.rows), + static_cast(inShape.cols) }; + const std::vector strides{ static_cast(inShape.cols * sizeof(dtype)), + static_cast(sizeof(dtype)) }; + + switch (returnPolicy) + { + case ReturnPolicy::COPY: + { + return nc2pybind(inArray); + } + case ReturnPolicy::REFERENCE: + { + typename pybind11::capsule reference(inArray.data(), [](void* /*ptr*/) {}); + return pbArrayGeneric(shape, strides, inArray.data(), reference); + } + case ReturnPolicy::TAKE_OWNERSHIP: + { + typename pybind11::capsule garbageCollect(inArray.dataRelease(), + [](void* ptr) + { + auto* dataPtr = reinterpret_cast(ptr); + delete[] dataPtr; + }); + return pbArrayGeneric(shape, strides, inArray.data(), garbageCollect); + } + default: + { + std::stringstream sstream; + sstream << "ReturnPolicy " << returnPolicyStringMap.at(returnPolicy) << " has not been implemented yet" + << std::endl; + THROW_INVALID_ARGUMENT_ERROR(sstream.str()); + } + } + } +} // namespace nc::pybindInterface +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4e5be4370c1518460effbc58ccdc8ae148e29166 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random.hpp @@ -0,0 +1,61 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Random number distributions +/// +#pragma once + +#include "NumCpp/Random/RNG.hpp" +#include "NumCpp/Random/bernoulli.hpp" +#include "NumCpp/Random/beta.hpp" +#include "NumCpp/Random/binomial.hpp" +#include "NumCpp/Random/cauchy.hpp" +#include "NumCpp/Random/chiSquare.hpp" +#include "NumCpp/Random/choice.hpp" +#include "NumCpp/Random/discrete.hpp" +#include "NumCpp/Random/exponential.hpp" +#include "NumCpp/Random/extremeValue.hpp" +#include "NumCpp/Random/f.hpp" +#include "NumCpp/Random/gamma.hpp" +#include "NumCpp/Random/generator.hpp" +#include "NumCpp/Random/geometric.hpp" +#include "NumCpp/Random/laplace.hpp" +#include "NumCpp/Random/lognormal.hpp" +#include "NumCpp/Random/negativeBinomial.hpp" +#include "NumCpp/Random/nonCentralChiSquared.hpp" +#include "NumCpp/Random/normal.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/poisson.hpp" +#include "NumCpp/Random/rand.hpp" +#include "NumCpp/Random/randFloat.hpp" +#include "NumCpp/Random/randInt.hpp" +#include "NumCpp/Random/randN.hpp" +#include "NumCpp/Random/shuffle.hpp" +#include "NumCpp/Random/standardNormal.hpp" +#include "NumCpp/Random/studentT.hpp" +#include "NumCpp/Random/triangle.hpp" +#include "NumCpp/Random/uniform.hpp" +#include "NumCpp/Random/uniformOnSphere.hpp" +#include "NumCpp/Random/weibull.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/RNG.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/RNG.hpp new file mode 100644 index 0000000000000000000000000000000000000000..55ca4e3a5cff2159872253161489ec0158033620 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/RNG.hpp @@ -0,0 +1,1116 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Random Number Generater Class with non-global state +/// +#pragma once + +#include + +#include "NumCpp/Random/bernoulli.hpp" +#include "NumCpp/Random/beta.hpp" +#include "NumCpp/Random/binomial.hpp" +#include "NumCpp/Random/cauchy.hpp" +#include "NumCpp/Random/chiSquare.hpp" +#include "NumCpp/Random/choice.hpp" +#include "NumCpp/Random/discrete.hpp" +#include "NumCpp/Random/exponential.hpp" +#include "NumCpp/Random/extremeValue.hpp" +#include "NumCpp/Random/f.hpp" +#include "NumCpp/Random/gamma.hpp" +#include "NumCpp/Random/geometric.hpp" +#include "NumCpp/Random/laplace.hpp" +#include "NumCpp/Random/lognormal.hpp" +#include "NumCpp/Random/negativeBinomial.hpp" +#include "NumCpp/Random/nonCentralChiSquared.hpp" +#include "NumCpp/Random/normal.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/poisson.hpp" +#include "NumCpp/Random/rand.hpp" +#include "NumCpp/Random/randFloat.hpp" +#include "NumCpp/Random/randInt.hpp" +#include "NumCpp/Random/randN.hpp" +#include "NumCpp/Random/shuffle.hpp" +#include "NumCpp/Random/standardNormal.hpp" +#include "NumCpp/Random/studentT.hpp" +#include "NumCpp/Random/triangle.hpp" +#include "NumCpp/Random/uniform.hpp" +#include "NumCpp/Random/uniformOnSphere.hpp" +#include "NumCpp/Random/weibull.hpp" + +namespace nc::random +{ + //============================================================================ + // Class Description: + /// Random Number Generater Class with non-global state + /// + template + class RNG + { + public: + //============================================================================ + // Method Description: + /// Defualt Constructor + /// + RNG() = default; + + //============================================================================ + // Method Description: + /// Seed Constructor + /// + /// @param seed: the seed value + /// + explicit RNG(int seed) : + generator_(seed){}; + + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + bool bernoulli(double inP = 0.5) + { + return detail::bernoulli(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + NdArray bernoulli(const Shape& inShape, double inP = 0.5) + { + return detail::bernoulli(generator_, inShape, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inAlpha, inBeta); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(const Shape& inShape, dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inShape, inAlpha, inBeta); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inShape, inN, inP); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(dtype inDof) + { + return detail::chiSquare(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(const Shape& inShape, dtype inDof) + { + return detail::chiSquare(generator_, inShape, inDof); + } + + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param inArray + /// @return NdArray + /// + template + dtype choice(const NdArray& inArray) + { + return detail::choice(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray choice(const NdArray& inArray, uint32 inNum, bool replace = true) + { + return detail::choice(generator_, inArray, inNum, replace); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(const NdArray& inWeights) + { + return detail::discrete(generator_, inWeights); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(const Shape& inShape, const NdArray& inWeights) + { + return detail::discrete(generator_, inShape, inWeights); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(dtype inScaleValue = 1) + { + return detail::exponential(generator_, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(const Shape& inShape, dtype inScaleValue = 1) + { + return detail::exponential(generator_, inShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inShape, inA, inB); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(const Shape& inShape, dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inShape, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inShape, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(double inP = 0.5) + { + return detail::geometric(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(const Shape& inShape, double inP = 0.5) + { + return detail::geometric(generator_, inShape, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inLoc, inScale); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inShape, inLoc, inScale); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inShape, inN, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inK, inLambda); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray nonCentralChiSquared(const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inShape, inK, inLambda); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(dtype inValue) + { + return detail::permutation(generator_, inValue); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(const NdArray& inArray) + { + return detail::permutation(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(double inMean = 1) + { + return detail::poisson(generator_, inMean); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(const Shape& inShape, double inMean = 1) + { + return detail::poisson(generator_, inShape, inMean); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @return NdArray + /// + template + dtype rand() + { + return detail::rand(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(const Shape& inShape) + { + return detail::rand(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inShape, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inShape, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @return dtype + /// + template + dtype randN() + { + return detail::randN(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(const Shape& inShape) + { + return detail::randN(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Seed Constructor + /// + /// @param value: the seed value + /// + void seed(int value) noexcept + { + generator_.seed(value); + } + + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param inArray + /// + template + void shuffle(NdArray& inArray) + { + return detail::shuffle(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @return NdArray + /// + template + dtype standardNormal() + { + return detail::standardNormal(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(const Shape& inShape) + { + return detail::standardNormal(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(dtype inDof) + { + return detail::studentT(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(const Shape& inShape, dtype inDof) + { + return detail::studentT(generator_, inShape, inDof); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inA, inB, inC); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray triangle(const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inShape, inA, inB, inC); + } +#endif + + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(const Shape& inShape, dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inShape, inLow, inHigh); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(uint32 inNumPoints, uint32 inDims = 2) + { + return detail::uniformOnSphere(generator_, inNumPoints, inDims); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inShape, inA, inB); + } + + private: + GeneratorType generator_{}; + }; +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/bernoulli.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/bernoulli.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a643fbbb6413b95a38440b8831885c5eda5bbdd3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/bernoulli.hpp @@ -0,0 +1,119 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "bernoulli" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param generator: instance of a random number generator + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + template + bool bernoulli(GeneratorType& generator, double inP = 0.5) + { + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1]."); + } + + std::bernoulli_distribution dist(inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + template + NdArray bernoulli(GeneratorType& generator, const Shape& inShape, double inP = 0.5) + { + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::bernoulli_distribution dist(inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](bool& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + inline bool bernoulli(double inP = 0.5) + { + return detail::bernoulli(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + inline NdArray bernoulli(const Shape& inShape, double inP = 0.5) + { + return detail::bernoulli(generator_, inShape, inP); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/beta.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/beta.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c2801ed7f07492be418a297a8f204671e1143ab4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/beta.hpp @@ -0,0 +1,160 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "beta" distribution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/beta_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param generator: instance of a random number generator + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(GeneratorType& generator, dtype inAlpha, dtype inBeta) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inAlpha < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input alpha must be greater than zero."); + } + + if (inBeta < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input beta must be greater than zero."); + } + + boost::random::beta_distribution dist(inAlpha, inBeta); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(GeneratorType& generator, const Shape& inShape, dtype inAlpha, dtype inBeta) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inAlpha < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input alpha must be greater than zero."); + } + + if (inBeta < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input beta must be greater than zero."); + } + + NdArray returnArray(inShape); + + boost::random::beta_distribution dist(inAlpha, inBeta); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inAlpha, inBeta); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(const Shape& inShape, dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inShape, inAlpha, inBeta); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/binomial.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/binomial.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a8b3ebd1d5dd964d21283403912d13d91e75fa82 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/binomial.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "binomial" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param generator: instance of a random number generator + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(GeneratorType& generator, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::binomial_distribution dist(inN, inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(GeneratorType& generator, const Shape& inShape, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::binomial_distribution dist(inN, inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inShape, inN, inP); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/cauchy.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/cauchy.hpp new file mode 100644 index 0000000000000000000000000000000000000000..999fe0144bdacbd709a625dff069a66023b35514 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/cauchy.hpp @@ -0,0 +1,133 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "cauchy" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::cauchy_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::cauchy_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/chiSquare.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/chiSquare.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b98a87f1c96d9136c80db8afc31e75f2646b84c3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/chiSquare.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "chi square" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param generator: instance of a random number generator + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(GeneratorType& generator, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom must be greater than zero."); + } + + std::chi_squared_distribution dist(inDof); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(GeneratorType& generator, const Shape& inShape, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::chi_squared_distribution dist(inDof); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(dtype inDof) + { + return detail::chiSquare(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(const Shape& inShape, dtype inDof) + { + return detail::chiSquare(generator_, inShape, inDof); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/choice.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/choice.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ed9948e52cc7fc56628ea068f02b5e77b4bbd612 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/choice.hpp @@ -0,0 +1,118 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Chooses a random sample from an input array. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/randInt.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @return NdArray + /// + template + dtype choice(GeneratorType& generator, const NdArray& inArray) + { + uint32 randIdx = detail::randInt(generator, inArray.size()); + return inArray[randIdx]; + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray + choice(GeneratorType& generator, const NdArray& inArray, uint32 inNum, bool replace = true) + { + if (!replace && inNum > inArray.size()) + { + THROW_INVALID_ARGUMENT_ERROR("when 'replace' == false 'inNum' must be <= inArray.size()"); + } + + if (replace) + { + NdArray outArray(1, inNum); + std::for_each(outArray.begin(), + outArray.end(), + [&generator, &inArray](dtype& value) -> void { value = choice(generator, inArray); }); + + return outArray; + } + + return detail::permutation(generator, inArray)[Slice(inNum)]; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param inArray + /// @return NdArray + /// + template + dtype choice(const NdArray& inArray) + { + return detail::choice(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray choice(const NdArray& inArray, uint32 inNum, bool replace = true) + { + return detail::choice(generator_, inArray, inNum, replace = true); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/discrete.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/discrete.hpp new file mode 100644 index 0000000000000000000000000000000000000000..62fe533a5399429fcbe5c3c7d59abdb3fbe939e8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/discrete.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "discrete" distrubution. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param generator: instance of a random number generator + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(GeneratorType& generator, const NdArray& inWeights) + { + STATIC_ASSERT_INTEGER(dtype); + + std::discrete_distribution dist(inWeights.cbegin(), inWeights.cend()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(GeneratorType& generator, const Shape& inShape, const NdArray& inWeights) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(inShape); + + std::discrete_distribution dist(inWeights.cbegin(), inWeights.cend()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(const NdArray& inWeights) + { + return detail::discrete(generator_, inWeights); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(const Shape& inShape, const NdArray& inWeights) + { + return detail::discrete(generator_, inShape, inWeights); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/exponential.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/exponential.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d37a1902838c8e2cfbc271ad8459ddba440cb61a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/exponential.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "exponential" distrubution +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param generator: instance of a random number generator + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(GeneratorType& generator, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::exponential_distribution dist(inScaleValue); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(GeneratorType& generator, const Shape& inShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inShape); + + std::exponential_distribution dist(inScaleValue); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(dtype inScaleValue = 1) + { + return detail::exponential(generator_, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(const Shape& inShape, dtype inScaleValue = 1) + { + return detail::exponential(generator_, inShape, inScaleValue); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/extremeValue.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/extremeValue.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c65a9572698c7ae9a2ef8246359595a5a5b8391d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/extremeValue.hpp @@ -0,0 +1,139 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "extreme value" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(GeneratorType& generator, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + std::extreme_value_distribution dist(inA, inB); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(GeneratorType& generator, const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::extreme_value_distribution dist(inA, inB); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inShape, inA, inB); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/f.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/f.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9fec07dfa2f94ad46da1d41e00b9d140aeafd454 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/f.hpp @@ -0,0 +1,147 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "F" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param generator: instance of a random number generator + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(GeneratorType& generator, dtype inDofN, dtype inDofD) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDofN <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom should be greater than zero."); + } + + if (inDofD <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("denominator degrees of freedom should be greater than zero."); + } + + std::fisher_f_distribution dist(inDofN, inDofD); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(GeneratorType& generator, const Shape& inShape, dtype inDofN, dtype inDofD) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDofN <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom should be greater than zero."); + } + + if (inDofD <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("denominator degrees of freedom should be greater than zero."); + } + + NdArray returnArray(inShape); + + std::fisher_f_distribution dist(inDofN, inDofD); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(const Shape& inShape, dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inShape, inDofN, inDofD); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/gamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/gamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2cda5b1586858f991830b4b20f1afad536d35ae0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/gamma.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "gamma" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param generator: instance of a random number generator + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(GeneratorType& generator, dtype inGammaShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inGammaShape <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input gamma shape should be greater than zero."); + } + + if (inScaleValue <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input scale should be greater than zero."); + } + + std::gamma_distribution dist(inGammaShape, inScaleValue); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(GeneratorType& generator, const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inGammaShape <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input gamma shape should be greater than zero."); + } + + if (inScaleValue <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input scale should be greater than zero."); + } + + NdArray returnArray(inShape); + + std::gamma_distribution dist(inGammaShape, inScaleValue); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inShape, inGammaShape, inScaleValue); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/generator.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/generator.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a9e8f0c6ad317251240941dd1db7af21add2eda3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/generator.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Seeds the random number generator +/// +#pragma once + +#include + +namespace nc::random +{ + /// generator function + static std::mt19937_64 generator_; + + //============================================================================ + // Method Description: + /// Seeds the random number generator + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html#numpy.random.seed + /// + /// @param inSeed + /// + inline void seed(int inSeed) + { + generator_.seed(inSeed); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/geometric.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/geometric.hpp new file mode 100644 index 0000000000000000000000000000000000000000..638c0987a344fa8029615ba1881f9b8cd7754496 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/geometric.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "geometric" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param generator: instance of a random number generator + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(GeneratorType& generator, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::geometric_distribution dist(inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(GeneratorType& generator, const Shape& inShape, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::geometric_distribution dist(inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(double inP = 0.5) + { + return detail::geometric(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(const Shape& inShape, double inP = 0.5) + { + return detail::geometric(generator_, inShape, inP); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/laplace.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/laplace.hpp new file mode 100644 index 0000000000000000000000000000000000000000..101dba703641b3c8a5872f2b618ce15ed30e7cf0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/laplace.hpp @@ -0,0 +1,138 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "laplace" distrubution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/random/laplace_distribution.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param generator: instance of a random number generator + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(GeneratorType& generator, dtype inLoc = 0, dtype inScale = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + boost::random::laplace_distribution dist(inLoc, inScale); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(GeneratorType& generator, const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inShape); + + boost::random::laplace_distribution dist(inLoc, inScale); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inLoc, inScale); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inShape, inLoc, inScale); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/lognormal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/lognormal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..95cfe2ef6fc33ab3803ad43fa88edc8661a13cc1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/lognormal.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "lognormal" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::lognormal_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::lognormal_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/negativeBinomial.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/negativeBinomial.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3d04d75d8515dff6175ba682633424688fe25c9e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/negativeBinomial.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "negative Binomial" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param generator: instance of a random number generator + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(GeneratorType& generator, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::negative_binomial_distribution dist(inN, inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(GeneratorType& generator, const Shape& inShape, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::negative_binomial_distribution dist(inN, inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inShape, inN, inP); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp new file mode 100644 index 0000000000000000000000000000000000000000..27da69f0043dbcda452eeffd0f10329050514fa4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp @@ -0,0 +1,161 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "non central chi squared" distrubution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/non_central_chi_squared_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param generator: instance of a random number generator + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(GeneratorType& generator, dtype inK = 1, dtype inLambda = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inK <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input k must be greater than zero."); + } + + if (inLambda <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input lambda must be greater than zero."); + } + + boost::random::non_central_chi_squared_distribution dist(inK, inLambda); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray + nonCentralChiSquared(GeneratorType& generator, const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inK <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input k must be greater than zero."); + } + + if (inLambda <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input lambda must be greater than zero."); + } + + NdArray returnArray(inShape); + + boost::random::non_central_chi_squared_distribution dist(inK, inLambda); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inK, inLambda); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray nonCentralChiSquared(const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inShape, inK, inLambda); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/normal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/normal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..862fcd90e3c2818f714535ff67eb8f325a2f3099 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/normal.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "normal" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::normal_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::normal_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/permutation.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/permutation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..a5839dde98d26a11a68b5ed2fa4effa7f7dd6943 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/permutation.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Randomly permute a sequence, or return a permuted range +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param generator: instance of a random number generator + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(GeneratorType& generator, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray = arange(inValue); + std::shuffle(returnArray.begin(), returnArray.end(), generator); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(GeneratorType& generator, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray); + std::shuffle(returnArray.begin(), returnArray.end(), generator); + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(dtype inValue) + { + return detail::permutation(generator_, inValue); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(const NdArray& inArray) + { + return detail::permutation(generator_, inArray); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/poisson.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/poisson.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e3315e5e41936c39d2bb401060c3faeb36b3033e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/poisson.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "poisson" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param generator: instance of a random number generator + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(GeneratorType& generator, double inMean = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inMean <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input mean must be greater than zero."); + } + + std::poisson_distribution dist(inMean); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(GeneratorType& generator, const Shape& inShape, double inMean = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inMean <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input mean must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::poisson_distribution dist(inMean); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(double inMean = 1) + { + return detail::poisson(generator_, inMean); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(const Shape& inShape, double inMean = 1) + { + return detail::poisson(generator_, inShape, inMean); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/rand.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/rand.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9f9f8f0612c8326e6c60157bafb142ffadce85d5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/rand.hpp @@ -0,0 +1,124 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Create an array of the given shape and populate it with +/// random samples from a uniform distribution over [0, 1). +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param generator: instance of a random number generator + /// @return NdArray + /// + template + dtype rand(GeneratorType& generator) + { + STATIC_ASSERT_FLOAT(dtype); + + std::uniform_real_distribution dist(static_cast(0.), + static_cast(1.) - DtypeInfo::epsilon()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray returnArray(inShape); + + std::uniform_real_distribution dist(static_cast(0.), + static_cast(1.) - DtypeInfo::epsilon()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @return NdArray + /// + template + dtype rand() + { + return detail::rand(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(const Shape& inShape) + { + return detail::rand(generator_, inShape); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randFloat.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randFloat.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7292f3454209c97f2973db32d0cf6abe3599564c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randFloat.hpp @@ -0,0 +1,157 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Return random floats from low (inclusive) to high (exclusive), +/// with the given shape +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(GeneratorType& generator, dtype inLow, dtype inHigh = 0.) + { + STATIC_ASSERT_FLOAT(dtype); + + if (utils::essentiallyEqual(inLow, inHigh)) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + std::uniform_real_distribution dist(inLow, inHigh - DtypeInfo::epsilon()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + STATIC_ASSERT_FLOAT(dtype); + + if (utils::essentiallyEqual(inLow, inHigh)) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + NdArray returnArray(inShape); + + std::uniform_real_distribution dist(inLow, inHigh - DtypeInfo::epsilon()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randInt.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randInt.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fc9687da4707fcbd97dbe27aceec8742b859ca5a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randInt.hpp @@ -0,0 +1,157 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Return random integers from low (inclusive) to high (exclusive), +/// with the given shape +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(GeneratorType& generator, dtype inLow, dtype inHigh = 0) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inLow == inHigh) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + std::uniform_int_distribution dist(inLow, inHigh - 1); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inLow == inHigh) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh - 1) + { + std::swap(inLow, inHigh); + } + + NdArray returnArray(inShape); + + std::uniform_int_distribution dist(inLow, inHigh - 1); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&dist, &generator](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randN.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randN.hpp new file mode 100644 index 0000000000000000000000000000000000000000..42c9d3a1adf435297831b864884ab09297d863bb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/randN.hpp @@ -0,0 +1,121 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "standard normal" distribution. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param generator: instance of a random number generator + /// @return dtype + /// + template + dtype randN(GeneratorType& generator) + { + STATIC_ASSERT_FLOAT(dtype); + + std::normal_distribution dist; + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray returnArray(inShape); + + std::normal_distribution dist; + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @return dtype + /// + template + dtype randN() + { + return detail::randN(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(const Shape& inShape) + { + return detail::randN(generator_, inShape); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/shuffle.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/shuffle.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3bfe866305ee3697f6bd2015be8a933086c93436 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/shuffle.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Modify a sequence in-place by shuffling its contents. +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// + template + void shuffle(GeneratorType& generator, NdArray& inArray) + { + std::shuffle(inArray.begin(), inArray.end(), generator); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param inArray + /// + template + void shuffle(NdArray& inArray) + { + return detail::shuffle(generator_, inArray); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/standardNormal.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/standardNormal.hpp new file mode 100644 index 0000000000000000000000000000000000000000..41ff1dc11677ba7b1e9f424307e8134f2458e51a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/standardNormal.hpp @@ -0,0 +1,113 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "standard normal" distrubution +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/normal.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param generator: instance of a random number generator + /// @return NdArray + /// + template + dtype standardNormal(GeneratorType& generator) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return detail::normal(generator, 0, 1); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return detail::normal(generator, inShape, 0, 1); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @return NdArray + /// + template + dtype standardNormal() + { + return detail::standardNormal(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(const Shape& inShape) + { + return detail::standardNormal(generator_, inShape); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/studentT.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/studentT.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f389383340f576c1904fe383e3dac55001ab1e46 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/studentT.hpp @@ -0,0 +1,136 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "student-T" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param generator: instance of a random number generator + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(GeneratorType& generator, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("degrees of freedom must be greater than zero."); + } + + std::student_t_distribution dist(inDof); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(GeneratorType& generator, const Shape& inShape, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("degrees of freedom must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::student_t_distribution dist(inDof); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(dtype inDof) + { + return detail::studentT(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(const Shape& inShape, dtype inDof) + { + return detail::studentT(generator_, inShape, inDof); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/triangle.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/triangle.hpp new file mode 100644 index 0000000000000000000000000000000000000000..53fdf22aa2507e215ca22c3f7824b6423921305f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/triangle.hpp @@ -0,0 +1,190 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Create an array of the given shape and populate it with +/// random samples from the "triangle" distribution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/triangle_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param generator: instance of a random number generator + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(GeneratorType& generator, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inA < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input A must be greater than or equal to zero."); + } + + if (inB < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input B must be greater than or equal to zero."); + } + + if (inC < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input C must be greater than or equal to zero."); + } + + const bool aLessB = inA <= inB; + const bool bLessC = inB <= inC; + if (!(aLessB && bLessC)) + { + THROW_INVALID_ARGUMENT_ERROR("inputs must be a <= b <= c."); + } + + boost::random::triangle_distribution dist(inA, inB, inC); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray + triangle(GeneratorType& generator, const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inA < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input A must be greater than or equal to zero."); + } + + if (inB < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input B must be greater than or equal to zero."); + } + + if (inC < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input C must be greater than or equal to zero."); + } + + const bool aLessB = inA <= inB; + const bool bLessC = inB <= inC; + if (!(aLessB && bLessC)) + { + THROW_INVALID_ARGUMENT_ERROR("inputs must be a <= b <= c."); + } + + NdArray returnArray(inShape); + + boost::random::triangle_distribution dist(inA, inB, inC); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inA, inB, inC); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray triangle(const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inShape, inA, inB, inC); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniform.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniform.hpp new file mode 100644 index 0000000000000000000000000000000000000000..30a62a49b95680ee5d8fd4a96887cfeba908ae0c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniform.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Draw samples from a uniform distribution. +/// +#pragma once + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Random/randFloat.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(GeneratorType& generator, dtype inLow, dtype inHigh) + { + STATIC_ASSERT_FLOAT(dtype); + + return detail::randFloat(generator, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh) + { + STATIC_ASSERT_FLOAT(dtype); + + return detail::randFloat(generator, inShape, inLow, inHigh); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(const Shape& inShape, dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniformOnSphere.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniformOnSphere.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6133733bc10a72f13c85d350ab5deca41fb9a9c1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/uniformOnSphere.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Such a distribution produces random numbers uniformly +/// distributed on the unit sphere of arbitrary dimension dim. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/uniform_on_sphere.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param generator: instance of a random number generator + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(GeneratorType& generator, uint32 inNumPoints, uint32 inDims = 2) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inNumPoints == 0) + { + return {}; + } + + boost::random::uniform_on_sphere dist(static_cast(inDims)); + + NdArray returnArray(inNumPoints, inDims); + for (uint32 row = 0; row < inNumPoints; ++row) + { + const auto& point = dist(generator); + std::copy(point.begin(), point.end(), returnArray.begin(row)); + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(uint32 inNumPoints, uint32 inDims = 2) + { + return detail::uniformOnSphere(generator_, inNumPoints, inDims); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/weibull.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/weibull.hpp new file mode 100644 index 0000000000000000000000000000000000000000..317bf89034089533f94adca87ddc16e748747cc4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Random/weibull.hpp @@ -0,0 +1,150 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "weibull" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param generator: instance of a random number generator + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(GeneratorType& generator, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + std::weibull_distribution dist(inA, inB); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(GeneratorType& generator, const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::weibull_distribution dist(inA, inB); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inShape, inA, inB); + } +} // namespace nc::random diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c212cf881ead1a5d59b22746da130f99505d98d7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Roots/Bisection.hpp" +#include "NumCpp/Roots/Brent.hpp" +#include "NumCpp/Roots/Dekker.hpp" +#include "NumCpp/Roots/Newton.hpp" +#include "NumCpp/Roots/Secant.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Bisection.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Bisection.hpp new file mode 100644 index 0000000000000000000000000000000000000000..aec89a95317e84ba765a75e6b8efdd4cbe43b0e2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Bisection.hpp @@ -0,0 +1,155 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Bisection root finding method + /// + class Bisection : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Bisection(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Bisection(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Bisection() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + checkAndFixAlgorithmCriteria(a, b); + + double x = 0.5 * (a + b); + double fx = f_(x); + + while (std::fabs(fx) >= epsilon_) + { + x = calculateX(x, a, b, fx); + fx = f_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Checks the bounds criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// + void checkAndFixAlgorithmCriteria(double &a, double &b) const noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (f_(a) < f_(b)) + { + std::swap(a, b); + } + } + + //============================================================================ + // Method Description: + /// Calculates the bisection point + /// + /// @param x: the evaluation point + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fx: the function evaluated at x + /// @return x + /// + static double calculateX(double x, double &a, double &b, double fx) noexcept + { + if (fx < 0) + { + b = x; + } + else + { + a = x; + } + + return 0.5 * (a + b); + } + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Brent.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Brent.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b9838188bf9e45c014e91f8af06cc9fa087faf0e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Brent.hpp @@ -0,0 +1,280 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Brent root finding method + /// + class Brent : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Brent(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Brent(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Brent() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + double fa = f_(a); + double fb = f_(b); + + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + double lastB = a; // b_{k-1} + double lastFb = fa; + double s = DtypeInfo::max(); + double fs = DtypeInfo::max(); + double penultimateB = a; // b_{k-2} + + bool bisection = true; + while (std::fabs(fb) > epsilon_ && std::fabs(fs) > epsilon_ && std::fabs(b - a) > epsilon_) + { + if (useInverseQuadraticInterpolation(fa, fb, lastFb)) + { + s = calculateInverseQuadraticInterpolation(a, b, lastB, fa, fb, lastFb); + } + else + { + s = calculateSecant(a, b, fa, fb); + } + + if (useBisection(bisection, b, lastB, penultimateB, s)) + { + s = calculateBisection(a, b); + bisection = true; + } + else + { + bisection = false; + } + + fs = f_(s); + penultimateB = lastB; + lastB = b; + + if (fa * fs < 0) + { + b = s; + } + else + { + a = s; + } + + fa = f_(a); + lastFb = fb; + fb = f_(b); + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + incrementNumberOfIterations(); + } + + return fb < fs ? b : s; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Calculates the bisection point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return x + /// + static double calculateBisection(const double a, const double b) noexcept + { + return 0.5 * (a + b); + } + + //============================================================================ + // Method Description: + /// Calculates the secant point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @return the secant point + /// + static double calculateSecant(const double a, const double b, const double fa, const double fb) noexcept + { + // No need to check division by 0, in this case the method returns NAN which is taken care by + // useSecantMethod method + return b - fb * (b - a) / (fb - fa); + } + + //============================================================================ + // Method Description: + /// Calculates the inverse quadratic interpolation + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param lastB: the previous upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @param lastFb: the previous function evaluated at the upper bound + /// @return the inverse quadratic interpolation + /// + static double calculateInverseQuadraticInterpolation(const double a, + const double b, + const double lastB, + const double fa, + const double fb, + const double lastFb) noexcept + { + return a * fb * lastFb / ((fa - fb) * (fa - lastFb)) + b * fa * lastFb / ((fb - fa) * (fb - lastFb)) + + lastB * fa * fb / ((lastFb - fa) * (lastFb - fb)); + } + + //============================================================================ + // Method Description: + /// Uses the inverse quadratic interpolation + /// + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @param lastFb: the previous function evaluated at the upper bound + /// @return bool + /// + static bool useInverseQuadraticInterpolation(const double fa, const double fb, const double lastFb) noexcept + { + return !utils::essentiallyEqual(fa, lastFb) && utils::essentiallyEqual(fb, lastFb); + } + + //============================================================================ + // Method Description: + /// Checks the algorithm criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// + static void checkAndFixAlgorithmCriteria(double &a, double &b, double &fa, double &fb) noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (std::fabs(fa) < std::fabs(fb)) + { + std::swap(a, b); + std::swap(fa, fb); + } + } + + //============================================================================ + // Method Description: + /// Uses the bisection + /// + /// @param bisection: the bisection point + /// @param b: the upper bound + /// @param lastB: the previous upper bound + /// @param penultimateB: + /// @param s: + /// @return bool + /// + [[nodiscard]] bool useBisection(const bool bisection, + const double b, + const double lastB, + const double penultimateB, + const double s) const noexcept + { + const double DELTA = epsilon_ + std::numeric_limits::min(); + + return (bisection && + std::fabs(s - b) >= + 0.5 * std::fabs(b - lastB)) || // Bisection was used in last step but |s-b|>=|b-lastB|/2 <- + // Interpolation step would be to rough, so still use bisection + (!bisection && std::fabs(s - b) >= + 0.5 * std::fabs(lastB - penultimateB)) || // Interpolation was used in last step + // but |s-b|>=|lastB-penultimateB|/2 <- + // Interpolation step would be to small + (bisection && + std::fabs(b - lastB) < DELTA) || // If last iteration was using bisection and difference between + // b and lastB is < delta use bisection for next iteration + (!bisection && std::fabs(lastB - penultimateB) < + DELTA); // If last iteration was using interpolation but difference between + // lastB ond penultimateB is < delta use biscetion for next iteration + } + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Dekker.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Dekker.hpp new file mode 100644 index 0000000000000000000000000000000000000000..c902e9d233d9288626067372816d5c2075f65f72 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Dekker.hpp @@ -0,0 +1,198 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Dekker root finding method + /// + class Dekker : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Dekker(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Dekker(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Dekker() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + double fa = f_(a); + double fb = f_(b); + + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + double lastB = a; + double lastFb = fa; + + while (std::fabs(fb) > epsilon_ && std::fabs(b - a) > epsilon_) + { + const double s = calculateSecant(b, fb, lastB, lastFb); + const double m = calculateBisection(a, b); + + lastB = b; + + b = useSecantMethod(b, s, m) ? s : m; + + lastFb = fb; + fb = f_(b); + + if (fa * fb > 0 && fb * lastFb < 0) + { + a = lastB; + } + + fa = f_(a); + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + incrementNumberOfIterations(); + } + + return b; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Checks the bounds criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evalulated at the lower bound + /// @param fb: the function evalulated at the upper bound + /// + static void checkAndFixAlgorithmCriteria(double &a, double &b, double &fa, double &fb) noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (std::fabs(fa) < std::fabs(fb)) + { + std::swap(a, b); + std::swap(fa, fb); + } + } + + //============================================================================ + // Method Description: + /// Calculates secant + /// + /// @param b: the upper bound + /// @param fb: the function evalulated at the upper bound + /// @param lastB: the last upper bound + /// @param lastFb: the function evalulated at the last upper bound + /// @ return secant value + /// + static double calculateSecant(double b, double fb, double lastB, double lastFb) noexcept + { + // No need to check division by 0, in this case the method returns NAN which is taken care by + // useSecantMethod method + return b - fb * (b - lastB) / (fb - lastFb); + } + + //============================================================================ + // Method Description: + /// Calculate the bisection point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return bisection point + /// + static double calculateBisection(double a, double b) noexcept + { + return 0.5 * (a + b); + } + + //============================================================================ + // Method Description: + /// Whether or not to use the secant method + /// + /// @param b: the upper bound + /// @param s: + /// @param m: + /// @ return bool + /// + static bool useSecantMethod(double b, double s, double m) noexcept + { + // Value s calculated by secant method has to be between m and b + return (b > m && s > m && s < b) || (b < m && s > b && s < m); + } + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Iteration.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Iteration.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e50d71ebfc63bb36b518e3e87ff0929a507ce6fd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Iteration.hpp @@ -0,0 +1,120 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// ABC for iteration classes to derive from + class Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// + explicit Iteration(double epsilon) noexcept : + epsilon_(epsilon) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// + Iteration(double epsilon, uint32 maxNumIterations) noexcept : + epsilon_(epsilon), + maxNumIterations_(maxNumIterations) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + virtual ~Iteration() noexcept = default; + + //============================================================================ + // Method Description: + /// Returns the number of iterations + /// + /// @return: number of iterations + /// + [[nodiscard]] uint32 numIterations() const noexcept + { + return numIterations_; + } + + protected: + //============================================================================ + // Method Description: + /// Resets the number of iterations + /// + void resetNumberOfIterations() noexcept + { + numIterations_ = 0; + } + + //============================================================================ + // Method Description: + /// Incraments the number of iterations + /// + /// @return the number of iterations prior to incramenting + /// + void incrementNumberOfIterations() + { + ++numIterations_; + if (numIterations_ > maxNumIterations_) + { + THROW_RUNTIME_ERROR( + "Maximum number of iterations has been reached; no root has been found within epsilon."); + } + } + + //====================================Attributes============================== + const double epsilon_; + uint32 maxNumIterations_{ 1000 }; + uint32 numIterations_{ 0 }; + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Newton.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Newton.hpp new file mode 100644 index 0000000000000000000000000000000000000000..af4e7e9d6182afca68b2ba541872cf9d2127bb57 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Newton.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Newton root finding method + /// + class Newton : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// @param fPrime: the derivative of the function + /// + Newton(const double epsilon, std::function f, std::function fPrime) noexcept : + Iteration(epsilon), + f_(std::move(f)), + fPrime_(std::move(fPrime)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// @param fPrime: the derivative of the function + /// + Newton(const double epsilon, + const uint32 maxNumIterations, + std::function f, + std::function fPrime) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)), + fPrime_(std::move(fPrime)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Newton() noexcept override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param x: the starting point + /// @return root nearest the starting point + /// + double solve(double x) + { + resetNumberOfIterations(); + + double fx = f_(x); + double fxPrime = fPrime_(x); + + while (std::fabs(fx) >= epsilon_) + { + x = calculateX(x, fx, fxPrime); + + fx = f_(x); + fxPrime = fPrime_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + const std::function fPrime_; + + //============================================================================ + // Method Description: + /// Calculates x + /// + /// @param x: the current x value + /// @param fx: the function evaluated at the current x value + /// @param fxPrime: the derivate of the function evaluated at the current x value + /// @return x + /// + static double calculateX(double x, double fx, double fxPrime) noexcept + { + return x - fx / fxPrime; + } + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Secant.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Secant.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d20b8aea05f0357850c215bf7762fc20161d4410 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Roots/Secant.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Secant root finding method + /// + class Secant : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Secant(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Secant(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Secant() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + if (f_(a) > f_(b)) + { + std::swap(a, b); + } + + double x = b; + double lastX = a; + double fx = f_(b); + double lastFx = f_(a); + + while (std::fabs(fx) >= epsilon_) + { + const double x_tmp = calculateX(x, lastX, fx, lastFx); + + lastFx = fx; + lastX = x; + x = x_tmp; + + fx = f_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Calculates x + /// + /// @param x: the current x value + /// @param lastX: the previous x value + /// @param fx: the function evaluated at the current x value + /// @param lastFx: the function evaluated at the previous x value + /// @return x + /// + static double calculateX(double x, double lastX, double fx, double lastFx) noexcept + { + const double functionDifference = fx - lastFx; + return x - fx * (x - lastX) / functionDifference; + } + }; +} // namespace nc::roots diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations.hpp new file mode 100644 index 0000000000000000000000000000000000000000..00a99561f0aa9e17fd033b2ea71e512aae773f50 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations.hpp @@ -0,0 +1,33 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Module for dealing with rotations +/// +#pragma once + +#include "NumCpp/Rotations/DCM.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Rotations/rodriguesRotation.hpp" +#include "NumCpp/Rotations/wahbasProblem.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/DCM.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/DCM.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7961e1492b3c0e8c2720eeb5b9d92195759a6b4c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/DCM.hpp @@ -0,0 +1,192 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Factory methods for generating direction cosine matrices and vectors +/// +#pragma once + +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/round.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //================================================================================ + /// Factory methods for generating direction cosine matrices and vectors + class DCM + { + public: + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates according + /// to the input euler angles + /// + /// @param roll: euler roll angle in radians + /// @param pitch: euler pitch angle in radians + /// @param yaw: euler yaw angle in radians + /// @return NdArray + /// + static NdArray eulerAngles(double roll, double pitch, double yaw) + { + return Quaternion(roll, pitch, yaw).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates according + /// to the input euler angles + /// + /// @param angles: euler roll, pitch, angles + /// @return NdArray + /// + static NdArray eulerAngles(const NdArray& angles) + { + return Quaternion(angles).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the input axis by the input angle + /// + /// @param inAxis: euler axis cartesian vector with x,y,z components + /// @param inAngle: euler angle in radians + /// @return NdArray + /// + static NdArray eulerAxisAngle(const NdArray& inAxis, double inAngle) + { + return Quaternion(inAxis, inAngle).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the input axis by the input angle + /// + /// @param inAxis: euler axis cartesian vector with x,y,z components + /// @param inAngle: euler angle in radians + /// @return NdArray + /// + static NdArray eulerAxisAngle(const Vec3& inAxis, double inAngle) + { + return Quaternion(inAxis, inAngle).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns whether the input array is a direction cosine + /// matrix + /// + /// @param inArray + /// @return bool + /// + static bool isValid(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + return inShape.rows == inShape.cols && + utils::essentiallyEqual(round(linalg::det(inArray), 2), 1.) && + utils::essentiallyEqual(round(linalg::det(inArray.transpose()), 2), 1.); + } + + //============================================================================ + // Method Description: + /// The euler roll angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler roll angle in radians + /// + static double roll(const NdArray& dcm) + { + return Quaternion(dcm).roll(); + } + + //============================================================================ + // Method Description: + /// The euler pitch angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler pitch angle in radians + /// + static double pitch(const NdArray& dcm) + { + return Quaternion(dcm).pitch(); + } + + //============================================================================ + // Method Description: + /// The euler yaw angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler yaw angle in radians + /// + static double yaw(const NdArray& dcm) + { + return Quaternion(dcm).yaw(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray xRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 1., 0., 0. }, inAngle); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray yRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 0., 1., 0. }, inAngle); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray zRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 0., 0., 1. }, inAngle); + } + }; +} // namespace nc::rotations diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/Quaternion.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/Quaternion.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3bea6570dc08a3212a30ca1e335d75a54e80e68a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/Quaternion.hpp @@ -0,0 +1,1034 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds a unit quaternion +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/norm.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/Linalg/hat.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //================================================================================ + // Class Description: + /// Holds a unit quaternion + class Quaternion + { + public: + //============================================================================ + // Method Description: + /// Default Constructor + /// + Quaternion() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param roll: euler roll angle in radians + /// @param pitch: euler pitch angle in radians + /// @param yaw: euler yaw angle in radians + /// + Quaternion(double roll, double pitch, double yaw) noexcept + { + eulerToQuat(roll, pitch, yaw); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inI + /// @param inJ + /// @param inK + /// @param inS + /// + Quaternion(double inI, double inJ, double inK, double inS) noexcept : + components_{ inI, inJ, inK, inS } + { + normalize(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param components + /// + Quaternion(const std::array& components) noexcept : + components_{ components } + { + normalize(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inArray: if size = 3 the roll, pitch, yaw euler angles + /// if size = 4 the i, j, k, s components + /// if shape = [3, 3] then direction cosine matrix + /// + Quaternion(const NdArray& inArray) : + components_{ 0., 0., 0., 0. } + { + if (inArray.size() == 3) + { + // euler angles + eulerToQuat(inArray[0], inArray[1], inArray[2]); + } + else if (inArray.size() == 4) + { + // quaternion i, j, k, s components + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), components_.begin()); + normalize(); + } + else if (inArray.size() == 9) + { + // direction cosine matrix + dcmToQuat(inArray); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input array is not a valid size."); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inAxis: Euler axis + /// @param inAngle: Euler angle in radians + /// + Quaternion(const Vec3& inAxis, double inAngle) noexcept + { + // normalize the input vector + Vec3 normAxis = inAxis.normalize(); + + const double halfAngle = inAngle / 2.; + const double sinHalfAngle = std::sin(halfAngle); + + components_[0] = normAxis.x * sinHalfAngle; + components_[1] = normAxis.y * sinHalfAngle; + components_[2] = normAxis.z * sinHalfAngle; + components_[3] = std::cos(halfAngle); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inAxis: Euler axis x,y,z vector components + /// @param inAngle: Euler angle in radians + /// + Quaternion(const NdArray& inAxis, double inAngle) : + Quaternion(Vec3(inAxis), inAngle) + { + } + + //============================================================================ + // Method Description: + /// the angle of rotation around the rotation axis that is described by the quaternion + /// + /// @return radians + /// + [[nodiscard]] double angleOfRotation() const noexcept + { + return 2. * std::acos(s()); + } + + //============================================================================ + // Method Description: + /// angular velocity vector between the two quaternions. The norm + /// of the array is the magnitude + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inTime (seperation time) + /// @return NdArray + /// + static NdArray angularVelocity(const Quaternion& inQuat1, const Quaternion& inQuat2, double inTime) + { + NdArray q0 = inQuat1.toNdArray(); + NdArray q1 = inQuat2.toNdArray(); + + NdArray qDot = q1 - q0; + qDot /= inTime; + + NdArray eyeTimesScalar(3); + eyeTimesScalar.zeros(); + eyeTimesScalar(0, 0) = inQuat2.s(); + eyeTimesScalar(1, 1) = inQuat2.s(); + eyeTimesScalar(2, 2) = inQuat2.s(); + + NdArray epsilonHat = linalg::hat(inQuat2.i(), inQuat2.j(), inQuat2.k()); + NdArray q(4, 3); + q.put(Slice(0, 3), Slice(0, 3), eyeTimesScalar + epsilonHat); + q(3, 0) = -inQuat2.i(); + q(3, 1) = -inQuat2.j(); + q(3, 2) = -inQuat2.k(); + + NdArray omega = q.transpose().dot(qDot.transpose()); + return omega *= 2.; + } + + //============================================================================ + // Method Description: + /// angular velocity vector between the two quaternions. The norm + /// of the array is the magnitude + /// + /// @param inQuat2 + /// @param inTime (seperation time) + /// @return NdArray + /// + [[nodiscard]] NdArray angularVelocity(const Quaternion& inQuat2, double inTime) const + { + return angularVelocity(*this, inQuat2, inTime); + } + + //============================================================================ + // Method Description: + /// the axis of rotation described by the quaternion + /// + /// @return Vec3 + /// + [[nodiscard]] Vec3 axisOfRotation() const noexcept + { + const auto halfAngle = angleOfRotation() / 2.; + const auto sinHalfAngle = std::sin(halfAngle); + auto axis = Vec3(i() / sinHalfAngle, j() / sinHalfAngle, k() / sinHalfAngle); + + // shouldn't be necessary, but let's be pedantic + return axis.normalize(); + } + + //============================================================================ + // Method Description: + /// quaternion conjugate + /// + /// @return Quaternion + /// + [[nodiscard]] Quaternion conjugate() const noexcept + { + return { -i(), -j(), -k(), s() }; + } + + //============================================================================ + // Method Description: + /// returns the i component + /// + /// @return double + /// + [[nodiscard]] double i() const noexcept + { + return components_[0]; + } + + //============================================================================ + // Method Description: + /// quaternion identity (0,0,0,1) + /// + /// @return Quaternion + /// + static Quaternion identity() noexcept + { + return {}; + } + + //============================================================================ + // Method Description: + /// quaternion inverse + /// + /// @return Quaterion + /// + [[nodiscard]] Quaternion inverse() const noexcept + { + /// for unit quaternions the inverse is equal to the conjugate + return conjugate(); + } + + //============================================================================ + // Method Description: + /// returns the j component + /// + /// @return double + /// + [[nodiscard]] double j() const noexcept + { + return components_[1]; + } + + //============================================================================ + // Method Description: + /// returns the k component + /// + /// @return double + /// + [[nodiscard]] double k() const noexcept + { + return components_[2]; + } + + //============================================================================ + // Method Description: + /// linearly interpolates between the two quaternions + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inPercent [0, 1] + /// @return Quaternion + /// + static Quaternion nlerp(const Quaternion& inQuat1, const Quaternion& inQuat2, double inPercent) + { + if (inPercent < 0. || inPercent > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input percent must be of the range [0,1]."); + } + + if (utils::essentiallyEqual(inPercent, 0.)) + { + return inQuat1; + } + if (utils::essentiallyEqual(inPercent, 1.)) + { + return inQuat2; + } + + const double oneMinus = 1. - inPercent; + std::array newComponents{}; + + stl_algorithms::transform(inQuat1.components_.begin(), + inQuat1.components_.end(), + inQuat2.components_.begin(), + newComponents.begin(), + [inPercent, oneMinus](double component1, double component2) -> double + { return oneMinus * component1 + inPercent * component2; }); + + return { newComponents }; + } + + //============================================================================ + // Method Description: + /// linearly interpolates between the two quaternions + /// + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + [[nodiscard]] Quaternion nlerp(const Quaternion& inQuat2, double inPercent) const + { + return nlerp(*this, inQuat2, inPercent); + } + + //============================================================================ + // Method Description: + /// The euler pitch angle in radians + /// + /// @return euler pitch angle in radians + /// + [[nodiscard]] double pitch() const noexcept + { + return std::asin(2 * (s() * j() - k() * i())); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the pitch axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion pitchRotation(double inAngle) noexcept + { + return { 0., inAngle, 0. }; + } + + //============================================================================ + // Method Description: + /// prints the Quaternion to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + // Method Description: + /// The euler roll angle in radians + /// + /// @return euler roll angle in radians + /// + [[nodiscard]] double roll() const noexcept + { + return std::atan2(2. * (s() * i() + j() * k()), 1. - 2. * (utils::sqr(i()) + utils::sqr(j()))); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the roll axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion rollRotation(double inAngle) noexcept + { + return { inAngle, 0., 0. }; + } + + //============================================================================ + // Method Description: + /// rotate a vector using the quaternion + /// + /// @param inVector (cartesian vector with x,y,z components) + /// @return NdArray (cartesian vector with x,y,z components) + /// + [[nodiscard]] NdArray rotate(const NdArray& inVector) const + { + if (inVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input inVector must be a cartesion vector of length = 3."); + } + + return *this * inVector; + } + + //============================================================================ + // Method Description: + /// rotate a vector using the quaternion + /// + /// @param inVec3 + /// @return Vec3 + /// + [[nodiscard]] Vec3 rotate(const Vec3& inVec3) const + { + return *this * inVec3; + } + + //============================================================================ + // Method Description: + /// returns the s component + /// + /// @return double + /// + [[nodiscard]] double s() const noexcept + { + return components_[3]; + } + + //============================================================================ + // Method Description: + /// spherical linear interpolates between the two quaternions + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + static Quaternion slerp(const Quaternion& inQuat1, const Quaternion& inQuat2, double inPercent) + { + if (inPercent < 0 || inPercent > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input percent must be of the range [0, 1]"); + } + + if (utils::essentiallyEqual(inPercent, 0.)) + { + return inQuat1; + } + if (utils::essentiallyEqual(inPercent, 1.)) + { + return inQuat2; + } + + double dotProduct = dot(inQuat1.toNdArray(), inQuat2.toNdArray()).item(); + + // If the dot product is negative, the quaternions + // have opposite handed-ness and slerp won't take + // the shorter path. Fix by reversing one quaternion. + Quaternion quat1Copy(inQuat1); + if (dotProduct < 0.) + { + quat1Copy *= -1.; + dotProduct *= -1.; + } + + constexpr double DOT_THRESHOLD = 0.9995; + if (dotProduct > DOT_THRESHOLD) + { + // If the inputs are too close for comfort, linearly interpolate + // and normalize the result. + return nlerp(inQuat1, inQuat2, inPercent); + } + + dotProduct = clip(dotProduct, -1., 1.); // Robustness: Stay within domain of acos() + const double theta0 = std::acos(dotProduct); // angle between input vectors + const double theta = theta0 * inPercent; // angle between v0 and result + + const double s0 = std::cos(theta) - + dotProduct * std::sin(theta) / std::sin(theta0); // == sin(theta_0 - theta) / sin(theta_0) + const double s1 = std::sin(theta) / std::sin(theta0); + + NdArray interpQuat = (quat1Copy.toNdArray() * s0) + (inQuat2.toNdArray() * s1); + return Quaternion(interpQuat); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// spherical linear interpolates between the two quaternions + /// + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + [[nodiscard]] Quaternion slerp(const Quaternion& inQuat2, double inPercent) const + { + return slerp(*this, inQuat2, inPercent); + } + + //============================================================================ + // Method Description: + /// returns the quaternion as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string output = "[" + utils::num2str(i()) + ", " + utils::num2str(j()) + ", " + utils::num2str(k()) + + ", " + utils::num2str(s()) + "]\n"; + + return output; + } + + //============================================================================ + // Method Description: + /// returns the direction cosine matrix + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toDCM() const + { + NdArray dcm(3); + + const double q0 = i(); + const double q1 = j(); + const double q2 = k(); + const double q3 = s(); + + const double q0sqr = utils::sqr(q0); + const double q1sqr = utils::sqr(q1); + const double q2sqr = utils::sqr(q2); + const double q3sqr = utils::sqr(q3); + + dcm(0, 0) = q3sqr + q0sqr - q1sqr - q2sqr; + dcm(0, 1) = 2. * (q0 * q1 - q3 * q2); + dcm(0, 2) = 2. * (q0 * q2 + q3 * q1); + dcm(1, 0) = 2. * (q0 * q1 + q3 * q2); + dcm(1, 1) = q3sqr + q1sqr - q0sqr - q2sqr; + dcm(1, 2) = 2. * (q1 * q2 - q3 * q0); + dcm(2, 0) = 2. * (q0 * q2 - q3 * q1); + dcm(2, 1) = 2. * (q1 * q2 + q3 * q0); + dcm(2, 2) = q3sqr + q2sqr - q0sqr - q1sqr; + + return dcm; + } + + //============================================================================ + // Method Description: + /// returns the quaternion as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + auto componentsCopy = components_; + return NdArray(componentsCopy); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the x-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion xRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 1., 0., 0. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// The euler yaw angle in radians + /// + /// @return euler yaw angle in radians + /// + [[nodiscard]] double yaw() const noexcept + { + return std::atan2(2. * (s() * k() + i() * j()), 1. - 2. * (utils::sqr(j()) + utils::sqr(k()))); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the yaw axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion yawRotation(double inAngle) noexcept + { + return { 0., 0., inAngle }; + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the y-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion yRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 0., 1., 0. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the y-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion zRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 0., 0., 1. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// equality operator + /// + /// @param inRhs + /// @return bool + /// + bool operator==(const Quaternion& inRhs) const noexcept + { + const auto comparitor = [](double value1, double value2) noexcept -> bool + { return utils::essentiallyEqual(value1, value2); }; + + return stl_algorithms::equal(components_.begin(), components_.end(), inRhs.components_.begin(), comparitor); + } + + //============================================================================ + // Method Description: + /// equality operator + /// + /// @param inRhs + /// @return bool + /// + bool operator!=(const Quaternion& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + // Method Description: + /// addition assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator+=(const Quaternion& inRhs) noexcept + { + stl_algorithms::transform(components_.begin(), + components_.end(), + inRhs.components_.begin(), + components_.begin(), + std::plus()); // NOLINT(modernize-use-transparent-functors) + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// addition operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator+(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) += inRhs; + } + + //============================================================================ + // Method Description: + /// subtraction assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator-=(const Quaternion& inRhs) noexcept + { + stl_algorithms::transform(components_.begin(), + components_.end(), + inRhs.components_.begin(), + components_.begin(), + std::minus()); // NOLINT(modernize-use-transparent-functors) + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// subtraction operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator-(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) -= inRhs; + } + + //============================================================================ + // Method Description: + /// negative operator + /// + /// @return Quaternion + /// + Quaternion operator-() const noexcept + { + return Quaternion(*this) *= -1.; + } + + //============================================================================ + // Method Description: + /// multiplication assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator*=(const Quaternion& inRhs) noexcept + { + double q0 = inRhs.s() * i(); + q0 += inRhs.i() * s(); + q0 -= inRhs.j() * k(); + q0 += inRhs.k() * j(); + + double q1 = inRhs.s() * j(); + q1 += inRhs.i() * k(); + q1 += inRhs.j() * s(); + q1 -= inRhs.k() * i(); + + double q2 = inRhs.s() * k(); + q2 -= inRhs.i() * j(); + q2 += inRhs.j() * i(); + q2 += inRhs.k() * s(); + + double q3 = inRhs.s() * s(); + q3 -= inRhs.i() * i(); + q3 -= inRhs.j() * j(); + q3 -= inRhs.k() * k(); + + components_[0] = q0; + components_[1] = q1; + components_[2] = q2; + components_[3] = q3; + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// multiplication operator, only useful for multiplying + /// by negative 1, all others will be renormalized back out + /// + /// @param inScalar + /// @return Quaternion + /// + Quaternion& operator*=(double inScalar) noexcept + { + stl_algorithms::for_each(components_.begin(), + components_.end(), + [inScalar](double& component) { component *= inScalar; }); + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator*(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) *= inRhs; + } + + //============================================================================ + // Method Description: + /// multiplication operator, only useful for multiplying + /// by negative 1, all others will be renormalized back out + /// + /// @param inScalar + /// @return Quaternion + /// + Quaternion operator*(double inScalar) const noexcept + { + return Quaternion(*this) *= inScalar; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inVec + /// @return NdArray + /// + NdArray operator*(const NdArray& inVec) const + { + if (inVec.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be a cartesion vector of length = 3."); + } + + const auto vecNorm = norm(inVec).item(); + if (utils::essentiallyEqual(vecNorm, 0.)) + { + return inVec; + } + + const auto p = Quaternion(inVec[0], inVec[1], inVec[2], 0.); + const auto pPrime = *this * p * this->inverse(); + + NdArray rotatedVec = { pPrime.i(), pPrime.j(), pPrime.k() }; + rotatedVec *= vecNorm; + return rotatedVec; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inVec3 + /// @return Vec3 + /// + Vec3 operator*(const Vec3& inVec3) const + { + return *this * inVec3.toNdArray(); + } + + //============================================================================ + // Method Description: + /// division assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator/=(const Quaternion& inRhs) noexcept + { + return *this *= inRhs.conjugate(); + } + + //============================================================================ + // Method Description: + /// division operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator/(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) /= inRhs; + } + + //============================================================================ + // Method Description: + /// IO operator for the Quaternion class + /// + /// @param inOStream + /// @param inQuat + /// @return std::ostream& + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Quaternion& inQuat) + { + inOStream << inQuat.str(); + return inOStream; + } + + private: + //====================================Attributes============================== + std::array components_{ { 0., 0., 0., 1. } }; + + //============================================================================ + // Method Description: + /// renormalizes the quaternion + /// + void normalize() noexcept + { + double sumOfSquares = 0.; + std::for_each(components_.begin(), + components_.end(), + [&sumOfSquares](double component) noexcept -> void + { sumOfSquares += utils::sqr(component); }); + + const double norm = std::sqrt(sumOfSquares); + stl_algorithms::for_each(components_.begin(), + components_.end(), + [norm](double& component) noexcept -> void { component /= norm; }); + } + + //============================================================================ + // Method Description: + /// Converts the euler roll, pitch, yaw angles to quaternion components + /// + /// @ param roll: the euler roll angle in radians + /// @ param pitch: the euler pitch angle in radians + /// @ param yaw: the euler yaw angle in radians + /// + void eulerToQuat(double roll, double pitch, double yaw) noexcept + { + const auto halfPhi = roll / 2.; + const auto halfTheta = pitch / 2.; + const auto halfPsi = yaw / 2.; + + const auto sinHalfPhi = std::sin(halfPhi); + const auto cosHalfPhi = std::cos(halfPhi); + + const auto sinHalfTheta = std::sin(halfTheta); + const auto cosHalfTheta = std::cos(halfTheta); + + const auto sinHalfPsi = std::sin(halfPsi); + const auto cosHalfPsi = std::cos(halfPsi); + + components_[0] = sinHalfPhi * cosHalfTheta * cosHalfPsi; + components_[0] -= cosHalfPhi * sinHalfTheta * sinHalfPsi; + + components_[1] = cosHalfPhi * sinHalfTheta * cosHalfPsi; + components_[1] += sinHalfPhi * cosHalfTheta * sinHalfPsi; + + components_[2] = cosHalfPhi * cosHalfTheta * sinHalfPsi; + components_[2] -= sinHalfPhi * sinHalfTheta * cosHalfPsi; + + components_[3] = cosHalfPhi * cosHalfTheta * cosHalfPsi; + components_[3] += sinHalfPhi * sinHalfTheta * sinHalfPsi; + } + + //============================================================================ + // Method Description: + /// Converts the direction cosine matrix to quaternion components + /// + /// @ param dcm: the direction cosine matrix + /// + void dcmToQuat(const NdArray& dcm) + { + const Shape inShape = dcm.shape(); + if (!(inShape.rows == 3 && inShape.cols == 3)) + { + THROW_INVALID_ARGUMENT_ERROR("input direction cosine matrix must have shape = (3,3)."); + } + + NdArray checks(1, 4); + checks[0] = 1 + dcm(0, 0) + dcm(1, 1) + dcm(2, 2); + checks[1] = 1 + dcm(0, 0) - dcm(1, 1) - dcm(2, 2); + checks[2] = 1 - dcm(0, 0) + dcm(1, 1) - dcm(2, 2); + checks[3] = 1 - dcm(0, 0) - dcm(1, 1) + dcm(2, 2); + + const uint32 maxIdx = argmax(checks).item(); + + switch (maxIdx) + { + case 0: + { + components_[3] = 0.5 * std::sqrt(1 + dcm(0, 0) + dcm(1, 1) + dcm(2, 2)); + components_[0] = (dcm(2, 1) - dcm(1, 2)) / (4 * components_[3]); + components_[1] = (dcm(0, 2) - dcm(2, 0)) / (4 * components_[3]); + components_[2] = (dcm(1, 0) - dcm(0, 1)) / (4 * components_[3]); + + break; + } + case 1: + { + components_[0] = 0.5 * std::sqrt(1 + dcm(0, 0) - dcm(1, 1) - dcm(2, 2)); + components_[1] = (dcm(1, 0) + dcm(0, 1)) / (4 * components_[0]); + components_[2] = (dcm(2, 0) + dcm(0, 2)) / (4 * components_[0]); + components_[3] = (dcm(2, 1) - dcm(1, 2)) / (4 * components_[0]); + + break; + } + case 2: + { + components_[1] = 0.5 * std::sqrt(1 - dcm(0, 0) + dcm(1, 1) - dcm(2, 2)); + components_[0] = (dcm(1, 0) + dcm(0, 1)) / (4 * components_[1]); + components_[2] = (dcm(2, 1) + dcm(1, 2)) / (4 * components_[1]); + components_[3] = (dcm(0, 2) - dcm(2, 0)) / (4 * components_[1]); + + break; + } + case 3: + { + components_[2] = 0.5 * std::sqrt(1 - dcm(0, 0) - dcm(1, 1) + dcm(2, 2)); + components_[0] = (dcm(2, 0) + dcm(0, 2)) / (4 * components_[2]); + components_[1] = (dcm(2, 1) + dcm(1, 2)) / (4 * components_[2]); + components_[3] = (dcm(1, 0) - dcm(0, 1)) / (4 * components_[2]); + + break; + } + } + } + }; +} // namespace nc::rotations diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b6ab6dd3124a172ff2dcdfda679f8ab4996d32fe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Performs Rodriques' rotation formula +/// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //============================================================================ + // Method Description: + /// Performs Rodriques' rotation formula + /// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + /// + /// @param k: the axis to rotate around + /// @param theta: the angle in radians to rotate + /// @param v: the vector to rotate + /// + /// @return Vec3 + /// + inline Vec3 rodriguesRotation(const Vec3& k, double theta, const Vec3& v) noexcept + { + const auto kUnit = k.normalize(); + + const auto vCosTheta = v * std::cos(theta); + + auto kCrossV = kUnit.cross(v); + kCrossV *= std::sin(theta); + + const auto kDotV = kUnit.dot(v); + auto kkDotV = kUnit * kDotV; + kkDotV *= 1 - std::cos(theta); + + auto vec = vCosTheta + kCrossV; + vec += kkDotV; + + return vec; + } + + //============================================================================ + // Method Description: + /// Performs Rodriques' rotation formula + /// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + /// + /// @param k: the axis to rotate around + /// @param theta: the angle in radians to rotate + /// @param v: the vector to rotate + /// + /// @return NdArray + /// + template + NdArray rodriguesRotation(const NdArray& k, double theta, const NdArray& v) + { + return rodriguesRotation(Vec3(k), theta, Vec3(v)).toNdArray(); + } +} // namespace nc::rotations \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/wahbasProblem.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/wahbasProblem.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4fcf74b79579f14764444ba05522a5d8f0254f8c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Rotations/wahbasProblem.hpp @@ -0,0 +1,130 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// In applied mathematics, Wahba's problem, first posed by Grace Wahba in 1965, seeks to +/// find a rotation matrix (special orthogonal matrix) between two coordinate systems from +/// a set of (weighted) vector observations. Solutions to Wahba's problem are often used in +/// satellite attitude determination utilising sensors such as magnetometers and multi-antenna +/// GPS receivers +/// https://en.wikipedia.org/wiki/Wahba%27s_problem +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/ones.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/Linalg/svd.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::rotations +{ + //============================================================================ + // Method Description: + /// Finds a rotation matrix (special orthogonal matrix) between two coordinate + /// systems from a set of (weighted) vector observations. Solutions to Wahba's + /// problem are often used in satellite attitude determination utilising sensors + /// such as magnetometers and multi-antenna GPS receivers + /// https://en.wikipedia.org/wiki/Wahba%27s_problem + /// + /// @param wk: k-th 3-vector measurement in the reference frame (n x 3 matrix) + /// @param vk: corresponding k-th 3-vector measurement in the body frame (n x 3 matrix) + /// @param ak: set of weights for each observation (1 x n or n x 1 matrix) + /// + /// @return NdArray rotation matrix + /// + template + NdArray wahbasProblem(const NdArray& wk, const NdArray& vk, const NdArray& ak) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto wkShape = wk.shape(); + if (wkShape.cols != 3) + { + THROW_INVALID_ARGUMENT_ERROR("wk matrix must be of shape [n, 3]"); + } + + const auto vkShape = vk.shape(); + if (vkShape.cols != 3) + { + THROW_INVALID_ARGUMENT_ERROR("vk matrix must be of shape [n, 3]"); + } + + if (wkShape.rows != vkShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("wk and vk matrices must have the same number of rows"); + } + + if (ak.size() != wkShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("ak matrix must have the same number of elements as wk and vk rows"); + } + + auto b = zeros(3, 3); + const auto cSlice = wk.cSlice(); + for (uint32 row = 0; row < wkShape.rows; ++row) + { + const auto wkVec = wk(row, cSlice); + const auto vkVec = vk(row, cSlice); + b += ak[row] * dot(wkVec.transpose(), vkVec); + } + + NdArray u; + NdArray s; + NdArray vt; + + linalg::svd(b, u, s, vt); + + auto m = eye(3, 3); + m(0, 0) = 1.; + m(1, 1) = 1.; + m(2, 2) = linalg::det(u) * linalg::det(vt.transpose()); + + return dot(u, dot(m, vt)); + } + + //============================================================================ + // Method Description: + /// Finds a rotation matrix (special orthogonal matrix) between two coordinate + /// systems from a set of (weighted) vector observations. Solutions to Wahba's + /// problem are often used in satellite attitude determination utilising sensors + /// such as magnetometers and multi-antenna GPS receivers + /// https://en.wikipedia.org/wiki/Wahba%27s_problem + /// + /// @param wk: k-th 3-vector measurement in the reference frame + /// @param vk: corresponding k-th 3-vector measurement in the body frame + /// + /// @return NdArray rotation matrix + /// + template + NdArray wahbasProblem(const NdArray& wk, const NdArray& vk) + { + const auto ak = ones({ 1, wk.shape().rows }); + return wahbasProblem(wk, vk, ak); + } +} // namespace nc::rotations diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f0182035c2a35a075e19b8a5ce8d83c098effd54 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Special/airy_ai.hpp" +#include "NumCpp/Special/airy_ai_prime.hpp" +#include "NumCpp/Special/airy_bi.hpp" +#include "NumCpp/Special/airy_bi_prime.hpp" +#include "NumCpp/Special/bernoulli.hpp" +#include "NumCpp/Special/bessel_in.hpp" +#include "NumCpp/Special/bessel_in_prime.hpp" +#include "NumCpp/Special/bessel_jn.hpp" +#include "NumCpp/Special/bessel_jn_prime.hpp" +#include "NumCpp/Special/bessel_kn.hpp" +#include "NumCpp/Special/bessel_kn_prime.hpp" +#include "NumCpp/Special/bessel_yn.hpp" +#include "NumCpp/Special/bessel_yn_prime.hpp" +#include "NumCpp/Special/beta.hpp" +#include "NumCpp/Special/cnr.hpp" +#include "NumCpp/Special/comp_ellint_1.hpp" +#include "NumCpp/Special/comp_ellint_2.hpp" +#include "NumCpp/Special/comp_ellint_3.hpp" +#include "NumCpp/Special/cyclic_hankel_1.hpp" +#include "NumCpp/Special/cyclic_hankel_2.hpp" +#include "NumCpp/Special/digamma.hpp" +#include "NumCpp/Special/ellint_1.hpp" +#include "NumCpp/Special/ellint_2.hpp" +#include "NumCpp/Special/ellint_3.hpp" +#include "NumCpp/Special/erf.hpp" +#include "NumCpp/Special/erf_inv.hpp" +#include "NumCpp/Special/erfc.hpp" +#include "NumCpp/Special/erfc_inv.hpp" +#include "NumCpp/Special/expint.hpp" +#include "NumCpp/Special/factorial.hpp" +#include "NumCpp/Special/gamma.hpp" +#include "NumCpp/Special/gamma1pm1.hpp" +#include "NumCpp/Special/log_gamma.hpp" +#include "NumCpp/Special/pnr.hpp" +#include "NumCpp/Special/polygamma.hpp" +#include "NumCpp/Special/prime.hpp" +#include "NumCpp/Special/riemann_zeta.hpp" +#include "NumCpp/Special/softmax.hpp" +#include "NumCpp/Special/spherical_bessel_jn.hpp" +#include "NumCpp/Special/spherical_bessel_yn.hpp" +#include "NumCpp/Special/spherical_hankel_1.hpp" +#include "NumCpp/Special/spherical_hankel_2.hpp" +#include "NumCpp/Special/trigamma.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9c4be23527cfdaf2bf406837fbd0c5897db612e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_ai(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_ai(inValue); + } + + //============================================================================ + // Method Description: + /// The first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_ai(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_ai(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..95bb3622b012cc56473050ea31a8904f7127fd27 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_ai_prime.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The derivative of the first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_ai_prime(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_ai_prime(inValue); + } + + //============================================================================ + // Method Description: + /// The derivative of the first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_ai_prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_ai_prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi.hpp new file mode 100644 index 0000000000000000000000000000000000000000..6efa8f9cd147ba49c327264f1be5a4c8e168effb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_bi(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_bi(inValue); + } + + //============================================================================ + // Method Description: + /// The second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_bi(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_bi(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..0787b783743bed6700296a77157f8fd6310a589b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/airy_bi_prime.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The derivative of the second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_bi_prime(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_bi_prime(inValue); + } + + //============================================================================ + // Method Description: + /// The derivative of the second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_bi_prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_bi_prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bernoulli.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bernoulli.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9abb0377d8408ee445160f7e12a3b34f4b9c855b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bernoulli.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/bernoulli.hpp" + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Both return the nth Bernoulli number B2n. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n + /// @return double + /// + inline double bernoilli(uint32 n) + { + if (n == 1) + { + return 0.5; + } + if (n % 2 != 0) + { + return 0.; + } + + return boost::math::bernoulli_b2n(n / 2); + } + + //============================================================================ + // Method Description: + /// Both return the nth Bernoulli number B2n. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray bernoilli(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> double { return bernoilli(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b75b3564ea72844831dd3c2852d9078ce725fcb5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_in(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_i(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_i(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_in(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_in(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..eb7a99c3fea75f67feabaa505f01bcaf93696871 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_in_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_in_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_i_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_in_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_in_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f23171ff5b0463e7751f15e10e63732b140024ef --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_jn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_j(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_j(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_jn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_jn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..b4db65fe73e4b809261fb592f2e3c09b6e503195 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_jn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_jn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_j_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_jn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_jn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8b81fb79b49d427b075e8ba7b86f9322f4b97974 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_kn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_k(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_k(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_kn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_kn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..248a980b0da92486d2529a851476c97f9051f8e9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_kn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_kn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_k_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the second kind + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_kn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_kn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..e8ce29c94f414d6d40b3a63301a91539ccbf7489 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_yn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_neumann(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_neumann(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_yn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_yn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn_prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn_prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..41fe1f6481c0c939d8d84ea626cfb800f7336a00 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/bessel_yn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_yn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_neumann_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_yn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_yn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/beta.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/beta.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f9df74983c0c451adf52ca6feafd48bc905c83ac --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/beta.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/beta.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The beta function. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param a + /// @param b + /// @return calculated-result-type + /// + template + auto beta(dtype1 a, dtype2 b) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::beta(a, b); +#else + return boost::math::beta(a, b); +#endif + } + + //============================================================================ + // Method Description: + /// The beta function. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayA + /// @param inArrayB + /// @return NdArray + /// + template + auto beta(const NdArray& inArrayA, const NdArray& inArrayB) + { + NdArray returnArray(inArrayB.shape()); + + stl_algorithms::transform( + inArrayA.cbegin(), + inArrayA.cend(), + inArrayB.cbegin(), + returnArray.begin(), + [](dtype1 a, dtype2 b) -> auto{ return beta(a, b); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cnr.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cnr.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5a1f7e61e584f1cb7ba483ac66183619ef027db6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cnr.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/factorial.hpp" +#include "NumCpp/Special/pnr.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the number of combinations of n choose r. C(n, r) + /// + /// @param n: the total number of items + /// @param r: the number of items taken + /// @return double + /// + inline double cnr(uint32 n, uint32 r) + { + return pnr(n, r) / factorial(r); + } +} // namespace nc::special diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8b9802a6b595d41589eabcdb8255804889690248 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_1.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_1.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the first kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @return calculated-result-type + /// + template + auto comp_ellint_1(dtype inK) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_1(inK); +#else + return boost::math::ellint_1(inK); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the first kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @return NdArray + /// + template + auto comp_ellint_1(const NdArray& inArrayK) + { + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + returnArray.begin(), + [](dtype inK) -> auto{ return comp_ellint_1(inK); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..cd28df573edbd0e7484385fe8cf646f88ee61c24 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_2.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_2.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the second kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @return calculated-result-type + /// + template + auto comp_ellint_2(dtype inK) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_2(inK); +#else + return boost::math::ellint_2(inK); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the second kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @return NdArray + /// + template + auto comp_ellint_2(const NdArray& inArrayK) + { + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + returnArray.begin(), + [](dtype inK) -> auto{ return comp_ellint_2(inK); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_3.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_3.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8b649ec5854fac56fb231db221eb319491415680 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/comp_ellint_3.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_3.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the third kind of k and v. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inV: elliptic characteristic + /// @return calculated-result-type + /// + template + auto comp_ellint_3(dtype1 inK, dtype2 inV) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_3(inK, inV); +#else + return boost::math::ellint_3(inK, inV); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the third kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: the order of the bessel function + /// @param inArrayV: elliptic characteristic + /// @return NdArray + /// + template + auto comp_ellint_3(const NdArray& inArrayK, const NdArray& inArrayV) + { + if (inArrayK.size() != inArrayV.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayk and inArrayV must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayV.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inV) -> auto{ return comp_ellint_3(inK, inV); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..03c4a3a3d2a6f840554e19a2d5aa4a17357e6c84 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return std::complex + /// + template + auto cyclic_hankel_1(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_hankel_1(inV, inX); + } + + //============================================================================ + // Method Description: + /// Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input array + /// @return NdArray + /// + template + auto cyclic_hankel_1(dtype1 inV, const NdArray& inX) + { + NdArray returnArray(inX.shape()); + + stl_algorithms::transform( + inX.cbegin(), + inX.cend(), + returnArray.begin(), + [inV](dtype2 x) -> auto{ return cyclic_hankel_1(inV, x); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..5b39c5910f899e225590b991d51fc8a441fb3776 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return std::complex<> + /// + template + auto cyclic_hankel_2(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_hankel_2(inV, inX); + } + + //============================================================================ + // Method Description: + /// Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input array + /// @return NdArray + /// + template + auto cyclic_hankel_2(dtype1 inV, const NdArray& inX) + { + NdArray returnArray(inX.shape()); + + stl_algorithms::transform( + inX.cbegin(), + inX.cend(), + returnArray.begin(), + [inV](dtype2 x) -> auto{ return cyclic_hankel_2(inV, x); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/digamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/digamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ceace1357afda42903b73d8feeff38d16493c635 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/digamma.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/digamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the digamma or psi function of inValue. Digamma is defined as the + /// logarithmic derivative of the gamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto digamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::digamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the digamma or psi function of values in inArray. Digamma is defined as the + /// logarithmic derivative of the gamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto digamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return digamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ca26b599b55faec8f725f544c0d36bccf4566f02 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_1.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_1.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the first kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_1(dtype1 inK, dtype2 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_1(inK, inP); +#else + return boost::math::ellint_1(inK, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the first kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_1(const NdArray& inArrayK, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayP.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inP) -> auto{ return ellint_1(inK, inP); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7c1a8c27bf885a6f14af80e5f7b8f9e81d0c59f4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_2.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_2.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_2(dtype1 inK, dtype2 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_2(inK, inP); +#else + return boost::math::ellint_2(inK, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_2(const NdArray& inArrayK, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayP.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inP) -> auto{ return ellint_2(inK, inP); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_3.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_3.hpp new file mode 100644 index 0000000000000000000000000000000000000000..79581737810f413ccb53cca374b06b06bb1f61a4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/ellint_3.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_3.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k, v, and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inV: elliptic characteristic + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_3(dtype1 inK, dtype2 inV, dtype3 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + STATIC_ASSERT_ARITHMETIC(dtype3); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_3(inK, inV, inP); +#else + return boost::math::ellint_3(inK, inV, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k, v, and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: the order of the bessel function + /// @param inArrayV: elliptic characteristic + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_3(const NdArray& inArrayK, const NdArray& inArrayV, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayV.size() || inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK, inArrayV, and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + for (uint32 i = 0; i < inArrayK.size(); ++i) + { + returnArray[i] = ellint_3(inArrayK[i], inArrayV[i], inArrayP[i]); + } + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..60941690b25b64e001a23fde7bded879d5b74997 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Calculate the error function of all elements in the input array. + /// Integral (from [-x, x]) of np.exp(np.power(-t, 2)) dt, multiplied by 1/np.pi. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erf(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erf(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the error function of all elements in the input array. + /// Integral (from [-x, x]) of np.exp(np.power(-t, 2)) dt, multiplied by 1/np.pi. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erf(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf_inv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf_inv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8ca9f883ba63f529f93cd4d08d35a6c967870e9a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erf_inv.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the inverse error function of z, that is a value x such that: + /// z = erf(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erf_inv(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erf_inv(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the inverse error function of z, that is a value x such that: + /// z = erf(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erf_inv(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erf_inv(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9d78d57fa0fee95dfd38d98ed5a8f6d94cf8488d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the complement of the error function of inValue. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erfc(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erfc(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the element-wise complement of the error + /// function of inValue. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erfc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erfc(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc_inv.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc_inv.hpp new file mode 100644 index 0000000000000000000000000000000000000000..21374199a30cc4a7a5e51fd0ab3a6807c4c036e1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/erfc_inv.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the inverse complentary error function of z, that is a value x such that: + /// z = erfc(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erfc_inv(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erfc_inv(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the inverse complementary error function of z, that is a value x such that: + /// z = erfc(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erfc_inv(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erfc_inv(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/expint.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/expint.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8a69e3370fb40c73e5097b5c15902091cb7e5422 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/expint.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/expint.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Exponential integral Ei. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inX: value + /// @return calculated-result-type + /// + template + auto expint(dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::expint(inX); +#else + return boost::math::expint(inX); +#endif + } + + //============================================================================ + // Method Description: + /// Exponential integral Ei. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayX: value + /// @return NdArray + /// + template + auto expint(const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [](dtype inX) -> auto{ return expint(inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/factorial.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/factorial.hpp new file mode 100644 index 0000000000000000000000000000000000000000..70c1b8be8af77b3ef6e065b88c88f6fda3f8a795 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/factorial.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/math/special_functions/factorials.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the factorial of the input value + /// + /// @param inValue + /// @return double + /// + inline double factorial(uint32 inValue) + { +#ifndef NUMCPP_NO_USE_BOOST + if (inValue <= boost::math::max_factorial::value) + { + return boost::math::factorial(inValue); + } + + return std::numeric_limits::infinity(); +#else + double result = 1.; + for (uint32 i = 2; i <= inValue; ++i) + { + result *= static_cast(i); + } + + return result; +#endif + } + + //============================================================================ + // Method Description: + /// Returns the factorial of the input value + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray factorial(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> double { return factorial(inValue); }); + + return returnArray; + } +} // namespace nc::special diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..ef9fc96ba8bec7cdf3a59acff0a5ce50fd22daa9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the "true gamma" of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto gamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::tgamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the "true gamma" of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto gamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return gamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma1pm1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma1pm1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7b4748b6e19d74501c7a6382a820d78273dea5dd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/gamma1pm1.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the true gamma(dz + 1) - 1 of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto gamma1pm1(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::tgamma1pm1(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the true gamma(dz + 1) - 1 of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto gamma1pm1(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return gamma1pm1(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/log_gamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/log_gamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d9830e3acc52331c89594e552bb8bfcb28714020 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/log_gamma.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns natural log of the true gamma of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto log_gamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::lgamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns natural log of the true gamma of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto log_gamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return log_gamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/pnr.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/pnr.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2ee697e83ff3a1650c620a1d063d1477b1384744 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/pnr.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/factorial.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/math/special_functions/factorials.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the number of permutaions of n choose r. P(n, r) + /// + /// @param n: the total number of items + /// @param r: the number of items taken + /// @return double + /// + inline double pnr(uint32 n, uint32 r) + { + if (r > n) + { + return 0.; + } + else if (r == n) + { + return factorial(n); + } + + double combinations = 1.; + +#ifndef NUMCPP_NO_USE_BOOST + if (n <= boost::math::max_factorial::value) + { + const double nFactorial = factorial(n); + const double nMinusRFactoral = factorial(n - r); + + combinations = nFactorial / nMinusRFactoral; + } + else + { +#endif + const uint32 lower = n - r + 1; + combinations = static_cast(lower); + for (uint32 i = lower + 1; i <= n; ++i) + { + combinations *= static_cast(i); + } +#ifndef NUMCPP_NO_USE_BOOST + } +#endif + + return combinations; + } +} // namespace nc::special diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/polygamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/polygamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..4d244aae0bb7218f0514a9c5fe7e2dc94d84eab8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/polygamma.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/polygamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the polygamma function of inValue. Polygamma is defined as the + /// n'th derivative of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth derivative + /// @param inValue + /// @return calculated-result-type + /// + template + auto polygamma(uint32 n, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::polygamma(n, inValue); + } + + //============================================================================ + // Method Description: + /// Returns the polygamma function of the values in inArray. Polygamma is defined as the + /// n'th derivative of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth derivative + /// @param inArray + /// @return NdArray + /// + template + auto polygamma(uint32 n, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [n](dtype inValue) -> auto{ return polygamma(n, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/prime.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/prime.hpp new file mode 100644 index 0000000000000000000000000000000000000000..269a8ce9492344e29b9bcdc3195762350cd1ca6d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/prime.hpp @@ -0,0 +1,85 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/prime.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The function prime provides fast table lookup to the first 10000 prime numbers + /// (starting from 2 as the zeroth prime: as 1 isn't terribly useful in practice). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth prime number to return + /// @return uint32 + /// + inline uint32 prime(uint32 n) + { + if (n > boost::math::max_prime) + { + THROW_INVALID_ARGUMENT_ERROR("input n must be less than or equal to " + + std::to_string(boost::math::max_prime)); + } + + return boost::math::prime(n); + } + + //============================================================================ + // Method Description: + /// The function prime provides fast table lookup to the first 10000 prime numbers + /// (starting from 2 as the zeroth prime: as 1 isn't terribly useful in practice). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> uint32 { return prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/riemann_zeta.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/riemann_zeta.hpp new file mode 100644 index 0000000000000000000000000000000000000000..40cf19d8c0d8e5c04c914354d33a02b45fb30ef0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/riemann_zeta.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/zeta.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The Riemann Zeta function + /// https://en.wikipedia.org/wiki/Riemann_zeta_function + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto riemann_zeta(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::riemann_zeta(inValue); +#else + return boost::math::zeta(inValue); +#endif + } + + //============================================================================ + // Method Description: + /// The Riemann Zeta function + /// https://en.wikipedia.org/wiki/Riemann_zeta_function + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArray + /// @return NdArray + /// + template + auto riemann_zeta(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return riemann_zeta(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/softmax.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/softmax.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3f1489682c182bb8e089ae5a8ec4ecea950cb65f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/softmax.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/exp.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The softmax function transforms each element of a collection by computing + /// the exponential of each element divided by the sum of the exponentials of all + /// the elements. That is, if x is a one-dimensional numpy array: + /// softmax(x) = np.exp(x)/sum(np.exp(x)) + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray softmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto returnArray = exp(inArray).template astype(); + returnArray /= static_cast(returnArray.sum().item()); + return returnArray; + } + case Axis::COL: + { + auto returnArray = exp(inArray).template astype(); + auto expSums = returnArray.sum(inAxis); + + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + const auto rowExpSum = static_cast(expSums[row]); + stl_algorithms::for_each(returnArray.begin(row), + returnArray.end(row), + [rowExpSum](double& value) { value /= rowExpSum; }); + } + + return returnArray; + } + case Axis::ROW: + { + auto returnArray = exp(inArray.transpose()).template astype(); + auto expSums = returnArray.sum(Axis::COL); + + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + const auto rowExpSum = static_cast(expSums[row]); + stl_algorithms::for_each(returnArray.begin(row), + returnArray.end(row), + [rowExpSum](double& value) { value /= rowExpSum; }); + } + + return returnArray.transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc::special diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d0e07cb67e9616a91cc713b07a035a76badfecdd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_bessel_jn(uint32 inV, dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::sph_bessel(inV, inX); +#else + return boost::math::sph_bessel(inV, inX); +#endif + } + + //============================================================================ + // Method Description: + /// Spherical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto spherical_bessel_jn(uint32 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype inX) -> auto{ return spherical_bessel_jn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp new file mode 100644 index 0000000000000000000000000000000000000000..50ffb261346263e8b3edf3143d5110eb93ea2578 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_bessel_yn(uint32 inV, dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::sph_neumann(inV, inX); +#else + return boost::math::sph_neumann(inV, inX); +#endif + } + + //============================================================================ + // Method Description: + /// Spherical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto spherical_bessel_yn(uint32 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype inX) -> auto{ return spherical_bessel_yn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_1.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_1.hpp new file mode 100644 index 0000000000000000000000000000000000000000..33d9293e5d5ffa925794994b78c3df4d9520e804 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_1.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_hankel_1(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::sph_hankel_1(inV, inX); + } + + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArray: the input values + /// @return NdArray + /// + template + auto spherical_hankel_1(dtype1 inV, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inV](dtype2 inValue) -> auto{ return spherical_hankel_1(inV, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..264d5ab689fe04fac793d5dac145ee31796e18a3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/spherical_hankel_2.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return double + /// + template + std::complex spherical_hankel_2(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::sph_hankel_2(inV, inX); + } + + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArray: the input value + /// @return NdArray + /// + template + auto spherical_hankel_2(dtype1 inV, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inV](dtype2 inValue) -> auto{ return spherical_hankel_2(inV, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/trigamma.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/trigamma.hpp new file mode 100644 index 0000000000000000000000000000000000000000..f0a16368c5613a803939ea5e53c57face2b6b64b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Special/trigamma.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/trigamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the trigamma function of x. Trigamma is defined as the derivative + /// of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto trigamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::trigamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the trigamma function of x. Trigamma is defined as the derivative + /// of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto trigamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return trigamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d48806984272e2c7bc6cec6c49da176438fd8877 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils.hpp @@ -0,0 +1,40 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Usefull utility type functions +/// +#pragma once + +#include "NumCpp/Utils/cube.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/gaussian.hpp" +#include "NumCpp/Utils/gaussian1d.hpp" +#include "NumCpp/Utils/interp.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" +#include "NumCpp/Utils/powerf.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Utils/timeit.hpp" +#include "NumCpp/Utils/value2str.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/cube.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/cube.hpp new file mode 100644 index 0000000000000000000000000000000000000000..00d31efe17b0d6b21ac5e691ff3a3ffba57937d5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/cube.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Cubes in input value +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Cubes in input value + /// + /// @param inValue + /// + /// @return cubed value + /// + template + constexpr dtype cube(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return inValue * inValue * inValue; + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqual.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqual.hpp new file mode 100644 index 0000000000000000000000000000000000000000..20157f76e06c1e35babebad1e90516e609a3ddb0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqual.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// tests that 2 floating point values are "essentially equal" +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// tests that 2 integer values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept + { + return inValue1 == inValue2; + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// @param inEpsilon + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2, dtype inEpsilon) noexcept + { + const auto absValue1 = std::abs(inValue1); + const auto absValue2 = std::abs(inValue2); + return std::abs(inValue1 - inValue2) <= ((absValue1 > absValue2 ? absValue2 : absValue1) * std::abs(inEpsilon)); + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept + { + return essentiallyEqual(inValue1, inValue2, DtypeInfo::epsilon()); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp new file mode 100644 index 0000000000000000000000000000000000000000..3c1ad47df1e2f8568187d1a00d19e6c2aeef8ebd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp @@ -0,0 +1,86 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// tests that 2 floating point values are "essentially equal" +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// tests that 2 complex values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, const std::complex& inValue2) noexcept + { + return inValue1 == inValue2; + } + + //============================================================================ + /// tests that 2 complex values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// @param inEpsilon + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, + const std::complex& inValue2, + const std::complex& inEpsilon) noexcept + { + const auto absValue1 = std::abs(inValue1); + const auto absValue2 = std::abs(inValue2); + return std::abs(inValue1 - inValue2) <= ((absValue1 > absValue2 ? absValue2 : absValue1) * std::abs(inEpsilon)); + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, const std::complex& inValue2) noexcept + { + return essentiallyEqual(inValue1, inValue2, DtypeInfo>::epsilon()); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian.hpp new file mode 100644 index 0000000000000000000000000000000000000000..53a3b56c95e5624ed707b1e43048e22de0bee68f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// samples a 2D gaussian of mean zero and input STD sigma +/// +#pragma once + +#include + +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::utils +{ + //============================================================================ + // Method Description: + /// samples a 2D gaussian of mean zero and input STD sigma + /// + /// @param inX + /// @param inY + /// @param inSigma + /// + /// @return dtype + /// + inline double gaussian(double inX, double inY, double inSigma) noexcept + { + double exponent = sqr(inX) + sqr(inY); + exponent /= 2; + exponent /= sqr(inSigma); + return std::exp(-exponent); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian1d.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian1d.hpp new file mode 100644 index 0000000000000000000000000000000000000000..543545a5716ac125f58acd0ad2ca97198f6c1331 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/gaussian1d.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// samples a 1D gaussian of input mean and sigma +/// +#pragma once + +#include + +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::utils +{ + //============================================================================ + // Method Description: + /// samples a 1D gaussian of input mean and sigma + /// + /// @param inX + /// @param inMu + /// @param inSigma + /// + /// @return dtype + /// + inline double gaussian1d(double inX, double inMu, double inSigma) noexcept + { + double exponent = sqr(inX - inMu); + exponent /= 2; + exponent /= sqr(inSigma); + return std::exp(-exponent); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/interp.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/interp.hpp new file mode 100644 index 0000000000000000000000000000000000000000..87ef6891b085dcf902896905223550cd92461daa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/interp.hpp @@ -0,0 +1,45 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Returns the linear interpolation between two points +/// +#pragma once + +namespace nc::utils +{ + //============================================================================ + /// Returns the linear interpolation between two points + /// + /// @param inValue1 + /// @param inValue2 + /// @param inPercent + /// + /// @return linear interpolated point + /// + constexpr double interp(double inValue1, double inValue2, double inPercent) noexcept + { + return inValue1 * (1. - inPercent) + inValue2 * inPercent; + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/num2str.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/num2str.hpp new file mode 100644 index 0000000000000000000000000000000000000000..00f0ccc8806a440823afb7b28289ef747e69102f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/num2str.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Converts the number into a string +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Converts the number into a string + /// + /// @param inNumber + /// + /// @return std::string + /// + template + std::string num2str(dtype inNumber) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::to_string(inNumber); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/power.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/power.hpp new file mode 100644 index 0000000000000000000000000000000000000000..8d4295535ec4b35aa4c9122beed245c86baac401 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/power.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raises the input value to an integer power +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Raises the input value to an integer power + /// + /// @param inValue + /// @param inPower + /// + /// @return inValue raised to inPower + /// + template + dtype power(dtype inValue, uint8 inPower) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inPower == 0) + { + return static_cast(1); + } + + dtype returnVal = inValue; + for (uint8 exponent = 1; exponent < inPower; ++exponent) + { + returnVal *= inValue; + } + return returnVal; + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/powerf.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/powerf.hpp new file mode 100644 index 0000000000000000000000000000000000000000..73e36e6cfde00f19c821000f70caf5c1a0cb5cd4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/powerf.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raises the input value to a floating point power +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Raises the input value to a floating point power + /// + /// @param inValue + /// @param inPower + /// + /// @return inValue raised to inPower + /// + template + auto powerf(dtype1 inValue, const dtype2 inPower) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype1); + + return std::pow(inValue, inPower); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/sqr.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/sqr.hpp new file mode 100644 index 0000000000000000000000000000000000000000..7d7bd0462579f1a0388aa9ad805a2b0be17a49f8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/sqr.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Squares in input value +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Squares in input value + /// + /// @param inValue + /// + /// @return squared value + /// + template + constexpr dtype sqr(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return inValue * inValue; + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/timeit.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/timeit.hpp new file mode 100644 index 0000000000000000000000000000000000000000..fdcf31e11c8789917852a4efd537c5104c40cf91 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/timeit.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Function profiling/timing +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Timer.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::utils +{ + namespace timeit_detail + { + /// @brief Result statistics of a timeit run + template + struct Result + { + TimeUnit min{}; + TimeUnit max{}; + TimeUnit mean{}; + }; + + template + std::ostream& operator<<(std::ostream& os, const Result result) + { + std::string unit{}; + if constexpr (std::is_same::value) + { + unit = " hours"; + } + else if constexpr (std::is_same::value) + { + unit = " minutes"; + } + else if constexpr (std::is_same::value) + { + unit = " seconds"; + } + else if constexpr (std::is_same::value) + { + unit = " milliseconds"; + } + else if constexpr (std::is_same::value) + { + unit = " microseconds"; + } + else if constexpr (std::is_same::value) + { + unit = " nanoseconds"; + } + else + { + unit = " time units of some sort"; + } + + os << "Timeit results:\n"; + os << "\tmin: " << result.min.count() << unit << "\n"; + os << "\tmax: " << result.max.count() << unit << "\n"; + os << "\tmean: " << result.mean.count() << unit << "\n"; + + return os; + } + } // namespace timeit_detail + + //============================================================================ + /// Timing of a function + /// + /// @param numIterations: number of iterations for the timing statistics + /// @param printResults: bool true to print the results + /// @param function: the function to time + /// @param args: the arguements that are forwarded to the function input + /// + /// @return timing statistics + /// + template + timeit_detail::Result + timeit(uint32 numIterations, bool printResults, Function function, Args&&... args) noexcept + { + auto result = timeit_detail::Result{}; + auto timer = Timer{}; + + for (uint32 i = 0; i < numIterations; ++i) + { + if (i == 0) + { + result.min = TimeUnit::max(); + } + + timer.tic(); + + using ResultType = std::invoke_result_t; + if constexpr (std::is_same_v) + { + function(std::forward(args)...); + } + else + { + // cppcheck-suppress redundantAssignment + [[maybe_unused]] const ResultType functionResult = function(std::forward(args)...); + } + + const auto elapsedTime = timer.toc(false); + + result.mean = result.mean + elapsedTime; + result.min = std::min(result.min, elapsedTime); + result.max = std::max(result.max, elapsedTime); + } + + result.mean = result.mean / numIterations; + + if (printResults) + { + std::cout << result; + } + + return result; + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/value2str.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/value2str.hpp new file mode 100644 index 0000000000000000000000000000000000000000..71a4d064890bda2491d8ed6f69172ebe27537703 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Utils/value2str.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Converts the number into a string +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Converts the value into a string + /// + /// @param inValue + /// + /// @return std::string + /// + template + std::string value2str(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::stringstream ss; + ss << inValue; + return ss.str(); + } +} // namespace nc::utils diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector.hpp new file mode 100644 index 0000000000000000000000000000000000000000..2ec9ace17f3ced4c1c3f2ce357119c622a2346f5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Vector/Vec2.hpp" +#include "NumCpp/Vector/Vec3.hpp" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec2.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec2.hpp new file mode 100644 index 0000000000000000000000000000000000000000..9b94d074f0d6fe310eb4de44def2ebe04ade84ac --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec2.hpp @@ -0,0 +1,560 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple 2D Vector class +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/interp.hpp" + +//==================================================================================== + +namespace nc +{ + //================================================================================ + // Class Description: + /// Holds a 2D vector + class Vec2 + { + public: + //====================================Attributes============================== + double x{ 0. }; + double y{ 0. }; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + constexpr Vec2() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inX: the x component + /// @param inY: the y component + /// + constexpr Vec2(double inX, double inY) noexcept : + x(inX), + y(inY) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + Vec2(const std::initializer_list& inList) + { + if (inList.size() != 2) + { + THROW_INVALID_ARGUMENT_ERROR("input initializer list must have a size = 2"); + } + + x = *inList.begin(); + y = *(inList.begin() + 1); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ndArray + /// + Vec2(const NdArray& ndArray) + { + if (ndArray.size() != 2) + { + THROW_INVALID_ARGUMENT_ERROR("input NdArray must have a size = 2"); + } + + x = ndArray[0]; + y = ndArray[1]; + } + + //============================================================================ + // Method Description: + /// Returns the angle between the two vectors + /// + /// @param otherVec + /// @return the angle in radians + /// + [[nodiscard]] double angle(const Vec2& otherVec) const noexcept + { + double dotProduct = dot(otherVec); + dotProduct /= norm(); + dotProduct /= otherVec.norm(); + + // clamp the value to the acos range just to be safe + dotProduct = std::max(std::min(dotProduct, 1.), -1.); + + return std::acos(dotProduct); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the vector with its magnitude clamped + /// to maxLength + /// + /// @param maxLength + /// @return Vec2 + /// + [[nodiscard]] Vec2 clampMagnitude(double maxLength) const noexcept + { + const double magnitude = norm(); + if (magnitude <= maxLength) + { + return *this; + } + + Vec2 returnVec = Vec2(*this).normalize(); + returnVec *= maxLength; + return returnVec; + } + + //============================================================================ + // Method Description: + /// Returns the distance between the two vectors + /// + /// @param otherVec + /// @return the distance (equivalent to (a - b).norm() + /// + [[nodiscard]] double distance(const Vec2& otherVec) const noexcept + { + return (Vec2(*this) -= otherVec).norm(); + } + + //============================================================================ + // Method Description: + /// Returns the dot product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] double dot(const Vec2& otherVec) const noexcept + { + return x * otherVec.x + y * otherVec.y; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, -1] + /// + /// @return Vec2 + /// + static constexpr Vec2 down() noexcept + { + return Vec2(0., -1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [-1, 0] + /// + /// @return Vec2 + /// + static constexpr Vec2 left() noexcept + { + return Vec2(-1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Linearly interpolates between two vectors + /// + /// @param otherVec + /// @param t the amount to interpolate by (clamped from [0, 1]); + /// @return Vec2 + /// + [[nodiscard]] Vec2 lerp(const Vec2& otherVec, double t) const noexcept + { + t = std::max(std::min(t, 1.), 0.); + + Vec2 trajectory = otherVec; + trajectory -= *this; + const double xInterp = utils::interp(0., trajectory.x, t); + const double yInterp = utils::interp(0., trajectory.y, t); + + return Vec2(*this) += Vec2(xInterp, yInterp); + } + + //============================================================================ + // Method Description: + /// Returns the magnitude of the vector + /// + /// @return magnitude of the vector + /// + [[nodiscard]] double norm() const noexcept + { + return std::hypot(x, y); + } + + //============================================================================ + // Method Description: + /// Returns a new normalized Vec2 + /// + /// @return Vec2 + /// + [[nodiscard]] Vec2 normalize() const noexcept + { + return Vec2(*this) /= norm(); + } + + //============================================================================ + // Method Description: + /// Projects the vector onto the input vector + /// + /// @param otherVec + /// @return Vec2 + /// + [[nodiscard]] Vec2 project(const Vec2& otherVec) const noexcept + { + const double projectedMagnitude = norm() * std::cos(angle(otherVec)); + return otherVec.normalize() *= projectedMagnitude; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [1, 0] + /// + /// @return Vec2 + /// + static constexpr Vec2 right() noexcept + { + return Vec2(1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string toString() const + { + std::stringstream stream; + stream << "Vec2[" << x << ", " << y << "]"; + return stream.str(); + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + NdArray returnArray = { x, y }; + return returnArray.transpose(); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 1] + /// + /// @return Vec2 + /// + static constexpr Vec2 up() noexcept + { + return Vec2(0., 1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const Vec2& rhs) const noexcept + { + return utils::essentiallyEqual(x, rhs.x) && utils::essentiallyEqual(y, rhs.y); + } + + //============================================================================ + // Method Description: + /// Not Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const Vec2& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator+=(double scalar) noexcept + { + x += scalar; + y += scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param rhs + /// @return Vec2 + /// + Vec2& operator+=(const Vec2& rhs) noexcept + { + x += rhs.x; + y += rhs.y; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator-=(double scalar) noexcept + { + x -= scalar; + y -= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param rhs + /// @return Vec2 + /// + Vec2& operator-=(const Vec2& rhs) noexcept + { + x -= rhs.x; + y -= rhs.y; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator*=(double scalar) noexcept + { + x *= scalar; + y *= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator/=(double scalar) noexcept + { + x /= scalar; + y /= scalar; + return *this; + } + }; + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(double lhs, const Vec2& rhs) noexcept + { + return Vec2(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(const Vec2& lhs, const Vec2& rhs) noexcept + { + return Vec2(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Returns the negative vector + /// + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& vec) noexcept + { + return Vec2(-vec.x, -vec.y); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(double lhs, const Vec2& rhs) noexcept + { + return -Vec2(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& lhs, const Vec2& rhs) noexcept + { + return Vec2(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator*(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) *= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator*(double lhs, const Vec2& rhs) noexcept + { + return Vec2(rhs) *= lhs; + } + + //============================================================================ + // Method Description: + /// Vector mulitplication (dot product) + /// + /// @param lhs + /// @param rhs + /// @return dot product + /// + /// + inline double operator*(const Vec2& lhs, const Vec2& rhs) noexcept + { + return lhs.dot(rhs); + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator/(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) /= rhs; + } + + //============================================================================ + // Method Description: + /// stream output operator + /// + /// @param stream + /// @param vec + /// @return std::ostream + /// + inline std::ostream& operator<<(std::ostream& stream, const Vec2& vec) + { + stream << vec.toString() << std::endl; + return stream; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec3.hpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec3.hpp new file mode 100644 index 0000000000000000000000000000000000000000..83c725b586fa5f025e0311cd33746cf43eaa452f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/NumCpp/Vector/Vec3.hpp @@ -0,0 +1,625 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple 3D Vector class +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Functions/hypot.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/interp.hpp" +#include "NumCpp/Vector/Vec2.hpp" + +//==================================================================================== + +namespace nc +{ + //================================================================================ + // Class Description: + /// Holds a 3D vector + class Vec3 + { + public: + //====================================Attributes============================== + double x{ 0. }; + double y{ 0. }; + double z{ 0. }; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + constexpr Vec3() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inX: the x component + /// @param inY: the y component + /// @param inZ: the y component + /// + constexpr Vec3(double inX, double inY, double inZ) noexcept : + x(inX), + y(inY), + z(inZ) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + Vec3(const std::initializer_list& inList) + { + if (inList.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input initializer list must have a size = 3"); + } + + x = *inList.begin(); + y = *(inList.begin() + 1); + z = *(inList.begin() + 2); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param vec2: 2d vector + /// + constexpr Vec3(const Vec2& vec2) noexcept : + x(vec2.x), + y(vec2.y) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ndArray + /// + Vec3(const NdArray& ndArray) + { + if (ndArray.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input NdArray must have a size = 3"); + } + + x = ndArray[0]; + y = ndArray[1]; + z = ndArray[2]; + } + + //============================================================================ + // Method Description: + /// Returns the angle between the two vectors + /// + /// @param otherVec + /// @return the angle in radians + /// + [[nodiscard]] double angle(const Vec3& otherVec) const noexcept + { + double dotProduct = dot(otherVec); + dotProduct /= norm(); + dotProduct /= otherVec.norm(); + + // clamp the value to the acos range just to be safe + dotProduct = std::max(std::min(dotProduct, 1.), -1.); + + return std::acos(dotProduct); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 0, -1] + /// + /// @return Vec3 + /// + static constexpr Vec3 back() noexcept + { + return Vec3(0., 0., -1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns a copy of the vector with its magnitude clamped + /// to maxLength + /// + /// @param maxLength + /// @return Vec3 + /// + [[nodiscard]] Vec3 clampMagnitude(double maxLength) const noexcept + { + const double magnitude = norm(); + if (magnitude <= maxLength) + { + return *this; + } + + Vec3 returnVec = Vec3(*this).normalize(); + returnVec *= maxLength; + return returnVec; + } + + //============================================================================ + // Method Description: + /// Returns the cross product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] Vec3 cross(const Vec3& otherVec) const noexcept + { + const double crossX = y * otherVec.z - z * otherVec.y; + const double crossY = -(x * otherVec.z - z * otherVec.x); + const double crossZ = x * otherVec.y - y * otherVec.x; + + return Vec3(crossX, crossY, crossZ); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the distance between the two vectors + /// + /// @param otherVec + /// @return the distance (equivalent to (a - b).norm() + /// + [[nodiscard]] double distance(const Vec3& otherVec) const noexcept + { + return (Vec3(*this) -= otherVec).norm(); + } + + //============================================================================ + // Method Description: + /// Returns the dot product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] double dot(const Vec3& otherVec) const noexcept + { + return x * otherVec.x + y * otherVec.y + z * otherVec.z; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, -1, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 down() noexcept + { + return Vec3(0., -1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 0, 1] + /// + /// @return Vec3 + /// + static constexpr Vec3 forward() noexcept + { + return Vec3(0., 0., 1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [-1, 0, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 left() noexcept + { + return Vec3(-1., 0., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Linearly interpolates between two vectors + /// + /// @param otherVec + /// @param t the amount to interpolate by (clamped from [0, 1]); + /// @return Vec3 + /// + [[nodiscard]] Vec3 lerp(const Vec3& otherVec, double t) const noexcept + { + t = std::max(std::min(t, 1.), 0.); + + Vec3 trajectory = otherVec; + trajectory -= *this; + const double xInterp = utils::interp(0., trajectory.x, t); + const double yInterp = utils::interp(0., trajectory.y, t); + const double zInterp = utils::interp(0., trajectory.z, t); + + return Vec3(*this) += Vec3(xInterp, yInterp, zInterp); + } + + //============================================================================ + // Method Description: + /// Returns the magnitude of the vector + /// + /// @return magnitude of the vector + /// + [[nodiscard]] double norm() const noexcept + { + return hypot(x, y, z); + } + + //============================================================================ + // Method Description: + /// Returns a new normalized Vec3 + /// + /// @return Vec3 + /// + [[nodiscard]] Vec3 normalize() const noexcept + { + return Vec3(*this) /= norm(); + } + + //============================================================================ + // Method Description: + /// Projects the vector onto the input vector + /// + /// @param otherVec + /// @return Vec3 + /// + [[nodiscard]] Vec3 project(const Vec3& otherVec) const noexcept + { + const double projectedMagnitude = norm() * std::cos(angle(otherVec)); + return otherVec.normalize() *= projectedMagnitude; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [1, 0, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 right() noexcept + { + return Vec3(1., 0., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the Vec3 as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string toString() const + { + std::stringstream stream; + stream << "Vec3[" << x << ", " << y << ", " << z << "]"; + return stream.str(); + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + NdArray returnArray = { x, y, z }; + return returnArray.transpose(); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 1, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 up() noexcept + { + return Vec3(0., 1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const Vec3& rhs) const noexcept + { + return utils::essentiallyEqual(x, rhs.x) && utils::essentiallyEqual(y, rhs.y) && + utils::essentiallyEqual(z, rhs.z); + } + + //============================================================================ + // Method Description: + /// Not Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const Vec3& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator+=(double scalar) noexcept + { + x += scalar; + y += scalar; + z += scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param rhs + /// @return Vec3 + /// + Vec3& operator+=(const Vec3& rhs) noexcept + { + x += rhs.x; + y += rhs.y; + z += rhs.z; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator-=(double scalar) noexcept + { + x -= scalar; + y -= scalar; + z -= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param rhs + /// @return Vec3 + /// + Vec3& operator-=(const Vec3& rhs) noexcept + { + x -= rhs.x; + y -= rhs.y; + z -= rhs.z; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator*=(double scalar) noexcept + { + x *= scalar; + y *= scalar; + z *= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator/=(double scalar) noexcept + { + x /= scalar; + y /= scalar; + z /= scalar; + return *this; + } + }; + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(double lhs, const Vec3& rhs) noexcept + { + return Vec3(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(const Vec3& lhs, const Vec3& rhs) noexcept + { + return Vec3(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Returns the negative vector + /// + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& vec) noexcept + { + return Vec3(-vec.x, -vec.y, -vec.z); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(double lhs, const Vec3& rhs) noexcept + { + return -Vec3(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& lhs, const Vec3& rhs) noexcept + { + return Vec3(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator*(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) *= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator*(double lhs, const Vec3& rhs) noexcept + { + return Vec3(rhs) *= lhs; + } + + //============================================================================ + // Method Description: + /// Vector mulitplication (dot product) + /// + /// @param lhs + /// @param rhs + /// @return dot product + /// + /// + inline double operator*(const Vec3& lhs, const Vec3& rhs) noexcept + { + return lhs.dot(rhs); + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator/(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) /= rhs; + } + + //============================================================================ + // Method Description: + /// stream output operator + /// + /// @param stream + /// @param vec + /// @return std::ostream + /// + inline std::ostream& operator<<(std::ostream& stream, const Vec3& vec) + { + stream << vec.toString() << std::endl; + return stream; + } +} // namespace nc diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/_kiss_fft_guts.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/_kiss_fft_guts.h new file mode 100644 index 0000000000000000000000000000000000000000..ba661444039d60b110b6a3ea3495c1699b9e42da --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/_kiss_fft_guts.h @@ -0,0 +1,164 @@ +/* +Copyright (c) 2003-2010, Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* kiss_fft.h + defines kiss_fft_scalar as either short or a float type + and defines + typedef struct { kiss_fft_scalar r; kiss_fft_scalar i; }kiss_fft_cpx; */ +#include "kiss_fft.h" +#include + +#define MAXFACTORS 32 +/* e.g. an fft of length 128 has 4 factors + as far as kissfft is concerned + 4*4*4*2 + */ + +struct kiss_fft_state{ + int nfft; + int inverse; + int factors[2*MAXFACTORS]; + kiss_fft_cpx twiddles[1]; +}; + +/* + Explanation of macros dealing with complex math: + + C_MUL(m,a,b) : m = a*b + C_FIXDIV( c , div ) : if a fixed point impl., c /= div. noop otherwise + C_SUB( res, a,b) : res = a - b + C_SUBFROM( res , a) : res -= a + C_ADDTO( res , a) : res += a + * */ +#ifdef FIXED_POINT +#if (FIXED_POINT==32) +# define FRACBITS 31 +# define SAMPPROD int64_t +#define SAMP_MAX 2147483647 +#else +# define FRACBITS 15 +# define SAMPPROD int32_t +#define SAMP_MAX 32767 +#endif + +#define SAMP_MIN -SAMP_MAX + +#if defined(CHECK_OVERFLOW) +# define CHECK_OVERFLOW_OP(a,op,b) \ + if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ + fprintf(stderr,"WARNING:overflow @ " __FILE__ "(%d): (%d " #op" %d) = %ld\n",__LINE__,(a),(b),(SAMPPROD)(a) op (SAMPPROD)(b) ); } +#endif + + +# define smul(a,b) ( (SAMPPROD)(a)*(b) ) +# define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) + +# define S_MUL(a,b) sround( smul(a,b) ) + +# define C_MUL(m,a,b) \ + do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ + (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) + +# define DIVSCALAR(x,k) \ + (x) = sround( smul( x, SAMP_MAX/k ) ) + +# define C_FIXDIV(c,div) \ + do { DIVSCALAR( (c).r , div); \ + DIVSCALAR( (c).i , div); }while (0) + +# define C_MULBYSCALAR( c, s ) \ + do{ (c).r = sround( smul( (c).r , s ) ) ;\ + (c).i = sround( smul( (c).i , s ) ) ; }while(0) + +#else /* not FIXED_POINT*/ + +# define S_MUL(a,b) ( (a)*(b) ) +#define C_MUL(m,a,b) \ + do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ + (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) +# define C_FIXDIV(c,div) /* NOOP */ +# define C_MULBYSCALAR( c, s ) \ + do{ (c).r *= (s);\ + (c).i *= (s); }while(0) +#endif + +#ifndef CHECK_OVERFLOW_OP +# define CHECK_OVERFLOW_OP(a,op,b) /* noop */ +#endif + +#define C_ADD( res, a,b)\ + do { \ + CHECK_OVERFLOW_OP((a).r,+,(b).r)\ + CHECK_OVERFLOW_OP((a).i,+,(b).i)\ + (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ + }while(0) +#define C_SUB( res, a,b)\ + do { \ + CHECK_OVERFLOW_OP((a).r,-,(b).r)\ + CHECK_OVERFLOW_OP((a).i,-,(b).i)\ + (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ + }while(0) +#define C_ADDTO( res , a)\ + do { \ + CHECK_OVERFLOW_OP((res).r,+,(a).r)\ + CHECK_OVERFLOW_OP((res).i,+,(a).i)\ + (res).r += (a).r; (res).i += (a).i;\ + }while(0) + +#define C_SUBFROM( res , a)\ + do {\ + CHECK_OVERFLOW_OP((res).r,-,(a).r)\ + CHECK_OVERFLOW_OP((res).i,-,(a).i)\ + (res).r -= (a).r; (res).i -= (a).i; \ + }while(0) + + +#ifdef FIXED_POINT +# define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) +# define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) +# define HALF_OF(x) ((x)>>1) +#elif defined(USE_SIMD) +# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) +# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) +# define HALF_OF(x) ((x)*_mm_set1_ps(.5)) +#else +# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) +# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) +# define HALF_OF(x) ((x)*.5) +#endif + +#define kf_cexp(x,phase) \ + do{ \ + (x)->r = KISS_FFT_COS(phase);\ + (x)->i = KISS_FFT_SIN(phase);\ + }while(0) + + +/* a debugging function */ +#define pcpx(c)\ + fprintf(stderr,"%g + %gi\n",(double)((c)->r),(double)((c)->i) ) + + +#ifdef KISS_FFT_USE_ALLOCA +// define this to allow use of alloca instead of malloc for temporary buffers +// Temporary buffers are used in two case: +// 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 +// 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. +#include +#define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) +#define KISS_FFT_TMP_FREE(ptr) +#else +#define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) +#define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features.h new file mode 100644 index 0000000000000000000000000000000000000000..ed298dcfc2416e19821ab2ffb9dc8f3ae1ddfde6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features.h @@ -0,0 +1,413 @@ + +/** + * Calculate filterbank features. Provides e.g. fbank and mfcc features for use + * in ASR applications. + * + * Derived from python_speech_features, by James Lyons. + * Port by Chris Lord. + */ + +#ifndef __C_SPEECH_FEATURES_H__ +#define __C_SPEECH_FEATURES_H__ + +#include +#include "c_speech_features_config.h" + +#define CSF_HZ2MEL(x) (2595.0 * csf_log10(1.0+(x)/700.0)) +#define CSF_MEL2HZ(x) (700.0 * (csf_pow(10.0, (x)/2595.0) - 1.0)) + +#define CSF_2D_INDEX(w,x,y) (((y)*(w))+(x)) +#define CSF_2D_REF(m,w,x,y) ((m)[CSF_2D_INDEX(w,x,y)]) + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Compute MFCC features from an audio signal. + * + * @param aSignal The audio signal from which to compute features. + * @param aSignalLen The length of the audio signal array. + * @param aSampleRate The sample-rate of the signal. + * @param aWinLen The length of the analysis window in seconds. (e.g. 0.025) + * @param aWinStep The step between successive windows in seconds. (e.g. 0.01) + * @param aNCep The number of cepstrum to return. (e.g. 13) + * @param aNFilters The number of filters in the filterbank. (e.g. 26) + * @param aNFFT The FFT size. (e.g. 512) + * @param aLowFreq The lowest band edge of mel filters, in hz. (e.g. 0) + * @param aHighFreq The highest band edge of mel filters, in hz. Must not be + * higher than @p aSampleRate / 2. If this is lower or equal + * to @p aLowFreq, it will be treated as @p aSampleRate / 2. + * @param aPreemph Preemphasis filter coefficient. 0 is no filter. (e.g. 0.97) + * @param aCepLifter The lifting coefficient to use. 0 disables lifting. + * (e.g. 22) + * @param aAppendEnergy If this is true, the zeroth cepstral coefficient is + * replaced with the log of the total frame energy. + * @param aWinFunc An array of size @c frameLen, as determined by multiplying + * @p aWinLen by @p aSmapleRate, or @c NULL to be used as an + * analysis window to apply to each frame. Refer to + * csf_framesig(). + * @param[out] aMFCC An array containing features, of shape + * (frames, @p aNCep). The user is responsible for freeing + * the array. + * + * @return The number of frames. + */ +int csf_mfcc(const short* aSignal, + unsigned int aSignalLen, + int aSampleRate, + csf_float aWinLen, + csf_float aWinStep, + int aNCep, + int aNFilters, + int aNFFT, + int aLowFreq, + int aHighFreq, + csf_float aPreemph, + int aCepLifter, + int aAppendEnergy, + csf_float* aWinFunc, + csf_float** aMFCC); + +/** + * @brief Compute Mel-filterbank energy features from an audio signal. + * + * Compute Mel-filterbank energy features from an audio signal. + * + * @param aSignal The audio signal from which to compute features. + * @param aSignalLen The length of the audio signal array. + * @param aSampleRate The sample-rate of the signal. + * @param aWinLen The length of the analysis window in seconds. (e.g. 0.025) + * @param aWinStep The step between successive windows in seconds. (e.g. 0.01) + * @param aNFilters The number of filters in the filterbank. (e.g. 26) + * @param aNFFT The FFT size. (e.g. 512) + * @param aLowFreq The lowest band edge of mel filters, in hz. (e.g. 0) + * @param aHighFreq The highest band edge of mel filters, in hz. Must not be + * higher than @p aSampleRate / 2. If this is lower or equal + * to @p aLowFreq, it will be treated as @p aSampleRate / 2. + * @param aPreemph Preemphasis filter coefficient. 0 is no filter. (e.g. 0.97) + * @param aWinFunc An array of size @c frameLen, as determined by multiplying + * @p aWinLen by @p aSmapleRate, or @c NULL to be used as an + * analysis window to apply to each frame. Refer to + * csf_framesig(). + * @param[out] aFeatures A 2D array containing features, of shape + * (frames, @p aNFilters). The user is responsible for + * freeing the array. + * @param[out] aEnergy An array containing energies, of shape (frames), or + * @c NULL. The user is responsible for freeing the array. + * + * @return The number of frames. + */ +int csf_fbank(const short* aSignal, + unsigned int aSignalLen, + int aSampleRate, + csf_float aWinLen, + csf_float aWinStep, + int aNFilters, + int aNFFT, + int aLowFreq, + int aHighFreq, + csf_float aPreemph, + csf_float* aWinFunc, + csf_float** aFeatures, + csf_float** aEnergy); + +/** + * @brief Compute log Mel-filterbank energy features from an audio signal. + * + * Compute log Mel-filterbank energy features from an audio signal. + * + * @param aSignal The audio signal from which to compute features. + * @param aSignalLen The length of the audio signal array. + * @param aSampleRate The sample-rate of the signal. + * @param aWinLen The length of the analysis window in seconds. (e.g. 0.025) + * @param aWinStep The step between successive windows in seconds. (e.g. 0.01) + * @param aNFilters The number of filters in the filterbank. (e.g. 26) + * @param aNFFT The FFT size. (e.g. 512) + * @param aLowFreq The lowest band edge of mel filters, in hz. (e.g. 0) + * @param aHighFreq The highest band edge of mel filters, in hz. Must not be + * higher than @p aSampleRate / 2. If this is lower or equal + * to @p aLowFreq, it will be treated as @p aSampleRate / 2. + * @param aPreemph Preemphasis filter coefficient. 0 is no filter. (e.g. 0.97) + * @param aWinFunc An array of size @c frameLen, as determined by multiplying + * @p aWinLen by @p aSmapleRate, or @c NULL to be used as an + * analysis window to apply to each frame. Refer to + * csf_framesig(). + * @param[out] aFeatures A 2D array containing features, of shape + * (frames, @p aNFilters). The user is responsible for + * freeing the array. + * @param[out] aEnergy An array containing energies, of shape (frames). The + * user is responsible for freeing the array. + * + * @return The number of frames. + */ +int csf_logfbank(const short* aSignal, + unsigned int aSignalLen, + int aSampleRate, + csf_float aWinLen, + csf_float aWinStep, + int aNFilters, + int aNFFT, + int aLowFreq, + int aHighFreq, + csf_float aPreemph, + csf_float* aWinFunc, + csf_float** aFeatures, + csf_float** aEnergy); + +/** + * @brief Compute Spectral Sub-band Centroid features from an audio signal. + * + * Compute Spectral Sub-band Centroid features from an audio signal. + * + * @param aSignal The audio signal from which to compute features. + * @param aSignalLen The length of the audio signal array. + * @param aSampleRate The sample-rate of the signal. + * @param aWinLen The length of the analysis window in seconds. (e.g. 0.025) + * @param aWinStep The step between successive windows in seconds. (e.g. 0.01) + * @param aNFilters The number of filters in the filterbank. (e.g. 26) + * @param aNFFT The FFT size. (e.g. 512) + * @param aLowFreq The lowest band edge of mel filters, in hz. (e.g. 0) + * @param aHighFreq The highest band edge of mel filters, in hz. Must not be + * higher than @p aSampleRate / 2. If this is lower or equal + * to @p aLowFreq, it will be treated as @p aSampleRate / 2. + * @param aPreemph Preemphasis filter coefficient. 0 is no filter. (e.g. 0.97) + * @param aWinFunc An array of size @c frameLen, as determined by multiplying + * @p aWinLen by @p aSmapleRate, or @c NULL to be used as an + * analysis window to apply to each frame. Refer to + * csf_framesig(). + * @param[out] aFeatures A 2D array containing features, of shape + * (frames, @p aNFilters). The user is responsible for + * freeing the array. + */ +int csf_ssc(const short* aSignal, + unsigned int aSignalLen, + int aSampleRate, + csf_float aWinLen, + csf_float aWinStep, + int aNFilters, + int aNFFT, + int aLowFreq, + int aHighFreq, + csf_float aPreemph, + csf_float* aWinFunc, + csf_float** aFeatures); + +/** + * @brief Convert a value in Hertz to Mels + * + * Convert a value in Hertz to Mels + * + * @param aHz A value in Hz. + * + * @return A value in Mels. + */ +csf_float csf_hz2mel(csf_float aHz); + +/** + * @brief Convert a value in Mels to Hertz + * + * Convert a value in Mels to Hertz + * + * @param aMel A value in Mels. + * + * @return A value in Hz. + */ +csf_float csf_mel2hz(csf_float aMel); + +/** + * @brief Compute a Mel-filterbank. + * + * Compute a Mel-filterbank. The filters are stored in the rows, the columns + * correspond to fft bins. The filters are returned as an array of size + * @p aNFilters * (@p aNFFT / 2 + 1). + * + * @param aNFilters The number of filters in the filterbank. (e.g. 20) + * @param aNFFT The FFT size. (e.g. 512) + * @param aSampleRate The sample-rate of the signal being worked with. Affects + * mel spacing. + * @param aLowFreq The lowest band edge of mel filters, in hz. (e.g. 0) + * @param aHighFreq The highest band edge of mel filters, in hz. Must not be + * higher than @p aSampleRate / 2. If this is lower or equal + * to @p aLowFreq, it will be treated as @p aSampleRate / 2. + * + * @return A 2D array of shape (@p aNFilters, @p aNFFT / 2 + 1). The user is + * responsible for freeing the array. + */ +csf_float* csf_get_filterbanks(int aNFilters, + int aNFFT, + int aSampleRate, + int aLowFreq, + int aHighFreq); + +/** + * @brief Apply a cepstral lifter on a matrix of cepstra. + * + * Apply a cepstral lifter on a matrix of cepstra. This has the effect of + * increasing the magnitude of high-frequency DCT coefficients. + * + * @param aCepstra The 2D array matrix of mel-cepstra. + * @param aNFrames The number of frames. + * @param aNCep The number of cepstra per frame. + * @param aCepLifter The lifting coefficient to use. 0 disables lifting. + * (e.g. 22) + */ +void csf_lifter(csf_float* aCepstra, + int aNFrames, + int aNCep, + int aCepLifter); + +/** + * @brief Compute delta features from a feature vector sequence. + * + * Compute delta features from a feature vector sequence. + * + * @param aFeatures A 2D array of shape (@p aNFeatures, @p aNFrames). Each row + * holds one feature vector. + * @param aNFrames The number of frames in @p aFeatures. + * @param aNFrameLen The length of each frame in @p aFeatures. + * @param @aN For each frame, calculate delta features based on preceding and + * following N frames. Must be 1 or larger. + * + * @return A 2D array of shape (@p aNFeatures, @p aNFrames) containing delta + * features. Each row contains holds 1 delta feature vector. The user + * is responsible for freeing the array. + */ +csf_float* csf_delta(const csf_float* aFeatures, + int aNFrames, + int aNFrameLen, + int aN); + +/** + * @brief Perform preemphasis on an input signal. + * + * Perform preemphasis on an input signal. + * + * @param aSignal The signal to filter. + * @param aSignalLen The length of the signal array. + * @param aCoeff The preemphasis coefficient. 0 is no filter. (e.g. 0.95) + * + * @return The filtered signal. The user is responsible for freeing this array. + */ +csf_float* csf_preemphasis(const short* aSignal, + unsigned int aSignalLen, + csf_float aCoeff); + +/** + * @brief Frame a signal into overlapping frames. + * + * Frame a signal into overlapping frames. + * + * @param aSignal The signal to frame. + * @param aSignalLen The length of the signal array. + * @param aFrameLen The length of each frame in samples. + * @param aPaddedFrameLen If greater than @p aFrameLen, @p aPaddedFrameLen - + * @p aFrameLen zeros will be appended to each frame. + * @param aFrameStep The number of samples after the start of the previous frame + * that the next frame should begin. + * @param aWinFunc An array of size @p aFrameLen, or @c NULL to be used as an + * analysis window to apply to each frame. When specified, + * each overlapping frame of the signal will be multiplied + * by the value in the corresponding index of the array. + * @param[out] aFrames A 2D array of frames, of shape + * (@c frames, @p aPaddedFrameLen). + * The user is responsible for freeing the array. + * + * @return The number of frames. + */ +int csf_framesig(const csf_float* aSignal, + unsigned int aSignalLen, + int aFrameLen, + int aPaddedFrameLen, + int aFrameStep, + csf_float* aWinFunc, + csf_float** aFrames); + +/** + * @brief Perform overlap-add procedure to undo the action of csf_framesig(). + * + * Perform overlap-add procedure to undo the action of csf_framesig(). + * + * @param aFrames The 2D array of frames. + * @param aNFrames The number of frames in @p aFrames. + * @param aSigLen The length of the desired signal, or 0 if unknown. + * @param aFrameLen The length of each frame in samples. + * @param aFrameStep The number of samples after the start of the previous frame + * that the next frame begins + * @param aWinFunc An array of size @p aFrameLen, or @c NULL to be used as an + * analysis window to apply to each frame. When specified, + * each sample of the signal will be divided by the aggregated + * value in the corresponding indices of the array. + * @param[out] aSignal An array of samples. The length will be @p aSigLen if + * specified. The user is responsible for freeing + * this array. + * + * @return Returns the length of @p aSignal. + */ +int csf_deframesig(const csf_float* aFrames, + int aNFrames, + int aSigLen, + int aFrameLen, + int aFrameStep, + csf_float* aWinFunc, + csf_float** aSignal); + +/** + * @brief Compute the magnitude spectrum of frames. + * + * Compute the magnitude spectrum of each frame in frames. + * + * @param aFrames The 2D array of frames, of shape (@p aNFrames, @p aNFFT). + * @param aNFrames The number of frames. + * @param aNFFT The FFT length to use. + * + * @return A 2D array containing the magnitude spectrum of the + * corresponding frame, of shape (@p aNFrames, @p aNFFT / 2 + 1). The + * user is responsible for freeing the array. + */ +csf_float* csf_magspec(const csf_float* aFrames, + int aNFrames, + int aNFFT); + +/** + * @brief Compute the power spectrum of frames. + * + * Compute the power spectrum of each frame in frames. + * + * @param aFrames The 2D array of frames, of shape (@p aNFrames, @p aNFFT). + * @param aNFrames The number of frames. + * @param aNFFT The FFT length to use. + * + * @return A 2D array containing the power spectrum of the + * corresponding frame, of shape (@p aNFrames, @p aNFFT / 2 + 1). + * The user is responsible for freeing the array. + */ +csf_float* csf_powspec(const csf_float* aFrames, + int aNFrames, + int aNFFT); + +/** + * @brief Compute the log power spectrum of frames. + * + * Compute the log power spectrum of each frame in frames. + * + * @param aFrames The 2D array of frames, of shape (@p aNFrames, @p aNFFT). + * @param aNFrames The number of frames. + * @param aNFFT The FFT length to use. + * @param aNorm If not zero, the log power spectrum is normalised so that the + * maximum value across all frames is 0. + * + * @return A 2D array containing the log power spectrum of the + * corresponding frame, of shape (@p aNFrames, @p aNFFT / 2 + 1). + * The user is responsible for freeing the array. + */ +csf_float* csf_logpowspec(const csf_float* aFrames, + int aNFrames, + int aNFFT, + int aNorm); + +#ifdef __cplusplus +} +#endif + +#endif /* __C_SPEECH_FEATURES_H__ */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features_config.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features_config.h new file mode 100644 index 0000000000000000000000000000000000000000..bff73dfc6d2f4a31038eae91f30fd41eb4550efe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/c_speech_features_config.h @@ -0,0 +1,26 @@ + +#include + +/* #undef ENABLE_DOUBLE */ + +#ifdef ENABLE_DOUBLE +# define csf_float double +# define csf_ceil ceil +# define csf_floor floor +# define csf_sin sin +# define csf_log log +# define csf_log10 log10 +# define csf_pow pow +# define csf_sqrt sqrt +# define csf_float_min DBL_MIN +#else +# define csf_float float +# define csf_ceil ceilf +# define csf_floor floorf +# define csf_sin sinf +# define csf_log logf +# define csf_log10 log10f +# define csf_pow powf +# define csf_sqrt sqrtf +# define csf_float_min FLT_MIN +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fft.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fft.h new file mode 100644 index 0000000000000000000000000000000000000000..64c50f4aae5900b7aba196803d8bdbced8e0685e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fft.h @@ -0,0 +1,124 @@ +#ifndef KISS_FFT_H +#define KISS_FFT_H + +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + ATTENTION! + If you would like a : + -- a utility that will handle the caching of fft objects + -- real-only (no imaginary time component ) FFT + -- a multi-dimensional FFT + -- a command-line utility to perform ffts + -- a command-line utility to perform fast-convolution filtering + + Then see kfc.h kiss_fftr.h kiss_fftnd.h fftutil.c kiss_fastfir.c + in the tools/ directory. +*/ + +#ifdef USE_SIMD +# include +# define kiss_fft_scalar __m128 +#define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) +#define KISS_FFT_FREE _mm_free +#else +#define KISS_FFT_MALLOC malloc +#define KISS_FFT_FREE free +#endif + + +#ifdef FIXED_POINT +#include +# if (FIXED_POINT == 32) +# define kiss_fft_scalar int32_t +# else +# define kiss_fft_scalar int16_t +# endif +#else +# ifndef kiss_fft_scalar +/* default is float */ +# define kiss_fft_scalar float +# endif +#endif + +typedef struct { + kiss_fft_scalar r; + kiss_fft_scalar i; +}kiss_fft_cpx; + +typedef struct kiss_fft_state* kiss_fft_cfg; + +/* + * kiss_fft_alloc + * + * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. + * + * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); + * + * The return value from fft_alloc is a cfg buffer used internally + * by the fft routine or NULL. + * + * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. + * The returned value should be free()d when done to avoid memory leaks. + * + * The state can be placed in a user supplied buffer 'mem': + * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, + * then the function places the cfg in mem and the size used in *lenmem + * and returns mem. + * + * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), + * then the function returns NULL and places the minimum cfg + * buffer size in *lenmem. + * */ + +kiss_fft_cfg kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); + +/* + * kiss_fft(cfg,in_out_buf) + * + * Perform an FFT on a complex input buffer. + * for a forward FFT, + * fin should be f[0] , f[1] , ... ,f[nfft-1] + * fout will be F[0] , F[1] , ... ,F[nfft-1] + * Note that each element is complex and can be accessed like + f[k].r and f[k].i + * */ +void kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); + +/* + A more generic version of the above function. It reads its input from every Nth sample. + * */ +void kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); + +/* If kiss_fft_alloc allocated a buffer, it is one contiguous + buffer and can be simply free()d when no longer needed*/ +#define kiss_fft_free free + +/* + Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up + your compiler output to call this before you exit. +*/ +void kiss_fft_cleanup(void); + + +/* + * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) + */ +int kiss_fft_next_fast_size(int n); + +/* for real ffts, we need an even size */ +#define kiss_fftr_next_fast_size_real(n) \ + (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fftr.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fftr.h new file mode 100644 index 0000000000000000000000000000000000000000..72e5a57714df11f15a78640bfd8701f00c85dc77 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/csf/kiss_fftr.h @@ -0,0 +1,46 @@ +#ifndef KISS_FTR_H +#define KISS_FTR_H + +#include "kiss_fft.h" +#ifdef __cplusplus +extern "C" { +#endif + + +/* + + Real optimized version can save about 45% cpu time vs. complex fft of a real seq. + + + + */ + +typedef struct kiss_fftr_state *kiss_fftr_cfg; + + +kiss_fftr_cfg kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); +/* + nfft must be even + + If you don't care to allocate space, use mem = lenmem = NULL +*/ + + +void kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); +/* + input timedata has nfft scalar points + output freqdata has nfft/2+1 complex points +*/ + +void kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); +/* + input freqdata has nfft/2+1 complex points + output timedata has nfft scalar points +*/ + +#define kiss_fftr_free free + +#ifdef __cplusplus +} +#endif +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.am b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.am new file mode 100644 index 0000000000000000000000000000000000000000..989d4a2181199aa48f3f8e8b8fdea092f27848a6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.am @@ -0,0 +1,34 @@ +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) 1998 - 2017, Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.haxx.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +########################################################################### +pkginclude_HEADERS = \ + curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \ + typecheck-gcc.h system.h + +pkgincludedir= $(includedir)/curl + +checksrc: + @@PERL@ $(top_srcdir)/lib/checksrc.pl -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) + +if CURLDEBUG +# for debug builds, we scan the sources on all regular make invokes +all-local: checksrc +endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.in b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.in new file mode 100644 index 0000000000000000000000000000000000000000..a33866776186fbed0eef96c5e1653f138cd25485 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/Makefile.in @@ -0,0 +1,693 @@ +# Makefile.in generated by automake 1.16.1 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994-2018 Free Software Foundation, Inc. + +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +VPATH = @srcdir@ +am__is_gnu_make = { \ + if test -z '$(MAKELEVEL)'; then \ + false; \ + elif test -n '$(MAKE_HOST)'; then \ + true; \ + elif test -n '$(MAKE_VERSION)' && test -n '$(CURDIR)'; then \ + true; \ + else \ + false; \ + fi; \ +} +am__make_running_with_option = \ + case $${target_option-} in \ + ?) ;; \ + *) echo "am__make_running_with_option: internal error: invalid" \ + "target option '$${target_option-}' specified" >&2; \ + exit 1;; \ + esac; \ + has_opt=no; \ + sane_makeflags=$$MAKEFLAGS; \ + if $(am__is_gnu_make); then \ + sane_makeflags=$$MFLAGS; \ + else \ + case $$MAKEFLAGS in \ + *\\[\ \ ]*) \ + bs=\\; \ + sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \ + | sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \ + esac; \ + fi; \ + skip_next=no; \ + strip_trailopt () \ + { \ + flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \ + }; \ + for flg in $$sane_makeflags; do \ + test $$skip_next = yes && { skip_next=no; continue; }; \ + case $$flg in \ + *=*|--*) continue;; \ + -*I) strip_trailopt 'I'; skip_next=yes;; \ + -*I?*) strip_trailopt 'I';; \ + -*O) strip_trailopt 'O'; skip_next=yes;; \ + -*O?*) strip_trailopt 'O';; \ + -*l) strip_trailopt 'l'; skip_next=yes;; \ + -*l?*) strip_trailopt 'l';; \ + -[dEDm]) skip_next=yes;; \ + -[JT]) skip_next=yes;; \ + esac; \ + case $$flg in \ + *$$target_option*) has_opt=yes; break;; \ + esac; \ + done; \ + test $$has_opt = yes +am__make_dryrun = (target_option=n; $(am__make_running_with_option)) +am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +pkgdatadir = $(datadir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = include/curl +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/m4/ax_code_coverage.m4 \ + $(top_srcdir)/m4/curl-compilers.m4 \ + $(top_srcdir)/m4/curl-confopts.m4 \ + $(top_srcdir)/m4/curl-functions.m4 \ + $(top_srcdir)/m4/curl-openssl.m4 \ + $(top_srcdir)/m4/curl-override.m4 \ + $(top_srcdir)/m4/curl-reentrant.m4 $(top_srcdir)/m4/libtool.m4 \ + $(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \ + $(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \ + $(top_srcdir)/m4/xc-am-iface.m4 \ + $(top_srcdir)/m4/xc-cc-check.m4 \ + $(top_srcdir)/m4/xc-lt-iface.m4 \ + $(top_srcdir)/m4/xc-translit.m4 \ + $(top_srcdir)/m4/xc-val-flgs.m4 \ + $(top_srcdir)/m4/zz40-xc-ovr.m4 \ + $(top_srcdir)/m4/zz50-xc-ovr.m4 \ + $(top_srcdir)/m4/zz60-xc-ovr.m4 $(top_srcdir)/acinclude.m4 \ + $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +DIST_COMMON = $(srcdir)/Makefile.am $(pkginclude_HEADERS) \ + $(am__DIST_COMMON) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/lib/curl_config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +AM_V_P = $(am__v_P_@AM_V@) +am__v_P_ = $(am__v_P_@AM_DEFAULT_V@) +am__v_P_0 = false +am__v_P_1 = : +AM_V_GEN = $(am__v_GEN_@AM_V@) +am__v_GEN_ = $(am__v_GEN_@AM_DEFAULT_V@) +am__v_GEN_0 = @echo " GEN " $@; +am__v_GEN_1 = +AM_V_at = $(am__v_at_@AM_V@) +am__v_at_ = $(am__v_at_@AM_DEFAULT_V@) +am__v_at_0 = @ +am__v_at_1 = +SOURCES = +DIST_SOURCES = +am__can_run_installinfo = \ + case $$AM_UPDATE_INFO_DIR in \ + n|no|NO) false;; \ + *) (install-info --version) >/dev/null 2>&1;; \ + esac +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(pkgincludedir)" +HEADERS = $(pkginclude_HEADERS) +am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) +# Read a list of newline-separated strings from the standard input, +# and print each of them once, without duplicates. Input order is +# *not* preserved. +am__uniquify_input = $(AWK) '\ + BEGIN { nonempty = 0; } \ + { items[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in items) print i; }; } \ +' +# Make sure the list of sources is unique. This is necessary because, +# e.g., the same source file might be shared among _SOURCES variables +# for different programs/libraries. +am__define_uniq_tagged_files = \ + list='$(am__tagged_files)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | $(am__uniquify_input)` +ETAGS = etags +CTAGS = ctags +am__DIST_COMMON = $(srcdir)/Makefile.in +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +pkgincludedir = $(includedir)/curl +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +BLANK_AT_MAKETIME = @BLANK_AT_MAKETIME@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CFLAG_CURL_SYMBOL_HIDING = @CFLAG_CURL_SYMBOL_HIDING@ +CODE_COVERAGE_CFLAGS = @CODE_COVERAGE_CFLAGS@ +CODE_COVERAGE_CPPFLAGS = @CODE_COVERAGE_CPPFLAGS@ +CODE_COVERAGE_CXXFLAGS = @CODE_COVERAGE_CXXFLAGS@ +CODE_COVERAGE_ENABLED = @CODE_COVERAGE_ENABLED@ +CODE_COVERAGE_LDFLAGS = @CODE_COVERAGE_LDFLAGS@ +CODE_COVERAGE_LIBS = @CODE_COVERAGE_LIBS@ +CONFIGURE_OPTIONS = @CONFIGURE_OPTIONS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CPPFLAG_CURL_STATICLIB = @CPPFLAG_CURL_STATICLIB@ +CURLVERSION = @CURLVERSION@ +CURL_CA_BUNDLE = @CURL_CA_BUNDLE@ +CURL_CFLAG_EXTRAS = @CURL_CFLAG_EXTRAS@ +CURL_DISABLE_DICT = @CURL_DISABLE_DICT@ +CURL_DISABLE_FILE = @CURL_DISABLE_FILE@ +CURL_DISABLE_FTP = @CURL_DISABLE_FTP@ +CURL_DISABLE_GOPHER = @CURL_DISABLE_GOPHER@ +CURL_DISABLE_HTTP = @CURL_DISABLE_HTTP@ +CURL_DISABLE_IMAP = @CURL_DISABLE_IMAP@ +CURL_DISABLE_LDAP = @CURL_DISABLE_LDAP@ +CURL_DISABLE_LDAPS = @CURL_DISABLE_LDAPS@ +CURL_DISABLE_POP3 = @CURL_DISABLE_POP3@ +CURL_DISABLE_PROXY = @CURL_DISABLE_PROXY@ +CURL_DISABLE_RTSP = @CURL_DISABLE_RTSP@ +CURL_DISABLE_SMB = @CURL_DISABLE_SMB@ +CURL_DISABLE_SMTP = @CURL_DISABLE_SMTP@ +CURL_DISABLE_TELNET = @CURL_DISABLE_TELNET@ +CURL_DISABLE_TFTP = @CURL_DISABLE_TFTP@ +CURL_LT_SHLIB_VERSIONED_FLAVOUR = @CURL_LT_SHLIB_VERSIONED_FLAVOUR@ +CURL_NETWORK_AND_TIME_LIBS = @CURL_NETWORK_AND_TIME_LIBS@ +CURL_NETWORK_LIBS = @CURL_NETWORK_LIBS@ +CURL_WITH_MULTI_SSL = @CURL_WITH_MULTI_SSL@ +CYGPATH_W = @CYGPATH_W@ +DEFAULT_SSL_BACKEND = @DEFAULT_SSL_BACKEND@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +ENABLE_SHARED = @ENABLE_SHARED@ +ENABLE_STATIC = @ENABLE_STATIC@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GCOV = @GCOV@ +GENHTML = @GENHTML@ +GREP = @GREP@ +HAVE_BROTLI = @HAVE_BROTLI@ +HAVE_GNUTLS_SRP = @HAVE_GNUTLS_SRP@ +HAVE_LDAP_SSL = @HAVE_LDAP_SSL@ +HAVE_LIBZ = @HAVE_LIBZ@ +HAVE_OPENSSL_SRP = @HAVE_OPENSSL_SRP@ +IDN_ENABLED = @IDN_ENABLED@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +IPV6_ENABLED = @IPV6_ENABLED@ +LCOV = @LCOV@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBCURL_LIBS = @LIBCURL_LIBS@ +LIBMETALINK_CPPFLAGS = @LIBMETALINK_CPPFLAGS@ +LIBMETALINK_LDFLAGS = @LIBMETALINK_LDFLAGS@ +LIBMETALINK_LIBS = @LIBMETALINK_LIBS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBTOOL = @LIBTOOL@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBOBJS = @LTLIBOBJS@ +LT_SYS_LIBRARY_PATH = @LT_SYS_LIBRARY_PATH@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MANOPT = @MANOPT@ +MKDIR_P = @MKDIR_P@ +NM = @NM@ +NMEDIT = @NMEDIT@ +NROFF = @NROFF@ +NSS_LIBS = @NSS_LIBS@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PERL = @PERL@ +PKGADD_NAME = @PKGADD_NAME@ +PKGADD_PKG = @PKGADD_PKG@ +PKGADD_VENDOR = @PKGADD_VENDOR@ +PKGCONFIG = @PKGCONFIG@ +RANDOM_FILE = @RANDOM_FILE@ +RANLIB = @RANLIB@ +REQUIRE_LIB_DEPS = @REQUIRE_LIB_DEPS@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SSL_BACKENDS = @SSL_BACKENDS@ +SSL_ENABLED = @SSL_ENABLED@ +SSL_LIBS = @SSL_LIBS@ +STRIP = @STRIP@ +SUPPORT_FEATURES = @SUPPORT_FEATURES@ +SUPPORT_PROTOCOLS = @SUPPORT_PROTOCOLS@ +USE_ARES = @USE_ARES@ +USE_AXTLS = @USE_AXTLS@ +USE_CYASSL = @USE_CYASSL@ +USE_DARWINSSL = @USE_DARWINSSL@ +USE_GNUTLS = @USE_GNUTLS@ +USE_GNUTLS_NETTLE = @USE_GNUTLS_NETTLE@ +USE_LIBRTMP = @USE_LIBRTMP@ +USE_LIBSSH = @USE_LIBSSH@ +USE_LIBSSH2 = @USE_LIBSSH2@ +USE_MBEDTLS = @USE_MBEDTLS@ +USE_NGHTTP2 = @USE_NGHTTP2@ +USE_NSS = @USE_NSS@ +USE_OPENLDAP = @USE_OPENLDAP@ +USE_POLARSSL = @USE_POLARSSL@ +USE_SCHANNEL = @USE_SCHANNEL@ +USE_UNIX_SOCKETS = @USE_UNIX_SOCKETS@ +USE_WINDOWS_SSPI = @USE_WINDOWS_SSPI@ +VERSION = @VERSION@ +VERSIONNUM = @VERSIONNUM@ +ZLIB_LIBS = @ZLIB_LIBS@ +ZSH_FUNCTIONS_DIR = @ZSH_FUNCTIONS_DIR@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +libext = @libext@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +subdirs = @subdirs@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ + +#*************************************************************************** +# _ _ ____ _ +# Project ___| | | | _ \| | +# / __| | | | |_) | | +# | (__| |_| | _ <| |___ +# \___|\___/|_| \_\_____| +# +# Copyright (C) 1998 - 2017, Daniel Stenberg, , et al. +# +# This software is licensed as described in the file COPYING, which +# you should have received as part of this distribution. The terms +# are also available at https://curl.haxx.se/docs/copyright.html. +# +# You may opt to use, copy, modify, merge, publish, distribute and/or sell +# copies of the Software, and permit persons to whom the Software is +# furnished to do so, under the terms of the COPYING file. +# +# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +# KIND, either express or implied. +# +########################################################################### +pkginclude_HEADERS = \ + curl.h curlver.h easy.h mprintf.h stdcheaders.h multi.h \ + typecheck-gcc.h system.h + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --gnu include/curl/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --gnu include/curl/Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__maybe_remake_depfiles);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pkgincludeHEADERS: $(pkginclude_HEADERS) + @$(NORMAL_INSTALL) + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + if test -n "$$list"; then \ + echo " $(MKDIR_P) '$(DESTDIR)$(pkgincludedir)'"; \ + $(MKDIR_P) "$(DESTDIR)$(pkgincludedir)" || exit 1; \ + fi; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(pkgincludedir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(pkgincludedir)" || exit $$?; \ + done + +uninstall-pkgincludeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(pkginclude_HEADERS)'; test -n "$(pkgincludedir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(pkgincludedir)'; $(am__uninstall_files_from_dir) + +ID: $(am__tagged_files) + $(am__define_uniq_tagged_files); mkid -fID $$unique +tags: tags-am +TAGS: tags + +tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + set x; \ + here=`pwd`; \ + $(am__define_uniq_tagged_files); \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: ctags-am + +CTAGS: ctags +ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files) + $(am__define_uniq_tagged_files); \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" +cscopelist: cscopelist-am + +cscopelist-am: $(am__tagged_files) + list='$(am__tagged_files)'; \ + case "$(srcdir)" in \ + [\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \ + *) sdir=$(subdir)/$(srcdir) ;; \ + esac; \ + for i in $$list; do \ + if test -f "$$i"; then \ + echo "$(subdir)/$$i"; \ + else \ + echo "$$sdir/$$i"; \ + fi; \ + done >> $(top_builddir)/cscope.files + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(BUILT_SOURCES) + $(MAKE) $(AM_MAKEFLAGS) distdir-am + +distdir-am: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +@CURLDEBUG_FALSE@all-local: +all-am: Makefile $(HEADERS) all-local +installdirs: + for dir in "$(DESTDIR)$(pkgincludedir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pkgincludeHEADERS + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pkgincludeHEADERS + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS TAGS all all-am all-local check check-am clean \ + clean-generic clean-libtool cscopelist-am ctags ctags-am \ + distclean distclean-generic distclean-libtool distclean-tags \ + distdir dvi dvi-am html html-am info info-am install \ + install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pkgincludeHEADERS \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \ + uninstall-am uninstall-pkgincludeHEADERS + +.PRECIOUS: Makefile + + +checksrc: + @@PERL@ $(top_srcdir)/lib/checksrc.pl -D$(top_srcdir)/include/curl $(pkginclude_HEADERS) + +# for debug builds, we scan the sources on all regular make invokes +@CURLDEBUG_TRUE@all-local: checksrc + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curl.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curl.h new file mode 100644 index 0000000000000000000000000000000000000000..521c254e7700dc78c6ae7f544fadffcf27c7132c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curl.h @@ -0,0 +1,3070 @@ +#ifndef CURLINC_CURL_H +#define CURLINC_CURL_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2021, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* + * If you have libcurl problems, all docs and details are found here: + * https://curl.se/libcurl/ + * + * curl-library mailing list subscription and unsubscription web interface: + * https://cool.haxx.se/mailman/listinfo/curl-library/ + */ + +#ifdef CURL_NO_OLDIES +#define CURL_STRICTER +#endif + +#include "curlver.h" /* libcurl version defines */ +#include "system.h" /* determine things run-time */ + +/* + * Define CURL_WIN32 when build target is Win32 API + */ + +#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \ + !defined(__SYMBIAN32__) +#define CURL_WIN32 +#endif + +#include +#include + +#if defined(__FreeBSD__) && (__FreeBSD__ >= 2) +/* Needed for __FreeBSD_version symbol definition */ +#include +#endif + +/* The include stuff here below is mainly for time_t! */ +#include +#include + +#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__) +#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \ + defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H)) +/* The check above prevents the winsock2 inclusion if winsock.h already was + included, since they can't co-exist without problems */ +#include +#include +#endif +#endif + +/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish + libc5-based Linux systems. Only include it on systems that are known to + require it! */ +#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \ + defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \ + defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \ + defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \ + (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \ + defined(__VXWORKS__) +#include +#endif + +#if !defined(CURL_WIN32) && !defined(_WIN32_WCE) +#include +#endif + +#if !defined(CURL_WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__) +#include +#endif + +#ifdef __BEOS__ +#include +#endif + +/* Compatibility for non-Clang compilers */ +#ifndef __has_declspec_attribute +# define __has_declspec_attribute(x) 0 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) +typedef struct Curl_easy CURL; +typedef struct Curl_share CURLSH; +#else +typedef void CURL; +typedef void CURLSH; +#endif + +/* + * libcurl external API function linkage decorations. + */ + +#ifdef CURL_STATICLIB +# define CURL_EXTERN +#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \ + (__has_declspec_attribute(dllexport) && \ + __has_declspec_attribute(dllimport)) +# if defined(BUILDING_LIBCURL) +# define CURL_EXTERN __declspec(dllexport) +# else +# define CURL_EXTERN __declspec(dllimport) +# endif +#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS) +# define CURL_EXTERN CURL_EXTERN_SYMBOL +#else +# define CURL_EXTERN +#endif + +#ifndef curl_socket_typedef +/* socket typedef */ +#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H) +typedef SOCKET curl_socket_t; +#define CURL_SOCKET_BAD INVALID_SOCKET +#else +typedef int curl_socket_t; +#define CURL_SOCKET_BAD -1 +#endif +#define curl_socket_typedef +#endif /* curl_socket_typedef */ + +/* enum for the different supported SSL backends */ +typedef enum { + CURLSSLBACKEND_NONE = 0, + CURLSSLBACKEND_OPENSSL = 1, + CURLSSLBACKEND_GNUTLS = 2, + CURLSSLBACKEND_NSS = 3, + CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */ + CURLSSLBACKEND_GSKIT = 5, + CURLSSLBACKEND_POLARSSL = 6, + CURLSSLBACKEND_WOLFSSL = 7, + CURLSSLBACKEND_SCHANNEL = 8, + CURLSSLBACKEND_SECURETRANSPORT = 9, + CURLSSLBACKEND_AXTLS = 10, /* never used since 7.63.0 */ + CURLSSLBACKEND_MBEDTLS = 11, + CURLSSLBACKEND_MESALINK = 12, + CURLSSLBACKEND_BEARSSL = 13, + CURLSSLBACKEND_RUSTLS = 14 +} curl_sslbackend; + +/* aliases for library clones and renames */ +#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL +#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL + +/* deprecated names: */ +#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL +#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT + +struct curl_httppost { + struct curl_httppost *next; /* next entry in the list */ + char *name; /* pointer to allocated name */ + long namelength; /* length of name length */ + char *contents; /* pointer to allocated data contents */ + long contentslength; /* length of contents field, see also + CURL_HTTPPOST_LARGE */ + char *buffer; /* pointer to allocated buffer contents */ + long bufferlength; /* length of buffer field */ + char *contenttype; /* Content-Type */ + struct curl_slist *contentheader; /* list of extra headers for this form */ + struct curl_httppost *more; /* if one field name has more than one + file, this link should link to following + files */ + long flags; /* as defined below */ + +/* specified content is a file name */ +#define CURL_HTTPPOST_FILENAME (1<<0) +/* specified content is a file name */ +#define CURL_HTTPPOST_READFILE (1<<1) +/* name is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRNAME (1<<2) +/* contents is only stored pointer do not free in formfree */ +#define CURL_HTTPPOST_PTRCONTENTS (1<<3) +/* upload file from buffer */ +#define CURL_HTTPPOST_BUFFER (1<<4) +/* upload file from pointer contents */ +#define CURL_HTTPPOST_PTRBUFFER (1<<5) +/* upload file contents by using the regular read callback to get the data and + pass the given pointer as custom pointer */ +#define CURL_HTTPPOST_CALLBACK (1<<6) +/* use size in 'contentlen', added in 7.46.0 */ +#define CURL_HTTPPOST_LARGE (1<<7) + + char *showfilename; /* The file name to show. If not set, the + actual file name will be used (if this + is a file part) */ + void *userp; /* custom pointer used for + HTTPPOST_CALLBACK posts */ + curl_off_t contentlen; /* alternative length of contents + field. Used if CURL_HTTPPOST_LARGE is + set. Added in 7.46.0 */ +}; + + +/* This is a return code for the progress callback that, when returned, will + signal libcurl to continue executing the default progress function */ +#define CURL_PROGRESSFUNC_CONTINUE 0x10000001 + +/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now + considered deprecated but was the only choice up until 7.31.0 */ +typedef int (*curl_progress_callback)(void *clientp, + double dltotal, + double dlnow, + double ultotal, + double ulnow); + +/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced + in 7.32.0, avoids the use of floating point numbers and provides more + detailed information. */ +typedef int (*curl_xferinfo_callback)(void *clientp, + curl_off_t dltotal, + curl_off_t dlnow, + curl_off_t ultotal, + curl_off_t ulnow); + +#ifndef CURL_MAX_READ_SIZE + /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */ +#define CURL_MAX_READ_SIZE 524288 +#endif + +#ifndef CURL_MAX_WRITE_SIZE + /* Tests have proven that 20K is a very bad buffer size for uploads on + Windows, while 16K for some odd reason performed a lot better. + We do the ifndef check to allow this value to easier be changed at build + time for those who feel adventurous. The practical minimum is about + 400 bytes since libcurl uses a buffer of this size as a scratch area + (unrelated to network send operations). */ +#define CURL_MAX_WRITE_SIZE 16384 +#endif + +#ifndef CURL_MAX_HTTP_HEADER +/* The only reason to have a max limit for this is to avoid the risk of a bad + server feeding libcurl with a never-ending header that will cause reallocs + infinitely */ +#define CURL_MAX_HTTP_HEADER (100*1024) +#endif + +/* This is a magic return code for the write callback that, when returned, + will signal libcurl to pause receiving on the current transfer. */ +#define CURL_WRITEFUNC_PAUSE 0x10000001 + +typedef size_t (*curl_write_callback)(char *buffer, + size_t size, + size_t nitems, + void *outstream); + +/* This callback will be called when a new resolver request is made */ +typedef int (*curl_resolver_start_callback)(void *resolver_state, + void *reserved, void *userdata); + +/* enumeration of file types */ +typedef enum { + CURLFILETYPE_FILE = 0, + CURLFILETYPE_DIRECTORY, + CURLFILETYPE_SYMLINK, + CURLFILETYPE_DEVICE_BLOCK, + CURLFILETYPE_DEVICE_CHAR, + CURLFILETYPE_NAMEDPIPE, + CURLFILETYPE_SOCKET, + CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */ + + CURLFILETYPE_UNKNOWN /* should never occur */ +} curlfiletype; + +#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0) +#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1) +#define CURLFINFOFLAG_KNOWN_TIME (1<<2) +#define CURLFINFOFLAG_KNOWN_PERM (1<<3) +#define CURLFINFOFLAG_KNOWN_UID (1<<4) +#define CURLFINFOFLAG_KNOWN_GID (1<<5) +#define CURLFINFOFLAG_KNOWN_SIZE (1<<6) +#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7) + +/* Information about a single file, used when doing FTP wildcard matching */ +struct curl_fileinfo { + char *filename; + curlfiletype filetype; + time_t time; /* always zero! */ + unsigned int perm; + int uid; + int gid; + curl_off_t size; + long int hardlinks; + + struct { + /* If some of these fields is not NULL, it is a pointer to b_data. */ + char *time; + char *perm; + char *user; + char *group; + char *target; /* pointer to the target filename of a symlink */ + } strings; + + unsigned int flags; + + /* used internally */ + char *b_data; + size_t b_size; + size_t b_used; +}; + +/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */ +#define CURL_CHUNK_BGN_FUNC_OK 0 +#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */ +#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */ + +/* if splitting of data transfer is enabled, this callback is called before + download of an individual chunk started. Note that parameter "remains" works + only for FTP wildcard downloading (for now), otherwise is not used */ +typedef long (*curl_chunk_bgn_callback)(const void *transfer_info, + void *ptr, + int remains); + +/* return codes for CURLOPT_CHUNK_END_FUNCTION */ +#define CURL_CHUNK_END_FUNC_OK 0 +#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */ + +/* If splitting of data transfer is enabled this callback is called after + download of an individual chunk finished. + Note! After this callback was set then it have to be called FOR ALL chunks. + Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC. + This is the reason why we don't need "transfer_info" parameter in this + callback and we are not interested in "remains" parameter too. */ +typedef long (*curl_chunk_end_callback)(void *ptr); + +/* return codes for FNMATCHFUNCTION */ +#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */ +#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */ +#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */ + +/* callback type for wildcard downloading pattern matching. If the + string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */ +typedef int (*curl_fnmatch_callback)(void *ptr, + const char *pattern, + const char *string); + +/* These are the return codes for the seek callbacks */ +#define CURL_SEEKFUNC_OK 0 +#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */ +#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so + libcurl might try other means instead */ +typedef int (*curl_seek_callback)(void *instream, + curl_off_t offset, + int origin); /* 'whence' */ + +/* This is a return code for the read callback that, when returned, will + signal libcurl to immediately abort the current transfer. */ +#define CURL_READFUNC_ABORT 0x10000000 +/* This is a return code for the read callback that, when returned, will + signal libcurl to pause sending data on the current transfer. */ +#define CURL_READFUNC_PAUSE 0x10000001 + +/* Return code for when the trailing headers' callback has terminated + without any errors*/ +#define CURL_TRAILERFUNC_OK 0 +/* Return code for when was an error in the trailing header's list and we + want to abort the request */ +#define CURL_TRAILERFUNC_ABORT 1 + +typedef size_t (*curl_read_callback)(char *buffer, + size_t size, + size_t nitems, + void *instream); + +typedef int (*curl_trailer_callback)(struct curl_slist **list, + void *userdata); + +typedef enum { + CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */ + CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */ + CURLSOCKTYPE_LAST /* never use */ +} curlsocktype; + +/* The return code from the sockopt_callback can signal information back + to libcurl: */ +#define CURL_SOCKOPT_OK 0 +#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return + CURLE_ABORTED_BY_CALLBACK */ +#define CURL_SOCKOPT_ALREADY_CONNECTED 2 + +typedef int (*curl_sockopt_callback)(void *clientp, + curl_socket_t curlfd, + curlsocktype purpose); + +struct curl_sockaddr { + int family; + int socktype; + int protocol; + unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it + turned really ugly and painful on the systems that + lack this type */ + struct sockaddr addr; +}; + +typedef curl_socket_t +(*curl_opensocket_callback)(void *clientp, + curlsocktype purpose, + struct curl_sockaddr *address); + +typedef int +(*curl_closesocket_callback)(void *clientp, curl_socket_t item); + +typedef enum { + CURLIOE_OK, /* I/O operation successful */ + CURLIOE_UNKNOWNCMD, /* command was unknown to callback */ + CURLIOE_FAILRESTART, /* failed to restart the read */ + CURLIOE_LAST /* never use */ +} curlioerr; + +typedef enum { + CURLIOCMD_NOP, /* no operation */ + CURLIOCMD_RESTARTREAD, /* restart the read stream from start */ + CURLIOCMD_LAST /* never use */ +} curliocmd; + +typedef curlioerr (*curl_ioctl_callback)(CURL *handle, + int cmd, + void *clientp); + +#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS +/* + * The following typedef's are signatures of malloc, free, realloc, strdup and + * calloc respectively. Function pointers of these types can be passed to the + * curl_global_init_mem() function to set user defined memory management + * callback routines. + */ +typedef void *(*curl_malloc_callback)(size_t size); +typedef void (*curl_free_callback)(void *ptr); +typedef void *(*curl_realloc_callback)(void *ptr, size_t size); +typedef char *(*curl_strdup_callback)(const char *str); +typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size); + +#define CURL_DID_MEMORY_FUNC_TYPEDEFS +#endif + +/* the kind of data that is passed to information_callback*/ +typedef enum { + CURLINFO_TEXT = 0, + CURLINFO_HEADER_IN, /* 1 */ + CURLINFO_HEADER_OUT, /* 2 */ + CURLINFO_DATA_IN, /* 3 */ + CURLINFO_DATA_OUT, /* 4 */ + CURLINFO_SSL_DATA_IN, /* 5 */ + CURLINFO_SSL_DATA_OUT, /* 6 */ + CURLINFO_END +} curl_infotype; + +typedef int (*curl_debug_callback) + (CURL *handle, /* the handle/transfer this concerns */ + curl_infotype type, /* what kind of data */ + char *data, /* points to the data */ + size_t size, /* size of the data pointed to */ + void *userptr); /* whatever the user please */ + +/* All possible error codes from all sorts of curl functions. Future versions + may return other values, stay prepared. + + Always add new return codes last. Never *EVER* remove any. The return + codes must remain the same! + */ + +typedef enum { + CURLE_OK = 0, + CURLE_UNSUPPORTED_PROTOCOL, /* 1 */ + CURLE_FAILED_INIT, /* 2 */ + CURLE_URL_MALFORMAT, /* 3 */ + CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for + 7.17.0, reused in April 2011 for 7.21.5] */ + CURLE_COULDNT_RESOLVE_PROXY, /* 5 */ + CURLE_COULDNT_RESOLVE_HOST, /* 6 */ + CURLE_COULDNT_CONNECT, /* 7 */ + CURLE_WEIRD_SERVER_REPLY, /* 8 */ + CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server + due to lack of access - when login fails + this is not returned. */ + CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for + 7.15.4, reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */ + CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server + [was obsoleted in August 2007 for 7.17.0, + reused in Dec 2011 for 7.24.0]*/ + CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */ + CURLE_FTP_WEIRD_227_FORMAT, /* 14 */ + CURLE_FTP_CANT_GET_HOST, /* 15 */ + CURLE_HTTP2, /* 16 - A problem in the http2 framing layer. + [was obsoleted in August 2007 for 7.17.0, + reused in July 2014 for 7.38.0] */ + CURLE_FTP_COULDNT_SET_TYPE, /* 17 */ + CURLE_PARTIAL_FILE, /* 18 */ + CURLE_FTP_COULDNT_RETR_FILE, /* 19 */ + CURLE_OBSOLETE20, /* 20 - NOT USED */ + CURLE_QUOTE_ERROR, /* 21 - quote command failure */ + CURLE_HTTP_RETURNED_ERROR, /* 22 */ + CURLE_WRITE_ERROR, /* 23 */ + CURLE_OBSOLETE24, /* 24 - NOT USED */ + CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */ + CURLE_READ_ERROR, /* 26 - couldn't open/read from file */ + CURLE_OUT_OF_MEMORY, /* 27 */ + /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error + instead of a memory allocation error if CURL_DOES_CONVERSIONS + is defined + */ + CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */ + CURLE_OBSOLETE29, /* 29 - NOT USED */ + CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */ + CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */ + CURLE_OBSOLETE32, /* 32 - NOT USED */ + CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */ + CURLE_HTTP_POST_ERROR, /* 34 */ + CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */ + CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */ + CURLE_FILE_COULDNT_READ_FILE, /* 37 */ + CURLE_LDAP_CANNOT_BIND, /* 38 */ + CURLE_LDAP_SEARCH_FAILED, /* 39 */ + CURLE_OBSOLETE40, /* 40 - NOT USED */ + CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */ + CURLE_ABORTED_BY_CALLBACK, /* 42 */ + CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */ + CURLE_OBSOLETE44, /* 44 - NOT USED */ + CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */ + CURLE_OBSOLETE46, /* 46 - NOT USED */ + CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */ + CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */ + CURLE_SETOPT_OPTION_SYNTAX, /* 49 - Malformed setopt option */ + CURLE_OBSOLETE50, /* 50 - NOT USED */ + CURLE_OBSOLETE51, /* 51 - NOT USED */ + CURLE_GOT_NOTHING, /* 52 - when this is a specific error */ + CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */ + CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as + default */ + CURLE_SEND_ERROR, /* 55 - failed sending network data */ + CURLE_RECV_ERROR, /* 56 - failure in receiving network data */ + CURLE_OBSOLETE57, /* 57 - NOT IN USE */ + CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */ + CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */ + CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint + wasn't verified fine */ + CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */ + CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */ + CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */ + CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */ + CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind + that failed */ + CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */ + CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not + accepted and we failed to login */ + CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */ + CURLE_TFTP_PERM, /* 69 - permission problem on server */ + CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */ + CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */ + CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */ + CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */ + CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */ + CURLE_CONV_FAILED, /* 75 - conversion failed */ + CURLE_CONV_REQD, /* 76 - caller must register conversion + callbacks using curl_easy_setopt options + CURLOPT_CONV_FROM_NETWORK_FUNCTION, + CURLOPT_CONV_TO_NETWORK_FUNCTION, and + CURLOPT_CONV_FROM_UTF8_FUNCTION */ + CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing + or wrong format */ + CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */ + CURLE_SSH, /* 79 - error from the SSH layer, somewhat + generic so the error message will be of + interest when this has happened */ + + CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL + connection */ + CURLE_AGAIN, /* 81 - socket is not ready for send/recv, + wait till it's ready and try again (Added + in 7.18.2) */ + CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or + wrong format (Added in 7.19.0) */ + CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in + 7.19.0) */ + CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */ + CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */ + CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */ + CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */ + CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */ + CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the + session will be queued */ + CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not + match */ + CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */ + CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer + */ + CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from + inside a callback */ + CURLE_AUTH_ERROR, /* 94 - an authentication function returned an + error */ + CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */ + CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */ + CURLE_PROXY, /* 97 - proxy handshake error */ + CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */ + CURL_LAST /* never use! */ +} CURLcode; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Previously obsolete error code re-used in 7.38.0 */ +#define CURLE_OBSOLETE16 CURLE_HTTP2 + +/* Previously obsolete error codes re-used in 7.24.0 */ +#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED +#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT + +/* compatibility with older names */ +#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING +#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY + +/* The following were added in 7.62.0 */ +#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION + +/* The following were added in 7.21.5, April 2011 */ +#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION + +/* Added for 7.78.0 */ +#define CURLE_TELNET_OPTION_SYNTAX CURLE_SETOPT_OPTION_SYNTAX + +/* The following were added in 7.17.1 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION + +/* The following were added in 7.17.0 */ +/* These are scheduled to disappear by 2009 */ +#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */ +#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46 +#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44 +#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10 +#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16 +#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32 +#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29 +#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12 +#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20 +#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40 +#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24 +#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57 +#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN + +#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED +#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE +#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR +#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL +#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS +#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR +#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED + +/* The following were added earlier */ + +#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT + +#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR +#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED +#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED + +#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE +#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME + +/* This was the error code 50 in 7.7.3 and a few earlier versions, this + is no longer used by libcurl but is instead #defined here only to not + make programs break */ +#define CURLE_ALREADY_COMPLETE 99999 + +/* Provide defines for really old option names */ +#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */ +#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */ +#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA + +/* Since long deprecated options with no code in the lib that does anything + with them. */ +#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40 +#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72 + +#endif /*!CURL_NO_OLDIES*/ + +/* + * Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was + * return for the transfers. + */ +typedef enum { + CURLPX_OK, + CURLPX_BAD_ADDRESS_TYPE, + CURLPX_BAD_VERSION, + CURLPX_CLOSED, + CURLPX_GSSAPI, + CURLPX_GSSAPI_PERMSG, + CURLPX_GSSAPI_PROTECTION, + CURLPX_IDENTD, + CURLPX_IDENTD_DIFFER, + CURLPX_LONG_HOSTNAME, + CURLPX_LONG_PASSWD, + CURLPX_LONG_USER, + CURLPX_NO_AUTH, + CURLPX_RECV_ADDRESS, + CURLPX_RECV_AUTH, + CURLPX_RECV_CONNECT, + CURLPX_RECV_REQACK, + CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED, + CURLPX_REPLY_COMMAND_NOT_SUPPORTED, + CURLPX_REPLY_CONNECTION_REFUSED, + CURLPX_REPLY_GENERAL_SERVER_FAILURE, + CURLPX_REPLY_HOST_UNREACHABLE, + CURLPX_REPLY_NETWORK_UNREACHABLE, + CURLPX_REPLY_NOT_ALLOWED, + CURLPX_REPLY_TTL_EXPIRED, + CURLPX_REPLY_UNASSIGNED, + CURLPX_REQUEST_FAILED, + CURLPX_RESOLVE_HOST, + CURLPX_SEND_AUTH, + CURLPX_SEND_CONNECT, + CURLPX_SEND_REQUEST, + CURLPX_UNKNOWN_FAIL, + CURLPX_UNKNOWN_MODE, + CURLPX_USER_REJECTED, + CURLPX_LAST /* never use */ +} CURLproxycode; + +/* This prototype applies to all conversion callbacks */ +typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length); + +typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */ + void *ssl_ctx, /* actually an OpenSSL + or WolfSSL SSL_CTX, + or an mbedTLS + mbedtls_ssl_config */ + void *userptr); + +typedef enum { + CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use + CONNECT HTTP/1.1 */ + CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT + HTTP/1.0 */ + CURLPROXY_HTTPS = 2, /* added in 7.52.0 */ + CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already + in 7.10 */ + CURLPROXY_SOCKS5 = 5, /* added in 7.10 */ + CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */ + CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the + host name rather than the IP address. added + in 7.18.0 */ +} curl_proxytype; /* this enum was added in 7.10 */ + +/* + * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options: + * + * CURLAUTH_NONE - No HTTP authentication + * CURLAUTH_BASIC - HTTP Basic authentication (default) + * CURLAUTH_DIGEST - HTTP Digest authentication + * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication + * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated) + * CURLAUTH_NTLM - HTTP NTLM authentication + * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour + * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper + * CURLAUTH_BEARER - HTTP Bearer token authentication + * CURLAUTH_ONLY - Use together with a single other type to force no + * authentication or just that single type + * CURLAUTH_ANY - All fine types set + * CURLAUTH_ANYSAFE - All fine types except Basic + */ + +#define CURLAUTH_NONE ((unsigned long)0) +#define CURLAUTH_BASIC (((unsigned long)1)<<0) +#define CURLAUTH_DIGEST (((unsigned long)1)<<1) +#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2) +/* Deprecated since the advent of CURLAUTH_NEGOTIATE */ +#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE +/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */ +#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE +#define CURLAUTH_NTLM (((unsigned long)1)<<3) +#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4) +#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5) +#define CURLAUTH_BEARER (((unsigned long)1)<<6) +#define CURLAUTH_AWS_SIGV4 (((unsigned long)1)<<7) +#define CURLAUTH_ONLY (((unsigned long)1)<<31) +#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) +#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE)) + +#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */ +#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */ +#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */ +#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */ +#define CURLSSH_AUTH_HOST (1<<2) /* host key files */ +#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */ +#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */ +#define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */ +#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY + +#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */ +#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */ +#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */ + +#define CURL_ERROR_SIZE 256 + +enum curl_khtype { + CURLKHTYPE_UNKNOWN, + CURLKHTYPE_RSA1, + CURLKHTYPE_RSA, + CURLKHTYPE_DSS, + CURLKHTYPE_ECDSA, + CURLKHTYPE_ED25519 +}; + +struct curl_khkey { + const char *key; /* points to a null-terminated string encoded with base64 + if len is zero, otherwise to the "raw" data */ + size_t len; + enum curl_khtype keytype; +}; + +/* this is the set of return values expected from the curl_sshkeycallback + callback */ +enum curl_khstat { + CURLKHSTAT_FINE_ADD_TO_FILE, + CURLKHSTAT_FINE, + CURLKHSTAT_REJECT, /* reject the connection, return an error */ + CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so + this causes a CURLE_DEFER error but otherwise the + connection will be left intact etc */ + CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key*/ + CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */ +}; + +/* this is the set of status codes pass in to the callback */ +enum curl_khmatch { + CURLKHMATCH_OK, /* match */ + CURLKHMATCH_MISMATCH, /* host found, key mismatch! */ + CURLKHMATCH_MISSING, /* no matching host/key found */ + CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */ +}; + +typedef int + (*curl_sshkeycallback) (CURL *easy, /* easy handle */ + const struct curl_khkey *knownkey, /* known */ + const struct curl_khkey *foundkey, /* found */ + enum curl_khmatch, /* libcurl's view on the keys */ + void *clientp); /* custom pointer passed from app */ + +/* parameter for the CURLOPT_USE_SSL option */ +typedef enum { + CURLUSESSL_NONE, /* do not attempt to use SSL */ + CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */ + CURLUSESSL_CONTROL, /* SSL for the control connection or fail */ + CURLUSESSL_ALL, /* SSL for all communication or fail */ + CURLUSESSL_LAST /* not an option, never use */ +} curl_usessl; + +/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */ + +/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the + name of improving interoperability with older servers. Some SSL libraries + have introduced work-arounds for this flaw but those work-arounds sometimes + make the SSL communication fail. To regain functionality with those broken + servers, a user can this way allow the vulnerability back. */ +#define CURLSSLOPT_ALLOW_BEAST (1<<0) + +/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those + SSL backends where such behavior is present. */ +#define CURLSSLOPT_NO_REVOKE (1<<1) + +/* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain + if possible. The OpenSSL backend has this ability. */ +#define CURLSSLOPT_NO_PARTIALCHAIN (1<<2) + +/* - REVOKE_BEST_EFFORT tells libcurl to ignore certificate revocation offline + checks and ignore missing revocation list for those SSL backends where such + behavior is present. */ +#define CURLSSLOPT_REVOKE_BEST_EFFORT (1<<3) + +/* - CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of + operating system. Currently implemented under MS-Windows. */ +#define CURLSSLOPT_NATIVE_CA (1<<4) + +/* - CURLSSLOPT_AUTO_CLIENT_CERT tells libcurl to automatically locate and use + a client certificate for authentication. (Schannel) */ +#define CURLSSLOPT_AUTO_CLIENT_CERT (1<<5) + +/* The default connection attempt delay in milliseconds for happy eyeballs. + CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document + this value, keep them in sync. */ +#define CURL_HET_DEFAULT 200L + +/* The default connection upkeep interval in milliseconds. */ +#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2009 */ + +#define CURLFTPSSL_NONE CURLUSESSL_NONE +#define CURLFTPSSL_TRY CURLUSESSL_TRY +#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL +#define CURLFTPSSL_ALL CURLUSESSL_ALL +#define CURLFTPSSL_LAST CURLUSESSL_LAST +#define curl_ftpssl curl_usessl +#endif /*!CURL_NO_OLDIES*/ + +/* parameter for the CURLOPT_FTP_SSL_CCC option */ +typedef enum { + CURLFTPSSL_CCC_NONE, /* do not send CCC */ + CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */ + CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */ + CURLFTPSSL_CCC_LAST /* not an option, never use */ +} curl_ftpccc; + +/* parameter for the CURLOPT_FTPSSLAUTH option */ +typedef enum { + CURLFTPAUTH_DEFAULT, /* let libcurl decide */ + CURLFTPAUTH_SSL, /* use "AUTH SSL" */ + CURLFTPAUTH_TLS, /* use "AUTH TLS" */ + CURLFTPAUTH_LAST /* not an option, never use */ +} curl_ftpauth; + +/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */ +typedef enum { + CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */ + CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD + again if MKD succeeded, for SFTP this does + similar magic */ + CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD + again even if MKD failed! */ + CURLFTP_CREATE_DIR_LAST /* not an option, never use */ +} curl_ftpcreatedir; + +/* parameter for the CURLOPT_FTP_FILEMETHOD option */ +typedef enum { + CURLFTPMETHOD_DEFAULT, /* let libcurl pick */ + CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */ + CURLFTPMETHOD_NOCWD, /* no CWD at all */ + CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */ + CURLFTPMETHOD_LAST /* not an option, never use */ +} curl_ftpmethod; + +/* bitmask defines for CURLOPT_HEADEROPT */ +#define CURLHEADER_UNIFIED 0 +#define CURLHEADER_SEPARATE (1<<0) + +/* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */ +#define CURLALTSVC_READONLYFILE (1<<2) +#define CURLALTSVC_H1 (1<<3) +#define CURLALTSVC_H2 (1<<4) +#define CURLALTSVC_H3 (1<<5) + + +struct curl_hstsentry { + char *name; + size_t namelen; + unsigned int includeSubDomains:1; + char expire[18]; /* YYYYMMDD HH:MM:SS [null-terminated] */ +}; + +struct curl_index { + size_t index; /* the provided entry's "index" or count */ + size_t total; /* total number of entries to save */ +}; + +typedef enum { + CURLSTS_OK, + CURLSTS_DONE, + CURLSTS_FAIL +} CURLSTScode; + +typedef CURLSTScode (*curl_hstsread_callback)(CURL *easy, + struct curl_hstsentry *e, + void *userp); +typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy, + struct curl_hstsentry *e, + struct curl_index *i, + void *userp); + +/* CURLHSTS_* are bits for the CURLOPT_HSTS option */ +#define CURLHSTS_ENABLE (long)(1<<0) +#define CURLHSTS_READONLYFILE (long)(1<<1) + +/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */ +#define CURLPROTO_HTTP (1<<0) +#define CURLPROTO_HTTPS (1<<1) +#define CURLPROTO_FTP (1<<2) +#define CURLPROTO_FTPS (1<<3) +#define CURLPROTO_SCP (1<<4) +#define CURLPROTO_SFTP (1<<5) +#define CURLPROTO_TELNET (1<<6) +#define CURLPROTO_LDAP (1<<7) +#define CURLPROTO_LDAPS (1<<8) +#define CURLPROTO_DICT (1<<9) +#define CURLPROTO_FILE (1<<10) +#define CURLPROTO_TFTP (1<<11) +#define CURLPROTO_IMAP (1<<12) +#define CURLPROTO_IMAPS (1<<13) +#define CURLPROTO_POP3 (1<<14) +#define CURLPROTO_POP3S (1<<15) +#define CURLPROTO_SMTP (1<<16) +#define CURLPROTO_SMTPS (1<<17) +#define CURLPROTO_RTSP (1<<18) +#define CURLPROTO_RTMP (1<<19) +#define CURLPROTO_RTMPT (1<<20) +#define CURLPROTO_RTMPE (1<<21) +#define CURLPROTO_RTMPTE (1<<22) +#define CURLPROTO_RTMPS (1<<23) +#define CURLPROTO_RTMPTS (1<<24) +#define CURLPROTO_GOPHER (1<<25) +#define CURLPROTO_SMB (1<<26) +#define CURLPROTO_SMBS (1<<27) +#define CURLPROTO_MQTT (1<<28) +#define CURLPROTO_GOPHERS (1<<29) +#define CURLPROTO_ALL (~0) /* enable everything */ + +/* long may be 32 or 64 bits, but we should never depend on anything else + but 32 */ +#define CURLOPTTYPE_LONG 0 +#define CURLOPTTYPE_OBJECTPOINT 10000 +#define CURLOPTTYPE_FUNCTIONPOINT 20000 +#define CURLOPTTYPE_OFF_T 30000 +#define CURLOPTTYPE_BLOB 40000 + +/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the + string options from the header file */ + + +#define CURLOPT(na,t,nu) na = t + nu + +/* CURLOPT aliases that make no run-time difference */ + +/* 'char *' argument to a string with a trailing zero */ +#define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'struct curl_slist *' argument */ +#define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'void *' argument passed untouched to callback */ +#define CURLOPTTYPE_CBPOINT CURLOPTTYPE_OBJECTPOINT + +/* 'long' argument with a set of values/bitmask */ +#define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG + +/* + * All CURLOPT_* values. + */ + +typedef enum { + /* This is the FILE * or void * the regular output should be written to. */ + CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1), + + /* The full URL to get/put */ + CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2), + + /* Port number to connect to, if other than default. */ + CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3), + + /* Name of proxy to use. */ + CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4), + + /* "user:password;options" to use when fetching. */ + CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5), + + /* "user:password" to use with proxy. */ + CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6), + + /* Range to get, specified as an ASCII string. */ + CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7), + + /* not used */ + + /* Specified file stream to upload from (use as input): */ + CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9), + + /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE + * bytes big. */ + CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10), + + /* Function that will be called to store the output (instead of fwrite). The + * parameters will use fwrite() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11), + + /* Function that will be called to read the input (instead of fread). The + * parameters will use fread() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12), + + /* Time-out the read operation after this amount of seconds */ + CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13), + + /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about + * how large the file being sent really is. That allows better error + * checking and better verifies that the upload was successful. -1 means + * unknown size. + * + * For large file support, there is also a _LARGE version of the key + * which takes an off_t type, allowing platforms with larger off_t + * sizes to handle larger files. See below for INFILESIZE_LARGE. + */ + CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14), + + /* POST static input fields. */ + CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15), + + /* Set the referrer page (needed by some CGIs) */ + CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16), + + /* Set the FTP PORT string (interface name, named or numerical IP address) + Use i.e '-' to use default address. */ + CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17), + + /* Set the User-Agent string (examined by some CGIs) */ + CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18), + + /* If the download receives less than "low speed limit" bytes/second + * during "low speed time" seconds, the operations is aborted. + * You could i.e if you have a pretty high speed connection, abort if + * it is less than 2000 bytes/sec during 20 seconds. + */ + + /* Set the "low speed limit" */ + CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19), + + /* Set the "low speed time" */ + CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20), + + /* Set the continuation offset. + * + * Note there is also a _LARGE version of this key which uses + * off_t types, allowing for large file offsets on platforms which + * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE. + */ + CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21), + + /* Set cookie in request: */ + CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22), + + /* This points to a linked list of headers, struct curl_slist kind. This + list is also used for RTSP (in spite of its name) */ + CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23), + + /* This points to a linked list of post entries, struct curl_httppost */ + CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24), + + /* name of the file keeping your private SSL-certificate */ + CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25), + + /* password for the SSL or SSH private key */ + CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26), + + /* send TYPE parameter? */ + CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27), + + /* send linked-list of QUOTE commands */ + CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28), + + /* send FILE * or void * to store headers to, if you use a callback it + is simply passed to the callback unmodified */ + CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29), + + /* point to a file to read the initial cookies from, also enables + "cookie awareness" */ + CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31), + + /* What version to specifically try to use. + See CURL_SSLVERSION defines below. */ + CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32), + + /* What kind of HTTP time condition to use, see defines */ + CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33), + + /* Time to use with the above condition. Specified in number of seconds + since 1 Jan 1970 */ + CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34), + + /* 35 = OBSOLETE */ + + /* Custom request, for customizing the get command like + HTTP: DELETE, TRACE and others + FTP: to use a different list command + */ + CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36), + + /* FILE handle to use instead of stderr */ + CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37), + + /* 38 is not used */ + + /* send linked-list of post-transfer QUOTE commands */ + CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39), + + /* OBSOLETE, do not use! */ + CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40), + + /* talk a lot */ + CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41), + + /* throw the header out too */ + CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42), + + /* shut off the progress meter */ + CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43), + + /* use HEAD to get http document */ + CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44), + + /* no output on http error codes >= 400 */ + CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45), + + /* this is an upload */ + CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46), + + /* HTTP POST method */ + CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47), + + /* bare names when listing directories */ + CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48), + + /* Append instead of overwrite on upload! */ + CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50), + + /* Specify whether to read the user+password from the .netrc or the URL. + * This must be one of the CURL_NETRC_* enums below. */ + CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51), + + /* use Location: Luke! */ + CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52), + + /* transfer data in text/ASCII format */ + CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53), + + /* HTTP PUT */ + CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54), + + /* 55 = OBSOLETE */ + + /* DEPRECATED + * Function that will be called instead of the internal progress display + * function. This function should be defined as the curl_progress_callback + * prototype defines. */ + CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56), + + /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION + callbacks */ + CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57), +#define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA + + /* We want the referrer field set automatically when following locations */ + CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58), + + /* Port of the proxy, can be set in the proxy string as well with: + "[host]:[port]" */ + CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59), + + /* size of the POST input data, if strlen() is not good to use */ + CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60), + + /* tunnel non-http operations through a HTTP proxy */ + CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61), + + /* Set the interface string to use as outgoing network interface */ + CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62), + + /* Set the krb4/5 security level, this also enables krb4/5 awareness. This + * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string + * is set but doesn't match one of these, 'private' will be used. */ + CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63), + + /* Set if we should verify the peer in ssl handshake, set 1 to verify. */ + CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64), + + /* The CApath or CAfile used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65), + + /* 66 = OBSOLETE */ + /* 67 = OBSOLETE */ + + /* Maximum number of http redirects to follow */ + CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68), + + /* Pass a long set to 1 to get the date of the requested document (if + possible)! Pass a zero to shut it off. */ + CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69), + + /* This points to a linked list of telnet options */ + CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70), + + /* Max amount of cached alive connections */ + CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71), + + /* OBSOLETE, do not use! */ + CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72), + + /* 73 = OBSOLETE */ + + /* Set to explicitly use a new connection for the upcoming transfer. + Do not use this unless you're absolutely sure of this, as it makes the + operation slower and is less friendly for the network. */ + CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74), + + /* Set to explicitly forbid the upcoming transfer's connection to be re-used + when done. Do not use this unless you're absolutely sure of this, as it + makes the operation slower and is less friendly for the network. */ + CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75), + + /* Set to a file name that contains random data for libcurl to use to + seed the random engine when doing SSL connects. */ + CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76), + + /* Set to the Entropy Gathering Daemon socket pathname */ + CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77), + + /* Time-out connect operations after this amount of seconds, if connects are + OK within this time, then fine... This only aborts the connect phase. */ + CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78), + + /* Function that will be called to store headers (instead of fwrite). The + * parameters will use fwrite() syntax, make sure to follow them. */ + CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79), + + /* Set this to force the HTTP request to get back to GET. Only really usable + if POST, PUT or a custom request have been used first. + */ + CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80), + + /* Set if we should verify the Common name from the peer certificate in ssl + * handshake, set 1 to check existence, 2 to ensure that it matches the + * provided hostname. */ + CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81), + + /* Specify which file name to write all known cookies in after completed + operation. Set file name to "-" (dash) to make it go to stdout. */ + CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82), + + /* Specify which SSL ciphers to use */ + CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83), + + /* Specify which HTTP version to use! This must be set to one of the + CURL_HTTP_VERSION* enums set below. */ + CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84), + + /* Specifically switch on or off the FTP engine's use of the EPSV command. By + default, that one will always be attempted before the more traditional + PASV command. */ + CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85), + + /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */ + CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86), + + /* name of the file keeping your private SSL-key */ + CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87), + + /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */ + CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88), + + /* crypto engine for the SSL-sub system */ + CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89), + + /* set the crypto engine for the SSL-sub system as default + the param has no meaning... + */ + CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90), + + /* Non-zero value means to use the global dns cache */ + /* DEPRECATED, do not use! */ + CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91), + + /* DNS cache timeout */ + CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92), + + /* send linked-list of pre-transfer QUOTE commands */ + CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93), + + /* set the debug function */ + CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94), + + /* set the data for the debug function */ + CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95), + + /* mark this as start of a cookie session */ + CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96), + + /* The CApath directory used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97), + + /* Instruct libcurl to use a smaller receive buffer */ + CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98), + + /* Instruct libcurl to not use any signal/alarm handlers, even when using + timeouts. This option is useful for multi-threaded applications. + See libcurl-the-guide for more background information. */ + CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99), + + /* Provide a CURLShare for mutexing non-ts data */ + CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100), + + /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default), + CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and + CURLPROXY_SOCKS5. */ + CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101), + + /* Set the Accept-Encoding string. Use this to tell a server you would like + the response to be compressed. Before 7.21.6, this was known as + CURLOPT_ENCODING */ + CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102), + + /* Set pointer to private data */ + CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103), + + /* Set aliases for HTTP 200 in the HTTP Response header */ + CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104), + + /* Continue to send authentication (user+password) when following locations, + even when hostname changed. This can potentially send off the name + and password to whatever host the server decides. */ + CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105), + + /* Specifically switch on or off the FTP engine's use of the EPRT command ( + it also disables the LPRT attempt). By default, those ones will always be + attempted before the good old traditional PORT command. */ + CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_USERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107), + + /* Set the ssl context callback function, currently only for OpenSSL or + WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument. + The function must match the curl_ssl_ctx_callback prototype. */ + CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108), + + /* Set the userdata for the ssl context callback function's third + argument */ + CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109), + + /* FTP Option that causes missing dirs to be created on the remote server. + In 7.19.4 we introduced the convenience enums for this option using the + CURLFTP_CREATE_DIR prefix. + */ + CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110), + + /* Set this to a bitmask value to enable the particular authentications + methods you like. Use this in combination with CURLOPT_PROXYUSERPWD. + Note that setting multiple bits may cause extra network round-trips. */ + CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111), + + /* FTP option that changes the timeout, in seconds, associated with + getting a response. This is different from transfer timeout time and + essentially places a demand on the FTP server to acknowledge commands + in a timely manner. */ + CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112), +#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT + + /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to + tell libcurl to use those IP versions only. This only has effect on + systems with support for more than one, i.e IPv4 _and_ IPv6. */ + CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113), + + /* Set this option to limit the size of a file that will be downloaded from + an HTTP or FTP server. + + Note there is also _LARGE version which adds large file support for + platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */ + CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114), + + /* See the comment for INFILESIZE above, but in short, specifies + * the size of the file being uploaded. -1 means unknown. + */ + CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115), + + /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version + * of this; look above for RESUME_FROM. + */ + CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116), + + /* Sets the maximum size of data that will be downloaded from + * an HTTP or FTP server. See MAXFILESIZE above for the LONG version. + */ + CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117), + + /* Set this option to the file name of your .netrc file you want libcurl + to parse (using the CURLOPT_NETRC option). If not set, libcurl will do + a poor attempt to find the user's home directory and check for a .netrc + file in there. */ + CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118), + + /* Enable SSL/TLS for FTP, pick one of: + CURLUSESSL_TRY - try using SSL, proceed anyway otherwise + CURLUSESSL_CONTROL - SSL for the control connection or fail + CURLUSESSL_ALL - SSL for all communication or fail + */ + CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119), + + /* The _LARGE version of the standard POSTFIELDSIZE option */ + CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120), + + /* Enable/disable the TCP Nagle algorithm */ + CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121), + + /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 123 OBSOLETE. Gone in 7.16.0 */ + /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */ + /* 127 OBSOLETE. Gone in 7.16.0 */ + /* 128 OBSOLETE. Gone in 7.16.0 */ + + /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option + can be used to change libcurl's default action which is to first try + "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK + response has been received. + + Available parameters are: + CURLFTPAUTH_DEFAULT - let libcurl decide + CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS + CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL + */ + CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129), + + CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130), + CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131), + + /* 132 OBSOLETE. Gone in 7.16.0 */ + /* 133 OBSOLETE. Gone in 7.16.0 */ + + /* null-terminated string for pass on to the FTP server when asked for + "account" info */ + CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134), + + /* feed cookie into cookie engine */ + CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135), + + /* ignore Content-Length */ + CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136), + + /* Set to non-zero to skip the IP address received in a 227 PASV FTP server + response. Typically used for FTP-SSL purposes but is not restricted to + that. libcurl will then instead use the same IP address it used for the + control connection. */ + CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137), + + /* Select "file method" to use when doing FTP, see the curl_ftpmethod + above. */ + CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138), + + /* Local port number to bind the socket to */ + CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139), + + /* Number of ports to try, including the first one set with LOCALPORT. + Thus, setting it to 1 will make no additional attempts but the first. + */ + CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140), + + /* no transfer, set up connection and let application use the socket by + extracting it with CURLINFO_LASTSOCKET */ + CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141), + + /* Function that will be called to convert from the + network encoding (instead of using the iconv calls in libcurl) */ + CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142), + + /* Function that will be called to convert to the + network encoding (instead of using the iconv calls in libcurl) */ + CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143), + + /* Function that will be called to convert from UTF8 + (instead of using the iconv calls in libcurl) + Note that this is used only for SSL certificate processing */ + CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144), + + /* if the connection proceeds too quickly then need to slow it down */ + /* limit-rate: maximum number of bytes per second to send or receive */ + CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145), + CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146), + + /* Pointer to command string to send if USER/PASS fails. */ + CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147), + + /* callback function for setting socket options */ + CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148), + CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149), + + /* set to 0 to disable session ID re-use for this transfer, default is + enabled (== 1) */ + CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150), + + /* allowed SSH authentication methods */ + CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151), + + /* Used by scp/sftp to do public/private key authentication */ + CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152), + CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153), + + /* Send CCC (Clear Command Channel) after authentication */ + CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154), + + /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */ + CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155), + CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156), + + /* set to zero to disable the libcurl's decoding and thus pass the raw body + data to the application even when it is encoded/compressed */ + CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157), + CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158), + + /* Permission used when creating new files and directories on the remote + server for protocols that support it, SFTP/SCP/FILE */ + CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159), + CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160), + + /* Set the behavior of POST when redirecting. Values must be set to one + of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */ + CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161), + + /* used by scp/sftp to verify the host's public key */ + CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162), + + /* Callback function for opening socket (instead of socket(2)). Optionally, + callback is able change the address or refuse to connect returning + CURL_SOCKET_BAD. The callback should have type + curl_opensocket_callback */ + CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163), + CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164), + + /* POST volatile input fields. */ + CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165), + + /* set transfer mode (;type=) when doing FTP via an HTTP proxy */ + CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166), + + /* Callback function for seeking in the input stream */ + CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167), + CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168), + + /* CRL file */ + CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169), + + /* Issuer certificate */ + CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170), + + /* (IPv6) Address scope */ + CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171), + + /* Collect certificate chain info and allow it to get retrievable with + CURLINFO_CERTINFO after the transfer is complete. */ + CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172), + + /* "name" and "pwd" to use when fetching. */ + CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173), + CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174), + + /* "name" and "pwd" to use with Proxy when fetching. */ + CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175), + CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176), + + /* Comma separated list of hostnames defining no-proxy zones. These should + match both hostnames directly, and hostnames within a domain. For + example, local.com will match local.com and www.local.com, but NOT + notlocal.com or www.notlocal.com. For compatibility with other + implementations of this, .local.com will be considered to be the same as + local.com. A single * is the only valid wildcard, and effectively + disables the use of proxy. */ + CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177), + + /* block size for TFTP transfers */ + CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178), + + /* Socks Service */ + /* DEPRECATED, do not use! */ + CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179), + + /* Socks Service */ + CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180), + + /* set the bitmask for the protocols that are allowed to be used for the + transfer, which thus helps the app which takes URLs from users or other + external inputs and want to restrict what protocol(s) to deal + with. Defaults to CURLPROTO_ALL. */ + CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181), + + /* set the bitmask for the protocols that libcurl is allowed to follow to, + as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs + to be set in both bitmasks to be allowed to get redirected to. */ + CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182), + + /* set the SSH knownhost file name to use */ + CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183), + + /* set the SSH host key callback, must point to a curl_sshkeycallback + function */ + CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184), + + /* set the SSH host key callback custom pointer */ + CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185), + + /* set the SMTP mail originator */ + CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186), + + /* set the list of SMTP mail receiver(s) */ + CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187), + + /* FTP: send PRET before PASV */ + CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188), + + /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */ + CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189), + + /* The RTSP session identifier */ + CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190), + + /* The RTSP stream URI */ + CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191), + + /* The Transport: header to use in RTSP requests */ + CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192), + + /* Manually initialize the client RTSP CSeq for this handle */ + CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193), + + /* Manually initialize the server RTSP CSeq for this handle */ + CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194), + + /* The stream to pass to INTERLEAVEFUNCTION. */ + CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195), + + /* Let the application define a custom write method for RTP data */ + CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196), + + /* Turn on wildcard matching */ + CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197), + + /* Directory matching callback called before downloading of an + individual file (chunk) started */ + CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198), + + /* Directory matching callback called after the file (chunk) + was downloaded, or skipped */ + CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199), + + /* Change match (fnmatch-like) callback for wildcard matching */ + CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200), + + /* Let the application define custom chunk data pointer */ + CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201), + + /* FNMATCH_FUNCTION user pointer */ + CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202), + + /* send linked-list of name:port:address sets */ + CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203), + + /* Set a username for authenticated TLS */ + CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204), + + /* Set a password for authenticated TLS */ + CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205), + + /* Set authentication type for authenticated TLS */ + CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206), + + /* Set to 1 to enable the "TE:" header in HTTP requests to ask for + compressed transfer-encoded responses. Set to 0 to disable the use of TE: + in outgoing requests. The current default is 0, but it might change in a + future libcurl release. + + libcurl will ask for the compressed methods it knows of, and if that + isn't any, it will not ask for transfer-encoding at all even if this + option is set to 1. + + */ + CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207), + + /* Callback function for closing socket (instead of close(2)). The callback + should have type curl_closesocket_callback */ + CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208), + CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209), + + /* allow GSSAPI credential delegation */ + CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210), + + /* Set the name servers to use for DNS resolution */ + CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211), + + /* Time-out accept operations (currently for FTP only) after this amount + of milliseconds. */ + CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212), + + /* Set TCP keepalive */ + CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213), + + /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */ + CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214), + CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215), + + /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */ + CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216), + + /* Set the SMTP auth originator */ + CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217), + + /* Enable/disable SASL initial response */ + CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218), + + /* Function that will be called instead of the internal progress display + * function. This function should be defined as the curl_xferinfo_callback + * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */ + CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219), + + /* The XOAUTH2 bearer token */ + CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220), + + /* Set the interface string to use as outgoing network + * interface for DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221), + + /* Set the local IPv4 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222), + + /* Set the local IPv6 address to use for outgoing DNS requests. + * Only supported by the c-ares DNS backend */ + CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223), + + /* Set authentication options directly */ + CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224), + + /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */ + CURLOPT(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225), + + /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */ + CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226), + + /* Time to wait for a response to a HTTP request containing an + * Expect: 100-continue header before sending the data anyway. */ + CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227), + + /* This points to a linked list of headers used for proxy requests only, + struct curl_slist kind */ + CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228), + + /* Pass in a bitmask of "header options" */ + CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_VALUES, 229), + + /* The public key in DER form used to validate the peer public key + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230), + + /* Path to Unix domain socket */ + CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231), + + /* Set if we should verify the certificate status. */ + CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232), + + /* Set if we should enable TLS false start. */ + CURLOPT(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233), + + /* Do not squash dot-dot sequences */ + CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234), + + /* Proxy Service Name */ + CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235), + + /* Service Name */ + CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236), + + /* Wait/don't wait for pipe/mutex to clarify */ + CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237), + + /* Set the protocol used when curl is given a URL without a protocol */ + CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238), + + /* Set stream weight, 1 - 256 (default is 16) */ + CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239), + + /* Set stream dependency on another CURL handle */ + CURLOPT(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240), + + /* Set E-xclusive stream dependency on another CURL handle */ + CURLOPT(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241), + + /* Do not send any tftp option requests to the server */ + CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242), + + /* Linked-list of host:port:connect-to-host:connect-to-port, + overrides the URL's host:port (only for the network layer) */ + CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243), + + /* Set TCP Fast Open */ + CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244), + + /* Continue to send data if the server responds early with an + * HTTP status code >= 300 */ + CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245), + + /* The CApath or CAfile used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246), + + /* The CApath directory used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247), + + /* Set if we should verify the proxy in ssl handshake, + set 1 to verify. */ + CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248), + + /* Set if we should verify the Common name from the proxy certificate in ssl + * handshake, set 1 to check existence, 2 to ensure that it matches + * the provided hostname. */ + CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249), + + /* What version to specifically try to use for proxy. + See CURL_SSLVERSION defines below. */ + CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_VALUES, 250), + + /* Set a username for authenticated TLS for proxy */ + CURLOPT(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 251), + + /* Set a password for authenticated TLS for proxy */ + CURLOPT(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 252), + + /* Set authentication type for authenticated TLS for proxy */ + CURLOPT(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253), + + /* name of the file keeping your private SSL-certificate for proxy */ + CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254), + + /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for + proxy */ + CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255), + + /* name of the file keeping your private SSL-key for proxy */ + CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256), + + /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for + proxy */ + CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257), + + /* password for the SSL private key for proxy */ + CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258), + + /* Specify which SSL ciphers to use for proxy */ + CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259), + + /* CRL file for proxy */ + CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260), + + /* Enable/disable specific SSL features with a bitmask for proxy, see + CURLSSLOPT_* */ + CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261), + + /* Name of pre proxy to use. */ + CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262), + + /* The public key in DER form used to validate the proxy public key + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263), + + /* Path to an abstract Unix domain socket */ + CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264), + + /* Suppress proxy CONNECT response headers from user callbacks */ + CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265), + + /* The request target, instead of extracted from the URL */ + CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266), + + /* bitmask of allowed auth methods for connections to SOCKS5 proxies */ + CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267), + + /* Enable/disable SSH compression */ + CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268), + + /* Post MIME data. */ + CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269), + + /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of + seconds since 1 Jan 1970. */ + CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270), + + /* Head start in milliseconds to give happy eyeballs. */ + CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271), + + /* Function that will be called before a resolver request is made */ + CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272), + + /* User data to pass to the resolver start callback. */ + CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_CBPOINT, 273), + + /* send HAProxy PROXY protocol header? */ + CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274), + + /* shuffle addresses before use when DNS returns multiple */ + CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275), + + /* Specify which TLS 1.3 ciphers suites to use */ + CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276), + CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277), + + /* Disallow specifying username/login in URL. */ + CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278), + + /* DNS-over-HTTPS URL */ + CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279), + + /* Preferred buffer size to use for uploads */ + CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280), + + /* Time in ms between connection upkeep calls for long-lived connections. */ + CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281), + + /* Specify URL using CURL URL API. */ + CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282), + + /* add trailing data just after no more data is available */ + CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283), + + /* pointer to be passed to HTTP_TRAILER_FUNCTION */ + CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_CBPOINT, 284), + + /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */ + CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285), + + /* alt-svc control bitmask */ + CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286), + + /* alt-svc cache file name to possibly read from/write to */ + CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287), + + /* maximum age of a connection to consider it for reuse (in seconds) */ + CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288), + + /* SASL authorisation identity */ + CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289), + + /* allow RCPT TO command to fail for some recipients */ + CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290), + + /* the private SSL-certificate as a "blob" */ + CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291), + CURLOPT(CURLOPT_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 292), + CURLOPT(CURLOPT_PROXY_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 293), + CURLOPT(CURLOPT_PROXY_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 294), + CURLOPT(CURLOPT_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 295), + + /* Issuer certificate for proxy */ + CURLOPT(CURLOPT_PROXY_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 296), + CURLOPT(CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 297), + + /* the EC curves requested by the TLS client (RFC 8422, 5.1); + * OpenSSL support via 'set_groups'/'set_curves': + * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html + */ + CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298), + + /* HSTS bitmask */ + CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299), + /* HSTS file name */ + CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300), + + /* HSTS read callback */ + CURLOPT(CURLOPT_HSTSREADFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 301), + CURLOPT(CURLOPT_HSTSREADDATA, CURLOPTTYPE_CBPOINT, 302), + + /* HSTS write callback */ + CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303), + CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304), + + /* Parameters for V4 signature */ + CURLOPT(CURLOPT_AWS_SIGV4, CURLOPTTYPE_STRINGPOINT, 305), + + /* Same as CURLOPT_SSL_VERIFYPEER but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 306), + + /* Same as CURLOPT_SSL_VERIFYHOST but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 307), + + /* Same as CURLOPT_SSL_VERIFYSTATUS but for DoH (DNS-over-HTTPS) servers. */ + CURLOPT(CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 308), + + /* The CA certificates as "blob" used to validate the peer certificate + this option is used only if SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_CAINFO_BLOB, CURLOPTTYPE_BLOB, 309), + + /* The CA certificates as "blob" used to validate the proxy certificate + this option is used only if PROXY_SSL_VERIFYPEER is true */ + CURLOPT(CURLOPT_PROXY_CAINFO_BLOB, CURLOPTTYPE_BLOB, 310), + + CURLOPT_LASTENTRY /* the last unused */ +} CURLoption; + +#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all + the obsolete stuff removed! */ + +/* Backwards compatibility with older names */ +/* These are scheduled to disappear by 2011 */ + +/* This was added in version 7.19.1 */ +#define CURLOPT_POST301 CURLOPT_POSTREDIR + +/* These are scheduled to disappear by 2009 */ + +/* The following were added in 7.17.0 */ +#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_FTPAPPEND CURLOPT_APPEND +#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY +#define CURLOPT_FTP_SSL CURLOPT_USE_SSL + +/* The following were added earlier */ + +#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD +#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL + +#else +/* This is set if CURL_NO_OLDIES is defined at compile-time */ +#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */ +#endif + + + /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host + name resolves addresses using more than one IP protocol version, this + option might be handy to force libcurl to use a specific IP version. */ +#define CURL_IPRESOLVE_WHATEVER 0 /* default, uses addresses to all IP + versions that your system allows */ +#define CURL_IPRESOLVE_V4 1 /* uses only IPv4 addresses/connections */ +#define CURL_IPRESOLVE_V6 2 /* uses only IPv6 addresses/connections */ + + /* three convenient "aliases" that follow the name scheme better */ +#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER + + /* These enums are for use with the CURLOPT_HTTP_VERSION option. */ +enum { + CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd + like the library to choose the best possible + for us! */ + CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */ + CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */ + CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */ + CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */ + CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1 + Upgrade */ + CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback. + Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */ + CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */ +}; + +/* Convenience definition simple because the name of the version is HTTP/2 and + not 2.0. The 2_0 version of the enum name was set while the version was + still planned to be 2.0 and we stick to it for compatibility. */ +#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0 + +/* + * Public API enums for RTSP requests + */ +enum { + CURL_RTSPREQ_NONE, /* first in list */ + CURL_RTSPREQ_OPTIONS, + CURL_RTSPREQ_DESCRIBE, + CURL_RTSPREQ_ANNOUNCE, + CURL_RTSPREQ_SETUP, + CURL_RTSPREQ_PLAY, + CURL_RTSPREQ_PAUSE, + CURL_RTSPREQ_TEARDOWN, + CURL_RTSPREQ_GET_PARAMETER, + CURL_RTSPREQ_SET_PARAMETER, + CURL_RTSPREQ_RECORD, + CURL_RTSPREQ_RECEIVE, + CURL_RTSPREQ_LAST /* last in list */ +}; + + /* These enums are for use with the CURLOPT_NETRC option. */ +enum CURL_NETRC_OPTION { + CURL_NETRC_IGNORED, /* The .netrc will never be read. + * This is the default. */ + CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred + * to one in the .netrc. */ + CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored. + * Unless one is set programmatically, the .netrc + * will be queried. */ + CURL_NETRC_LAST +}; + +enum { + CURL_SSLVERSION_DEFAULT, + CURL_SSLVERSION_TLSv1, /* TLS 1.x */ + CURL_SSLVERSION_SSLv2, + CURL_SSLVERSION_SSLv3, + CURL_SSLVERSION_TLSv1_0, + CURL_SSLVERSION_TLSv1_1, + CURL_SSLVERSION_TLSv1_2, + CURL_SSLVERSION_TLSv1_3, + + CURL_SSLVERSION_LAST /* never use, keep last */ +}; + +enum { + CURL_SSLVERSION_MAX_NONE = 0, + CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16), + CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16), + CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16), + CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16), + CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16), + + /* never use, keep last */ + CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16) +}; + +enum CURL_TLSAUTH { + CURL_TLSAUTH_NONE, + CURL_TLSAUTH_SRP, + CURL_TLSAUTH_LAST /* never use, keep last */ +}; + +/* symbols to use with CURLOPT_POSTREDIR. + CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303 + can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302 + | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */ + +#define CURL_REDIR_GET_ALL 0 +#define CURL_REDIR_POST_301 1 +#define CURL_REDIR_POST_302 2 +#define CURL_REDIR_POST_303 4 +#define CURL_REDIR_POST_ALL \ + (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303) + +typedef enum { + CURL_TIMECOND_NONE, + + CURL_TIMECOND_IFMODSINCE, + CURL_TIMECOND_IFUNMODSINCE, + CURL_TIMECOND_LASTMOD, + + CURL_TIMECOND_LAST +} curl_TimeCond; + +/* Special size_t value signaling a null-terminated string. */ +#define CURL_ZERO_TERMINATED ((size_t) -1) + +/* curl_strequal() and curl_strnequal() are subject for removal in a future + release */ +CURL_EXTERN int curl_strequal(const char *s1, const char *s2); +CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n); + +/* Mime/form handling support. */ +typedef struct curl_mime curl_mime; /* Mime context. */ +typedef struct curl_mimepart curl_mimepart; /* Mime part context. */ + +/* + * NAME curl_mime_init() + * + * DESCRIPTION + * + * Create a mime context and return its handle. The easy parameter is the + * target handle. + */ +CURL_EXTERN curl_mime *curl_mime_init(CURL *easy); + +/* + * NAME curl_mime_free() + * + * DESCRIPTION + * + * release a mime handle and its substructures. + */ +CURL_EXTERN void curl_mime_free(curl_mime *mime); + +/* + * NAME curl_mime_addpart() + * + * DESCRIPTION + * + * Append a new empty part to the given mime context and return a handle to + * the created part. + */ +CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime); + +/* + * NAME curl_mime_name() + * + * DESCRIPTION + * + * Set mime/form part name. + */ +CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name); + +/* + * NAME curl_mime_filename() + * + * DESCRIPTION + * + * Set mime part remote file name. + */ +CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part, + const char *filename); + +/* + * NAME curl_mime_type() + * + * DESCRIPTION + * + * Set mime part type. + */ +CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype); + +/* + * NAME curl_mime_encoder() + * + * DESCRIPTION + * + * Set mime data transfer encoder. + */ +CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part, + const char *encoding); + +/* + * NAME curl_mime_data() + * + * DESCRIPTION + * + * Set mime part data source from memory data, + */ +CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part, + const char *data, size_t datasize); + +/* + * NAME curl_mime_filedata() + * + * DESCRIPTION + * + * Set mime part data source from named file. + */ +CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part, + const char *filename); + +/* + * NAME curl_mime_data_cb() + * + * DESCRIPTION + * + * Set mime part data source from callback function. + */ +CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part, + curl_off_t datasize, + curl_read_callback readfunc, + curl_seek_callback seekfunc, + curl_free_callback freefunc, + void *arg); + +/* + * NAME curl_mime_subparts() + * + * DESCRIPTION + * + * Set mime part data source from subparts. + */ +CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part, + curl_mime *subparts); +/* + * NAME curl_mime_headers() + * + * DESCRIPTION + * + * Set mime part headers. + */ +CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part, + struct curl_slist *headers, + int take_ownership); + +typedef enum { + CURLFORM_NOTHING, /********* the first one is unused ************/ + CURLFORM_COPYNAME, + CURLFORM_PTRNAME, + CURLFORM_NAMELENGTH, + CURLFORM_COPYCONTENTS, + CURLFORM_PTRCONTENTS, + CURLFORM_CONTENTSLENGTH, + CURLFORM_FILECONTENT, + CURLFORM_ARRAY, + CURLFORM_OBSOLETE, + CURLFORM_FILE, + + CURLFORM_BUFFER, + CURLFORM_BUFFERPTR, + CURLFORM_BUFFERLENGTH, + + CURLFORM_CONTENTTYPE, + CURLFORM_CONTENTHEADER, + CURLFORM_FILENAME, + CURLFORM_END, + CURLFORM_OBSOLETE2, + + CURLFORM_STREAM, + CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */ + + CURLFORM_LASTENTRY /* the last unused */ +} CURLformoption; + +/* structure to be used as parameter for CURLFORM_ARRAY */ +struct curl_forms { + CURLformoption option; + const char *value; +}; + +/* use this for multipart formpost building */ +/* Returns code for curl_formadd() + * + * Returns: + * CURL_FORMADD_OK on success + * CURL_FORMADD_MEMORY if the FormInfo allocation fails + * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form + * CURL_FORMADD_NULL if a null pointer was given for a char + * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed + * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used + * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error) + * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated + * CURL_FORMADD_MEMORY if some allocation for string copying failed. + * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array + * + ***************************************************************************/ +typedef enum { + CURL_FORMADD_OK, /* first, no error */ + + CURL_FORMADD_MEMORY, + CURL_FORMADD_OPTION_TWICE, + CURL_FORMADD_NULL, + CURL_FORMADD_UNKNOWN_OPTION, + CURL_FORMADD_INCOMPLETE, + CURL_FORMADD_ILLEGAL_ARRAY, + CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */ + + CURL_FORMADD_LAST /* last */ +} CURLFORMcode; + +/* + * NAME curl_formadd() + * + * DESCRIPTION + * + * Pretty advanced function for building multi-part formposts. Each invoke + * adds one part that together construct a full post. Then use + * CURLOPT_HTTPPOST to send it off to libcurl. + */ +CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost, + struct curl_httppost **last_post, + ...); + +/* + * callback function for curl_formget() + * The void *arg pointer will be the one passed as second argument to + * curl_formget(). + * The character buffer passed to it must not be freed. + * Should return the buffer length passed to it as the argument "len" on + * success. + */ +typedef size_t (*curl_formget_callback)(void *arg, const char *buf, + size_t len); + +/* + * NAME curl_formget() + * + * DESCRIPTION + * + * Serialize a curl_httppost struct built with curl_formadd(). + * Accepts a void pointer as second argument which will be passed to + * the curl_formget_callback function. + * Returns 0 on success. + */ +CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg, + curl_formget_callback append); +/* + * NAME curl_formfree() + * + * DESCRIPTION + * + * Free a multipart formpost previously built with curl_formadd(). + */ +CURL_EXTERN void curl_formfree(struct curl_httppost *form); + +/* + * NAME curl_getenv() + * + * DESCRIPTION + * + * Returns a malloc()'ed string that MUST be curl_free()ed after usage is + * complete. DEPRECATED - see lib/README.curlx + */ +CURL_EXTERN char *curl_getenv(const char *variable); + +/* + * NAME curl_version() + * + * DESCRIPTION + * + * Returns a static ascii string of the libcurl version. + */ +CURL_EXTERN char *curl_version(void); + +/* + * NAME curl_easy_escape() + * + * DESCRIPTION + * + * Escapes URL strings (converts all letters consider illegal in URLs to their + * %XX versions). This function returns a new allocated string or NULL if an + * error occurred. + */ +CURL_EXTERN char *curl_easy_escape(CURL *handle, + const char *string, + int length); + +/* the previous version: */ +CURL_EXTERN char *curl_escape(const char *string, + int length); + + +/* + * NAME curl_easy_unescape() + * + * DESCRIPTION + * + * Unescapes URL encoding in strings (converts all %XX codes to their 8bit + * versions). This function returns a new allocated string or NULL if an error + * occurred. + * Conversion Note: On non-ASCII platforms the ASCII %XX codes are + * converted into the host encoding. + */ +CURL_EXTERN char *curl_easy_unescape(CURL *handle, + const char *string, + int length, + int *outlength); + +/* the previous version */ +CURL_EXTERN char *curl_unescape(const char *string, + int length); + +/* + * NAME curl_free() + * + * DESCRIPTION + * + * Provided for de-allocation in the same translation unit that did the + * allocation. Added in libcurl 7.10 + */ +CURL_EXTERN void curl_free(void *p); + +/* + * NAME curl_global_init() + * + * DESCRIPTION + * + * curl_global_init() should be invoked exactly once for each application that + * uses libcurl and before any call of other libcurl functions. + * + * This function is not thread-safe! + */ +CURL_EXTERN CURLcode curl_global_init(long flags); + +/* + * NAME curl_global_init_mem() + * + * DESCRIPTION + * + * curl_global_init() or curl_global_init_mem() should be invoked exactly once + * for each application that uses libcurl. This function can be used to + * initialize libcurl and set user defined memory management callback + * functions. Users can implement memory management routines to check for + * memory leaks, check for mis-use of the curl library etc. User registered + * callback routines will be invoked by this library instead of the system + * memory management routines like malloc, free etc. + */ +CURL_EXTERN CURLcode curl_global_init_mem(long flags, + curl_malloc_callback m, + curl_free_callback f, + curl_realloc_callback r, + curl_strdup_callback s, + curl_calloc_callback c); + +/* + * NAME curl_global_cleanup() + * + * DESCRIPTION + * + * curl_global_cleanup() should be invoked exactly once for each application + * that uses libcurl + */ +CURL_EXTERN void curl_global_cleanup(void); + +/* linked-list structure for the CURLOPT_QUOTE option (and other) */ +struct curl_slist { + char *data; + struct curl_slist *next; +}; + +/* + * NAME curl_global_sslset() + * + * DESCRIPTION + * + * When built with multiple SSL backends, curl_global_sslset() allows to + * choose one. This function can only be called once, and it must be called + * *before* curl_global_init(). + * + * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The + * backend can also be specified via the name parameter (passing -1 as id). + * If both id and name are specified, the name will be ignored. If neither id + * nor name are specified, the function will fail with + * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the + * NULL-terminated list of available backends. + * + * Upon success, the function returns CURLSSLSET_OK. + * + * If the specified SSL backend is not available, the function returns + * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated + * list of available SSL backends. + * + * The SSL backend can be set only once. If it has already been set, a + * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE. + */ + +struct curl_ssl_backend { + curl_sslbackend id; + const char *name; +}; +typedef struct curl_ssl_backend curl_ssl_backend; + +typedef enum { + CURLSSLSET_OK = 0, + CURLSSLSET_UNKNOWN_BACKEND, + CURLSSLSET_TOO_LATE, + CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */ +} CURLsslset; + +CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name, + const curl_ssl_backend ***avail); + +/* + * NAME curl_slist_append() + * + * DESCRIPTION + * + * Appends a string to a linked list. If no list exists, it will be created + * first. Returns the new list, after appending. + */ +CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *, + const char *); + +/* + * NAME curl_slist_free_all() + * + * DESCRIPTION + * + * free a previously built curl_slist. + */ +CURL_EXTERN void curl_slist_free_all(struct curl_slist *); + +/* + * NAME curl_getdate() + * + * DESCRIPTION + * + * Returns the time, in seconds since 1 Jan 1970 of the time string given in + * the first argument. The time argument in the second parameter is unused + * and should be set to NULL. + */ +CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused); + +/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS + and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */ +struct curl_certinfo { + int num_of_certs; /* number of certificates with information */ + struct curl_slist **certinfo; /* for each index in this array, there's a + linked list with textual information in the + format "name: value" */ +}; + +/* Information about the SSL library used and the respective internal SSL + handle, which can be used to obtain further information regarding the + connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */ +struct curl_tlssessioninfo { + curl_sslbackend backend; + void *internals; +}; + +#define CURLINFO_STRING 0x100000 +#define CURLINFO_LONG 0x200000 +#define CURLINFO_DOUBLE 0x300000 +#define CURLINFO_SLIST 0x400000 +#define CURLINFO_PTR 0x400000 /* same as SLIST */ +#define CURLINFO_SOCKET 0x500000 +#define CURLINFO_OFF_T 0x600000 +#define CURLINFO_MASK 0x0fffff +#define CURLINFO_TYPEMASK 0xf00000 + +typedef enum { + CURLINFO_NONE, /* first, never use this */ + CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1, + CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2, + CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3, + CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4, + CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5, + CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6, + CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7, + CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7, + CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8, + CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8, + CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9, + CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9, + CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10, + CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10, + CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11, + CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12, + CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13, + CURLINFO_FILETIME = CURLINFO_LONG + 14, + CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14, + CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15, + CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15, + CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16, + CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16, + CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17, + CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18, + CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19, + CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20, + CURLINFO_PRIVATE = CURLINFO_STRING + 21, + CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22, + CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23, + CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24, + CURLINFO_OS_ERRNO = CURLINFO_LONG + 25, + CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26, + CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27, + CURLINFO_COOKIELIST = CURLINFO_SLIST + 28, + CURLINFO_LASTSOCKET = CURLINFO_LONG + 29, + CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30, + CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31, + CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32, + CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33, + CURLINFO_CERTINFO = CURLINFO_PTR + 34, + CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35, + CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36, + CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37, + CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38, + CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39, + CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40, + CURLINFO_LOCAL_IP = CURLINFO_STRING + 41, + CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42, + CURLINFO_TLS_SESSION = CURLINFO_PTR + 43, + CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44, + CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45, + CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46, + CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47, + CURLINFO_PROTOCOL = CURLINFO_LONG + 48, + CURLINFO_SCHEME = CURLINFO_STRING + 49, + CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50, + CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51, + CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52, + CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53, + CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54, + CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55, + CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56, + CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57, + CURLINFO_EFFECTIVE_METHOD = CURLINFO_STRING + 58, + CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59, + CURLINFO_REFERER = CURLINFO_STRING + 60, + + CURLINFO_LASTONE = 60 +} CURLINFO; + +/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as + CURLINFO_HTTP_CODE */ +#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE + +typedef enum { + CURLCLOSEPOLICY_NONE, /* first, never use this */ + + CURLCLOSEPOLICY_OLDEST, + CURLCLOSEPOLICY_LEAST_RECENTLY_USED, + CURLCLOSEPOLICY_LEAST_TRAFFIC, + CURLCLOSEPOLICY_SLOWEST, + CURLCLOSEPOLICY_CALLBACK, + + CURLCLOSEPOLICY_LAST /* last, never use this */ +} curl_closepolicy; + +#define CURL_GLOBAL_SSL (1<<0) /* no purpose since since 7.57.0 */ +#define CURL_GLOBAL_WIN32 (1<<1) +#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32) +#define CURL_GLOBAL_NOTHING 0 +#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL +#define CURL_GLOBAL_ACK_EINTR (1<<2) + + +/***************************************************************************** + * Setup defines, protos etc for the sharing stuff. + */ + +/* Different data locks for a single share */ +typedef enum { + CURL_LOCK_DATA_NONE = 0, + /* CURL_LOCK_DATA_SHARE is used internally to say that + * the locking is just made to change the internal state of the share + * itself. + */ + CURL_LOCK_DATA_SHARE, + CURL_LOCK_DATA_COOKIE, + CURL_LOCK_DATA_DNS, + CURL_LOCK_DATA_SSL_SESSION, + CURL_LOCK_DATA_CONNECT, + CURL_LOCK_DATA_PSL, + CURL_LOCK_DATA_LAST +} curl_lock_data; + +/* Different lock access types */ +typedef enum { + CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */ + CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */ + CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */ + CURL_LOCK_ACCESS_LAST /* never use */ +} curl_lock_access; + +typedef void (*curl_lock_function)(CURL *handle, + curl_lock_data data, + curl_lock_access locktype, + void *userptr); +typedef void (*curl_unlock_function)(CURL *handle, + curl_lock_data data, + void *userptr); + + +typedef enum { + CURLSHE_OK, /* all is fine */ + CURLSHE_BAD_OPTION, /* 1 */ + CURLSHE_IN_USE, /* 2 */ + CURLSHE_INVALID, /* 3 */ + CURLSHE_NOMEM, /* 4 out of memory */ + CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */ + CURLSHE_LAST /* never use */ +} CURLSHcode; + +typedef enum { + CURLSHOPT_NONE, /* don't use */ + CURLSHOPT_SHARE, /* specify a data type to share */ + CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */ + CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */ + CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */ + CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock + callback functions */ + CURLSHOPT_LAST /* never use */ +} CURLSHoption; + +CURL_EXTERN CURLSH *curl_share_init(void); +CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...); +CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *); + +/**************************************************************************** + * Structures for querying information about the curl library at runtime. + */ + +typedef enum { + CURLVERSION_FIRST, + CURLVERSION_SECOND, + CURLVERSION_THIRD, + CURLVERSION_FOURTH, + CURLVERSION_FIFTH, + CURLVERSION_SIXTH, + CURLVERSION_SEVENTH, + CURLVERSION_EIGHTH, + CURLVERSION_NINTH, + CURLVERSION_TENTH, + CURLVERSION_LAST /* never actually use this */ +} CURLversion; + +/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by + basically all programs ever that want to get version information. It is + meant to be a built-in version number for what kind of struct the caller + expects. If the struct ever changes, we redefine the NOW to another enum + from above. */ +#define CURLVERSION_NOW CURLVERSION_TENTH + +struct curl_version_info_data { + CURLversion age; /* age of the returned struct */ + const char *version; /* LIBCURL_VERSION */ + unsigned int version_num; /* LIBCURL_VERSION_NUM */ + const char *host; /* OS/host/cpu/machine when configured */ + int features; /* bitmask, see defines below */ + const char *ssl_version; /* human readable string */ + long ssl_version_num; /* not used anymore, always 0 */ + const char *libz_version; /* human readable string */ + /* protocols is terminated by an entry with a NULL protoname */ + const char * const *protocols; + + /* The fields below this were added in CURLVERSION_SECOND */ + const char *ares; + int ares_num; + + /* This field was added in CURLVERSION_THIRD */ + const char *libidn; + + /* These field were added in CURLVERSION_FOURTH */ + + /* Same as '_libiconv_version' if built with HAVE_ICONV */ + int iconv_ver_num; + + const char *libssh_version; /* human readable string */ + + /* These fields were added in CURLVERSION_FIFTH */ + unsigned int brotli_ver_num; /* Numeric Brotli version + (MAJOR << 24) | (MINOR << 12) | PATCH */ + const char *brotli_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_SIXTH */ + unsigned int nghttp2_ver_num; /* Numeric nghttp2 version + (MAJOR << 16) | (MINOR << 8) | PATCH */ + const char *nghttp2_version; /* human readable string. */ + const char *quic_version; /* human readable quic (+ HTTP/3) library + + version or NULL */ + + /* These fields were added in CURLVERSION_SEVENTH */ + const char *cainfo; /* the built-in default CURLOPT_CAINFO, might + be NULL */ + const char *capath; /* the built-in default CURLOPT_CAPATH, might + be NULL */ + + /* These fields were added in CURLVERSION_EIGHTH */ + unsigned int zstd_ver_num; /* Numeric Zstd version + (MAJOR << 24) | (MINOR << 12) | PATCH */ + const char *zstd_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_NINTH */ + const char *hyper_version; /* human readable string. */ + + /* These fields were added in CURLVERSION_TENTH */ + const char *gsasl_version; /* human readable string. */ +}; +typedef struct curl_version_info_data curl_version_info_data; + +#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */ +#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported + (deprecated) */ +#define CURL_VERSION_SSL (1<<2) /* SSL options are present */ +#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */ +#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */ +#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported + (deprecated) */ +#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */ +#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */ +#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */ +#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */ +#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are + supported */ +#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */ +#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */ +#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */ +#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */ +#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper + is supported */ +#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */ +#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */ +#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */ +#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */ +#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used + for cookie domain verification */ +#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */ +#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */ +#define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */ +#define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */ +#define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */ +#define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */ +#define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */ +#define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */ +#define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */ + + /* + * NAME curl_version_info() + * + * DESCRIPTION + * + * This function returns a pointer to a static copy of the version info + * struct. See above. + */ +CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion); + +/* + * NAME curl_easy_strerror() + * + * DESCRIPTION + * + * The curl_easy_strerror function may be used to turn a CURLcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_easy_strerror(CURLcode); + +/* + * NAME curl_share_strerror() + * + * DESCRIPTION + * + * The curl_share_strerror function may be used to turn a CURLSHcode value + * into the equivalent human readable error string. This is useful + * for printing meaningful error messages. + */ +CURL_EXTERN const char *curl_share_strerror(CURLSHcode); + +/* + * NAME curl_easy_pause() + * + * DESCRIPTION + * + * The curl_easy_pause function pauses or unpauses transfers. Select the new + * state by setting the bitmask, use the convenience defines below. + * + */ +CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask); + +#define CURLPAUSE_RECV (1<<0) +#define CURLPAUSE_RECV_CONT (0) + +#define CURLPAUSE_SEND (1<<2) +#define CURLPAUSE_SEND_CONT (0) + +#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND) +#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT) + +#ifdef __cplusplus +} +#endif + +/* unfortunately, the easy.h and multi.h include files need options and info + stuff before they can be included! */ +#include "easy.h" /* nothing in curl is fun without the easy stuff */ +#include "multi.h" +#include "urlapi.h" +#include "options.h" + +/* the typechecker doesn't work in C++ (yet) */ +#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \ + ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \ + !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK) +#include "typecheck-gcc.h" +#else +#if defined(__STDC__) && (__STDC__ >= 1) +/* This preprocessor magic that replaces a call with the exact same call is + only done to make sure application authors pass exactly three arguments + to these functions. */ +#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param) +#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg) +#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) +#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) +#endif /* __STDC__ >= 1 */ +#endif /* gcc >= 4.3 && !__cplusplus */ + +#endif /* CURLINC_CURL_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curlver.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curlver.h new file mode 100644 index 0000000000000000000000000000000000000000..0eef644a0db48dd9070cf4439a27456dfefcd879 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/curlver.h @@ -0,0 +1,77 @@ +#ifndef CURLINC_CURLVER_H +#define CURLINC_CURLVER_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2021, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* This header file contains nothing but libcurl version info, generated by + a script at release-time. This was made its own header file in 7.11.2 */ + +/* This is the global package copyright */ +#define LIBCURL_COPYRIGHT "1996 - 2021 Daniel Stenberg, ." + +/* This is the version number of the libcurl package from which this header + file origins: */ +#define LIBCURL_VERSION "7.78.0-DEV" + +/* The numeric version number is also available "in parts" by using these + defines: */ +#define LIBCURL_VERSION_MAJOR 7 +#define LIBCURL_VERSION_MINOR 78 +#define LIBCURL_VERSION_PATCH 0 + +/* This is the numeric version of the libcurl version number, meant for easier + parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will + always follow this syntax: + + 0xXXYYZZ + + Where XX, YY and ZZ are the main version, release and patch numbers in + hexadecimal (using 8 bits each). All three numbers are always represented + using two digits. 1.2 would appear as "0x010200" while version 9.11.7 + appears as "0x090b07". + + This 6-digit (24 bits) hexadecimal number does not show pre-release number, + and it is always a greater number in a more recent release. It makes + comparisons with greater than and less than work. + + Note: This define is the full hex number and _does not_ use the + CURL_VERSION_BITS() macro since curl's own configure script greps for it + and needs it to contain the full number. +*/ +#define LIBCURL_VERSION_NUM 0x074e00 + +/* + * This is the date and time when the full source package was created. The + * timestamp is not stored in git, as the timestamp is properly set in the + * tarballs by the maketgz script. + * + * The format of the date follows this template: + * + * "2007-11-23" + */ +#define LIBCURL_TIMESTAMP "[unreleased]" + +#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z)) +#define CURL_AT_LEAST_VERSION(x,y,z) \ + (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) + +#endif /* CURLINC_CURLVER_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/easy.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/easy.h new file mode 100644 index 0000000000000000000000000000000000000000..2dbfb26b5b7f4e398ec32215a1bf8455d81d1914 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/easy.h @@ -0,0 +1,123 @@ +#ifndef CURLINC_EASY_H +#define CURLINC_EASY_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#ifdef __cplusplus +extern "C" { +#endif + +/* Flag bits in the curl_blob struct: */ +#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */ +#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */ + +struct curl_blob { + void *data; + size_t len; + unsigned int flags; /* bit 0 is defined, the rest are reserved and should be + left zeroes */ +}; + +CURL_EXTERN CURL *curl_easy_init(void); +CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...); +CURL_EXTERN CURLcode curl_easy_perform(CURL *curl); +CURL_EXTERN void curl_easy_cleanup(CURL *curl); + +/* + * NAME curl_easy_getinfo() + * + * DESCRIPTION + * + * Request internal information from the curl session with this function. The + * third argument MUST be a pointer to a long, a pointer to a char * or a + * pointer to a double (as the documentation describes elsewhere). The data + * pointed to will be filled in accordingly and can be relied upon only if the + * function returns CURLE_OK. This function is intended to get used *AFTER* a + * performed transfer, all results from this function are undefined until the + * transfer is completed. + */ +CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...); + + +/* + * NAME curl_easy_duphandle() + * + * DESCRIPTION + * + * Creates a new curl session handle with the same options set for the handle + * passed in. Duplicating a handle could only be a matter of cloning data and + * options, internal state info and things like persistent connections cannot + * be transferred. It is useful in multithreaded applications when you can run + * curl_easy_duphandle() for each new thread to avoid a series of identical + * curl_easy_setopt() invokes in every thread. + */ +CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl); + +/* + * NAME curl_easy_reset() + * + * DESCRIPTION + * + * Re-initializes a CURL handle to the default values. This puts back the + * handle to the same state as it was in when it was just created. + * + * It does keep: live connections, the Session ID cache, the DNS cache and the + * cookies. + */ +CURL_EXTERN void curl_easy_reset(CURL *curl); + +/* + * NAME curl_easy_recv() + * + * DESCRIPTION + * + * Receives data from the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen, + size_t *n); + +/* + * NAME curl_easy_send() + * + * DESCRIPTION + * + * Sends data over the connected socket. Use after successful + * curl_easy_perform() with CURLOPT_CONNECT_ONLY option. + */ +CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer, + size_t buflen, size_t *n); + + +/* + * NAME curl_easy_upkeep() + * + * DESCRIPTION + * + * Performs connection upkeep for the given session handle. + */ +CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/mprintf.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/mprintf.h new file mode 100644 index 0000000000000000000000000000000000000000..3549552dba63062f8904770055a5ed781517c48f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/mprintf.h @@ -0,0 +1,50 @@ +#ifndef CURLINC_MPRINTF_H +#define CURLINC_MPRINTF_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include +#include /* needed for FILE */ +#include "curl.h" /* for CURL_EXTERN */ + +#ifdef __cplusplus +extern "C" { +#endif + +CURL_EXTERN int curl_mprintf(const char *format, ...); +CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...); +CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...); +CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength, + const char *format, ...); +CURL_EXTERN int curl_mvprintf(const char *format, va_list args); +CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args); +CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args); +CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength, + const char *format, va_list args); +CURL_EXTERN char *curl_maprintf(const char *format, ...); +CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args); + +#ifdef __cplusplus +} +#endif + +#endif /* CURLINC_MPRINTF_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/multi.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/multi.h new file mode 100644 index 0000000000000000000000000000000000000000..37f9829b3b3191182d46bd5fa847c7fedb39524e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/multi.h @@ -0,0 +1,456 @@ +#ifndef CURLINC_MULTI_H +#define CURLINC_MULTI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +/* + This is an "external" header file. Don't give away any internals here! + + GOALS + + o Enable a "pull" interface. The application that uses libcurl decides where + and when to ask libcurl to get/send data. + + o Enable multiple simultaneous transfers in the same thread without making it + complicated for the application. + + o Enable the application to select() on its own file descriptors and curl's + file descriptors simultaneous easily. + +*/ + +/* + * This header file should not really need to include "curl.h" since curl.h + * itself includes this file and we expect user applications to do #include + * without the need for especially including multi.h. + * + * For some reason we added this include here at one point, and rather than to + * break existing (wrongly written) libcurl applications, we leave it as-is + * but with this warning attached. + */ +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER) +typedef struct Curl_multi CURLM; +#else +typedef void CURLM; +#endif + +typedef enum { + CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or + curl_multi_socket*() soon */ + CURLM_OK, + CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */ + CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */ + CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */ + CURLM_INTERNAL_ERROR, /* this is a libcurl bug */ + CURLM_BAD_SOCKET, /* the passed in socket argument did not match */ + CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */ + CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was + attempted to get added - again */ + CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a + callback */ + CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */ + CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */ + CURLM_LAST +} CURLMcode; + +/* just to make code nicer when using curl_multi_socket() you can now check + for CURLM_CALL_MULTI_SOCKET too in the same style it works for + curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */ +#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM + +/* bitmask bits for CURLMOPT_PIPELINING */ +#define CURLPIPE_NOTHING 0L +#define CURLPIPE_HTTP1 1L +#define CURLPIPE_MULTIPLEX 2L + +typedef enum { + CURLMSG_NONE, /* first, not used */ + CURLMSG_DONE, /* This easy handle has completed. 'result' contains + the CURLcode of the transfer */ + CURLMSG_LAST /* last, not used */ +} CURLMSG; + +struct CURLMsg { + CURLMSG msg; /* what this message means */ + CURL *easy_handle; /* the handle it concerns */ + union { + void *whatever; /* message-specific data */ + CURLcode result; /* return code for transfer */ + } data; +}; +typedef struct CURLMsg CURLMsg; + +/* Based on poll(2) structure and values. + * We don't use pollfd and POLL* constants explicitly + * to cover platforms without poll(). */ +#define CURL_WAIT_POLLIN 0x0001 +#define CURL_WAIT_POLLPRI 0x0002 +#define CURL_WAIT_POLLOUT 0x0004 + +struct curl_waitfd { + curl_socket_t fd; + short events; + short revents; /* not supported yet */ +}; + +/* + * Name: curl_multi_init() + * + * Desc: inititalize multi-style curl usage + * + * Returns: a new CURLM handle to use in all 'curl_multi' functions. + */ +CURL_EXTERN CURLM *curl_multi_init(void); + +/* + * Name: curl_multi_add_handle() + * + * Desc: add a standard curl handle to the multi stack + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle, + CURL *curl_handle); + + /* + * Name: curl_multi_remove_handle() + * + * Desc: removes a curl handle from the multi stack again + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle, + CURL *curl_handle); + + /* + * Name: curl_multi_fdset() + * + * Desc: Ask curl for its fd_set sets. The app can use these to select() or + * poll() on. We want curl_multi_perform() called as soon as one of + * them are ready. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle, + fd_set *read_fd_set, + fd_set *write_fd_set, + fd_set *exc_fd_set, + int *max_fd); + +/* + * Name: curl_multi_wait() + * + * Desc: Poll on all fds within a CURLM set as well as any + * additional fds passed to the function. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret); + +/* + * Name: curl_multi_poll() + * + * Desc: Poll on all fds within a CURLM set as well as any + * additional fds passed to the function. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle, + struct curl_waitfd extra_fds[], + unsigned int extra_nfds, + int timeout_ms, + int *ret); + +/* + * Name: curl_multi_wakeup() + * + * Desc: wakes up a sleeping curl_multi_poll call. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle); + + /* + * Name: curl_multi_perform() + * + * Desc: When the app thinks there's data available for curl it calls this + * function to read/write whatever there is right now. This returns + * as soon as the reads and writes are done. This function does not + * require that there actually is data available for reading or that + * data can be written, it can be called just in case. It returns + * the number of handles that still transfer data in the second + * argument's integer-pointer. + * + * Returns: CURLMcode type, general multi error code. *NOTE* that this only + * returns errors etc regarding the whole multi stack. There might + * still have occurred problems on individual transfers even when + * this returns OK. + */ +CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle, + int *running_handles); + + /* + * Name: curl_multi_cleanup() + * + * Desc: Cleans up and removes a whole multi stack. It does not free or + * touch any individual easy handles in any way. We need to define + * in what state those handles will be if this function is called + * in the middle of a transfer. + * + * Returns: CURLMcode type, general multi error code. + */ +CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle); + +/* + * Name: curl_multi_info_read() + * + * Desc: Ask the multi handle if there's any messages/informationals from + * the individual transfers. Messages include informationals such as + * error code from the transfer or just the fact that a transfer is + * completed. More details on these should be written down as well. + * + * Repeated calls to this function will return a new struct each + * time, until a special "end of msgs" struct is returned as a signal + * that there is no more to get at this point. + * + * The data the returned pointer points to will not survive calling + * curl_multi_cleanup(). + * + * The 'CURLMsg' struct is meant to be very simple and only contain + * very basic information. If more involved information is wanted, + * we will provide the particular "transfer handle" in that struct + * and that should/could/would be used in subsequent + * curl_easy_getinfo() calls (or similar). The point being that we + * must never expose complex structs to applications, as then we'll + * undoubtably get backwards compatibility problems in the future. + * + * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out + * of structs. It also writes the number of messages left in the + * queue (after this read) in the integer the second argument points + * to. + */ +CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle, + int *msgs_in_queue); + +/* + * Name: curl_multi_strerror() + * + * Desc: The curl_multi_strerror function may be used to turn a CURLMcode + * value into the equivalent human readable error string. This is + * useful for printing meaningful error messages. + * + * Returns: A pointer to a null-terminated error message. + */ +CURL_EXTERN const char *curl_multi_strerror(CURLMcode); + +/* + * Name: curl_multi_socket() and + * curl_multi_socket_all() + * + * Desc: An alternative version of curl_multi_perform() that allows the + * application to pass in one of the file descriptors that have been + * detected to have "action" on them and let libcurl perform. + * See man page for details. + */ +#define CURL_POLL_NONE 0 +#define CURL_POLL_IN 1 +#define CURL_POLL_OUT 2 +#define CURL_POLL_INOUT 3 +#define CURL_POLL_REMOVE 4 + +#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD + +#define CURL_CSELECT_IN 0x01 +#define CURL_CSELECT_OUT 0x02 +#define CURL_CSELECT_ERR 0x04 + +typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */ + curl_socket_t s, /* socket */ + int what, /* see above */ + void *userp, /* private callback + pointer */ + void *socketp); /* private socket + pointer */ +/* + * Name: curl_multi_timer_callback + * + * Desc: Called by libcurl whenever the library detects a change in the + * maximum number of milliseconds the app is allowed to wait before + * curl_multi_socket() or curl_multi_perform() must be called + * (to allow libcurl's timed events to take place). + * + * Returns: The callback should return zero. + */ +typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */ + long timeout_ms, /* see above */ + void *userp); /* private callback + pointer */ + +CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s, + int *running_handles); + +CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle, + curl_socket_t s, + int ev_bitmask, + int *running_handles); + +CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle, + int *running_handles); + +#ifndef CURL_ALLOW_OLD_MULTI_SOCKET +/* This macro below was added in 7.16.3 to push users who recompile to use + the new curl_multi_socket_action() instead of the old curl_multi_socket() +*/ +#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z) +#endif + +/* + * Name: curl_multi_timeout() + * + * Desc: Returns the maximum number of milliseconds the app is allowed to + * wait before curl_multi_socket() or curl_multi_perform() must be + * called (to allow libcurl's timed events to take place). + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle, + long *milliseconds); + +typedef enum { + /* This is the socket callback function pointer */ + CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1), + + /* This is the argument passed to the socket callback */ + CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2), + + /* set to 1 to enable pipelining for this multi handle */ + CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3), + + /* This is the timer callback function pointer */ + CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4), + + /* This is the argument passed to the timer callback */ + CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5), + + /* maximum number of entries in the connection cache */ + CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6), + + /* maximum number of (pipelining) connections to one host */ + CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7), + + /* maximum number of requests in a pipeline */ + CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8), + + /* a connection with a content-length longer than this + will not be considered for pipelining */ + CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9), + + /* a connection with a chunk length longer than this + will not be considered for pipelining */ + CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10), + + /* a list of site names(+port) that are blocked from pipelining */ + CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11), + + /* a list of server types that are blocked from pipelining */ + CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12), + + /* maximum number of open connections in total */ + CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13), + + /* This is the server push callback function pointer */ + CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14), + + /* This is the argument passed to the server push callback */ + CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15), + + /* maximum number of concurrent streams to support on a connection */ + CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16), + + CURLMOPT_LASTENTRY /* the last unused */ +} CURLMoption; + + +/* + * Name: curl_multi_setopt() + * + * Desc: Sets options for the multi handle. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle, + CURLMoption option, ...); + + +/* + * Name: curl_multi_assign() + * + * Desc: This function sets an association in the multi handle between the + * given socket and a private pointer of the application. This is + * (only) useful for curl_multi_socket uses. + * + * Returns: CURLM error code. + */ +CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle, + curl_socket_t sockfd, void *sockp); + + +/* + * Name: curl_push_callback + * + * Desc: This callback gets called when a new stream is being pushed by the + * server. It approves or denies the new stream. It can also decide + * to completely fail the connection. + * + * Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT + */ +#define CURL_PUSH_OK 0 +#define CURL_PUSH_DENY 1 +#define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */ + +struct curl_pushheaders; /* forward declaration only */ + +CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h, + size_t num); +CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h, + const char *name); + +typedef int (*curl_push_callback)(CURL *parent, + CURL *easy, + size_t num_headers, + struct curl_pushheaders *headers, + void *userp); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/options.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/options.h new file mode 100644 index 0000000000000000000000000000000000000000..14373b551c795024a133ec43097d3aa5e53417d2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/options.h @@ -0,0 +1,68 @@ +#ifndef CURLINC_OPTIONS_H +#define CURLINC_OPTIONS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2018 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + CURLOT_LONG, /* long (a range of values) */ + CURLOT_VALUES, /* (a defined set or bitmask) */ + CURLOT_OFF_T, /* curl_off_t (a range of values) */ + CURLOT_OBJECT, /* pointer (void *) */ + CURLOT_STRING, /* (char * to zero terminated buffer) */ + CURLOT_SLIST, /* (struct curl_slist *) */ + CURLOT_CBPTR, /* (void * passed as-is to a callback) */ + CURLOT_BLOB, /* blob (struct curl_blob *) */ + CURLOT_FUNCTION /* function pointer */ +} curl_easytype; + +/* Flag bits */ + +/* "alias" means it is provided for old programs to remain functional, + we prefer another name */ +#define CURLOT_FLAG_ALIAS (1<<0) + +/* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size + to use for curl_easy_setopt() for the given id */ +struct curl_easyoption { + const char *name; + CURLoption id; + curl_easytype type; + unsigned int flags; +}; + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_by_name(const char *name); + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_by_id (CURLoption id); + +CURL_EXTERN const struct curl_easyoption * +curl_easy_option_next(const struct curl_easyoption *prev); + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif +#endif /* CURLINC_OPTIONS_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/stdcheaders.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/stdcheaders.h new file mode 100644 index 0000000000000000000000000000000000000000..60596c7568e2d8710d4f7ae9072deca8d7800f39 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/stdcheaders.h @@ -0,0 +1,33 @@ +#ifndef CURLINC_STDCHEADERS_H +#define CURLINC_STDCHEADERS_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include + +size_t fread(void *, size_t, size_t, FILE *); +size_t fwrite(const void *, size_t, size_t, FILE *); + +int strcasecmp(const char *, const char *); +int strncasecmp(const char *, const char *, size_t); + +#endif /* CURLINC_STDCHEADERS_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/system.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/system.h new file mode 100644 index 0000000000000000000000000000000000000000..faf8fcf84fcc48a94c1f13f4ba58089880fe9e94 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/system.h @@ -0,0 +1,504 @@ +#ifndef CURLINC_SYSTEM_H +#define CURLINC_SYSTEM_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* + * Try to keep one section per platform, compiler and architecture, otherwise, + * if an existing section is reused for a different one and later on the + * original is adjusted, probably the piggybacking one can be adversely + * changed. + * + * In order to differentiate between platforms/compilers/architectures use + * only compiler built in predefined preprocessor symbols. + * + * curl_off_t + * ---------- + * + * For any given platform/compiler curl_off_t must be typedef'ed to a 64-bit + * wide signed integral data type. The width of this data type must remain + * constant and independent of any possible large file support settings. + * + * As an exception to the above, curl_off_t shall be typedef'ed to a 32-bit + * wide signed integral data type if there is no 64-bit type. + * + * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall + * only be violated if off_t is the only 64-bit data type available and the + * size of off_t is independent of large file support settings. Keep your + * build on the safe side avoiding an off_t gating. If you have a 64-bit + * off_t then take for sure that another 64-bit data type exists, dig deeper + * and you will find it. + * + */ + +#if defined(__DJGPP__) || defined(__GO32__) +# if defined(__DJGPP__) && (__DJGPP__ > 1) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__SALFORDC__) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__BORLANDC__) +# if (__BORLANDC__ < 0x520) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__TURBOC__) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__WATCOMC__) +# if defined(__386__) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__POCC__) +# if (__POCC__ < 280) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# elif defined(_MSC_VER) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__LCC__) +# if defined(__e2k__) /* MCST eLbrus C Compiler */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# else /* Local (or Little) C Compiler */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +# endif + +#elif defined(__SYMBIAN32__) +# if defined(__EABI__) /* Treat all ARM compilers equally */ +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__CW32__) +# pragma longlong on +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__VC32__) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int + +#elif defined(__MWERKS__) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(_WIN32_WCE) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__MINGW32__) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_WS2TCPIP_H 1 + +#elif defined(__VMS) +# if defined(__VAX) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int + +#elif defined(__OS400__) +# if defined(__ILEC400__) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(__MVS__) +# if defined(__IBMC__) || defined(__IBMCPP__) +# if defined(_ILP32) +# elif defined(_LP64) +# endif +# if defined(_LONG_LONG) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(__370__) +# if defined(__IBMC__) || defined(__IBMCPP__) +# if defined(_ILP32) +# elif defined(_LP64) +# endif +# if defined(_LONG_LONG) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 +# endif + +#elif defined(TPF) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +#elif defined(__TINYC__) /* also known as tcc */ +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */ +# if !defined(__LP64) && (defined(__ILP32) || \ + defined(__i386) || \ + defined(__sparcv8) || \ + defined(__sparcv8plus)) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__LP64) || \ + defined(__amd64) || defined(__sparcv9) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#elif defined(__xlc__) /* IBM xlc compiler */ +# if !defined(_LP64) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +/* ===================================== */ +/* KEEP MSVC THE PENULTIMATE ENTRY */ +/* ===================================== */ + +#elif defined(_MSC_VER) +# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64) +# define CURL_TYPEOF_CURL_OFF_T __int64 +# define CURL_FORMAT_CURL_OFF_T "I64d" +# define CURL_FORMAT_CURL_OFF_TU "I64u" +# define CURL_SUFFIX_CURL_OFF_T i64 +# define CURL_SUFFIX_CURL_OFF_TU ui64 +# else +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T int + +/* ===================================== */ +/* KEEP GENERIC GCC THE LAST ENTRY */ +/* ===================================== */ + +#elif defined(__GNUC__) && !defined(_SCO_DS) +# if !defined(__LP64__) && \ + (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \ + defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \ + defined(__sparc__) || defined(__mips__) || defined(__sh__) || \ + defined(__XTENSA__) || \ + (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \ + (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L)) +# define CURL_TYPEOF_CURL_OFF_T long long +# define CURL_FORMAT_CURL_OFF_T "lld" +# define CURL_FORMAT_CURL_OFF_TU "llu" +# define CURL_SUFFIX_CURL_OFF_T LL +# define CURL_SUFFIX_CURL_OFF_TU ULL +# elif defined(__LP64__) || \ + defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \ + defined(__e2k__) || \ + (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \ + (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L) +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# endif +# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t +# define CURL_PULL_SYS_TYPES_H 1 +# define CURL_PULL_SYS_SOCKET_H 1 + +#else +/* generic "safe guess" on old 32 bit style */ +# define CURL_TYPEOF_CURL_OFF_T long +# define CURL_FORMAT_CURL_OFF_T "ld" +# define CURL_FORMAT_CURL_OFF_TU "lu" +# define CURL_SUFFIX_CURL_OFF_T L +# define CURL_SUFFIX_CURL_OFF_TU UL +# define CURL_TYPEOF_CURL_SOCKLEN_T int +#endif + +#ifdef _AIX +/* AIX needs */ +#define CURL_PULL_SYS_POLL_H +#endif + + +/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */ +/* ws2tcpip.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_WS2TCPIP_H +# include +# include +# include +#endif + +/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */ +/* sys/types.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_TYPES_H +# include +#endif + +/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */ +/* sys/socket.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_SOCKET_H +# include +#endif + +/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */ +/* sys/poll.h is required here to properly make type definitions below. */ +#ifdef CURL_PULL_SYS_POLL_H +# include +#endif + +/* Data type definition of curl_socklen_t. */ +#ifdef CURL_TYPEOF_CURL_SOCKLEN_T + typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t; +#endif + +/* Data type definition of curl_off_t. */ + +#ifdef CURL_TYPEOF_CURL_OFF_T + typedef CURL_TYPEOF_CURL_OFF_T curl_off_t; +#endif + +/* + * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow + * these to be visible and exported by the external libcurl interface API, + * while also making them visible to the library internals, simply including + * curl_setup.h, without actually needing to include curl.h internally. + * If some day this section would grow big enough, all this should be moved + * to its own header file. + */ + +/* + * Figure out if we can use the ## preprocessor operator, which is supported + * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__ + * or __cplusplus so we need to carefully check for them too. + */ + +#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \ + defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \ + defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \ + defined(__ILEC400__) + /* This compiler is believed to have an ISO compatible preprocessor */ +#define CURL_ISOCPP +#else + /* This compiler is believed NOT to have an ISO compatible preprocessor */ +#undef CURL_ISOCPP +#endif + +/* + * Macros for minimum-width signed and unsigned curl_off_t integer constants. + */ + +#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551) +# define CURLINC_OFF_T_C_HLPR2(x) x +# define CURLINC_OFF_T_C_HLPR1(x) CURLINC_OFF_T_C_HLPR2(x) +# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ + CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T) +# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \ + CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU) +#else +# ifdef CURL_ISOCPP +# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix +# else +# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix +# endif +# define CURLINC_OFF_T_C_HLPR1(Val,Suffix) CURLINC_OFF_T_C_HLPR2(Val,Suffix) +# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T) +# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU) +#endif + +#endif /* CURLINC_SYSTEM_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/typecheck-gcc.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/typecheck-gcc.h new file mode 100644 index 0000000000000000000000000000000000000000..34d0267ed95ad568630691f1eebdd824f3038b83 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/typecheck-gcc.h @@ -0,0 +1,705 @@ +#ifndef CURLINC_TYPECHECK_GCC_H +#define CURLINC_TYPECHECK_GCC_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2021, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +/* wraps curl_easy_setopt() with typechecking */ + +/* To add a new kind of warning, add an + * if(curlcheck_sometype_option(_curl_opt)) + * if(!curlcheck_sometype(value)) + * _curl_easy_setopt_err_sometype(); + * block and define curlcheck_sometype_option, curlcheck_sometype and + * _curl_easy_setopt_err_sometype below + * + * NOTE: We use two nested 'if' statements here instead of the && operator, in + * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x + * when compiling with -Wlogical-op. + * + * To add an option that uses the same type as an existing option, you'll just + * need to extend the appropriate _curl_*_option macro + */ +#define curl_easy_setopt(handle, option, value) \ + __extension__({ \ + __typeof__(option) _curl_opt = option; \ + if(__builtin_constant_p(_curl_opt)) { \ + if(curlcheck_long_option(_curl_opt)) \ + if(!curlcheck_long(value)) \ + _curl_easy_setopt_err_long(); \ + if(curlcheck_off_t_option(_curl_opt)) \ + if(!curlcheck_off_t(value)) \ + _curl_easy_setopt_err_curl_off_t(); \ + if(curlcheck_string_option(_curl_opt)) \ + if(!curlcheck_string(value)) \ + _curl_easy_setopt_err_string(); \ + if(curlcheck_write_cb_option(_curl_opt)) \ + if(!curlcheck_write_cb(value)) \ + _curl_easy_setopt_err_write_callback(); \ + if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \ + if(!curlcheck_resolver_start_callback(value)) \ + _curl_easy_setopt_err_resolver_start_callback(); \ + if((_curl_opt) == CURLOPT_READFUNCTION) \ + if(!curlcheck_read_cb(value)) \ + _curl_easy_setopt_err_read_cb(); \ + if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \ + if(!curlcheck_ioctl_cb(value)) \ + _curl_easy_setopt_err_ioctl_cb(); \ + if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \ + if(!curlcheck_sockopt_cb(value)) \ + _curl_easy_setopt_err_sockopt_cb(); \ + if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \ + if(!curlcheck_opensocket_cb(value)) \ + _curl_easy_setopt_err_opensocket_cb(); \ + if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \ + if(!curlcheck_progress_cb(value)) \ + _curl_easy_setopt_err_progress_cb(); \ + if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \ + if(!curlcheck_debug_cb(value)) \ + _curl_easy_setopt_err_debug_cb(); \ + if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \ + if(!curlcheck_ssl_ctx_cb(value)) \ + _curl_easy_setopt_err_ssl_ctx_cb(); \ + if(curlcheck_conv_cb_option(_curl_opt)) \ + if(!curlcheck_conv_cb(value)) \ + _curl_easy_setopt_err_conv_cb(); \ + if((_curl_opt) == CURLOPT_SEEKFUNCTION) \ + if(!curlcheck_seek_cb(value)) \ + _curl_easy_setopt_err_seek_cb(); \ + if(curlcheck_cb_data_option(_curl_opt)) \ + if(!curlcheck_cb_data(value)) \ + _curl_easy_setopt_err_cb_data(); \ + if((_curl_opt) == CURLOPT_ERRORBUFFER) \ + if(!curlcheck_error_buffer(value)) \ + _curl_easy_setopt_err_error_buffer(); \ + if((_curl_opt) == CURLOPT_STDERR) \ + if(!curlcheck_FILE(value)) \ + _curl_easy_setopt_err_FILE(); \ + if(curlcheck_postfields_option(_curl_opt)) \ + if(!curlcheck_postfields(value)) \ + _curl_easy_setopt_err_postfields(); \ + if((_curl_opt) == CURLOPT_HTTPPOST) \ + if(!curlcheck_arr((value), struct curl_httppost)) \ + _curl_easy_setopt_err_curl_httpost(); \ + if((_curl_opt) == CURLOPT_MIMEPOST) \ + if(!curlcheck_ptr((value), curl_mime)) \ + _curl_easy_setopt_err_curl_mimepost(); \ + if(curlcheck_slist_option(_curl_opt)) \ + if(!curlcheck_arr((value), struct curl_slist)) \ + _curl_easy_setopt_err_curl_slist(); \ + if((_curl_opt) == CURLOPT_SHARE) \ + if(!curlcheck_ptr((value), CURLSH)) \ + _curl_easy_setopt_err_CURLSH(); \ + } \ + curl_easy_setopt(handle, _curl_opt, value); \ + }) + +/* wraps curl_easy_getinfo() with typechecking */ +#define curl_easy_getinfo(handle, info, arg) \ + __extension__({ \ + __typeof__(info) _curl_info = info; \ + if(__builtin_constant_p(_curl_info)) { \ + if(curlcheck_string_info(_curl_info)) \ + if(!curlcheck_arr((arg), char *)) \ + _curl_easy_getinfo_err_string(); \ + if(curlcheck_long_info(_curl_info)) \ + if(!curlcheck_arr((arg), long)) \ + _curl_easy_getinfo_err_long(); \ + if(curlcheck_double_info(_curl_info)) \ + if(!curlcheck_arr((arg), double)) \ + _curl_easy_getinfo_err_double(); \ + if(curlcheck_slist_info(_curl_info)) \ + if(!curlcheck_arr((arg), struct curl_slist *)) \ + _curl_easy_getinfo_err_curl_slist(); \ + if(curlcheck_tlssessioninfo_info(_curl_info)) \ + if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \ + _curl_easy_getinfo_err_curl_tlssesssioninfo(); \ + if(curlcheck_certinfo_info(_curl_info)) \ + if(!curlcheck_arr((arg), struct curl_certinfo *)) \ + _curl_easy_getinfo_err_curl_certinfo(); \ + if(curlcheck_socket_info(_curl_info)) \ + if(!curlcheck_arr((arg), curl_socket_t)) \ + _curl_easy_getinfo_err_curl_socket(); \ + if(curlcheck_off_t_info(_curl_info)) \ + if(!curlcheck_arr((arg), curl_off_t)) \ + _curl_easy_getinfo_err_curl_off_t(); \ + } \ + curl_easy_getinfo(handle, _curl_info, arg); \ + }) + +/* + * For now, just make sure that the functions are called with three arguments + */ +#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param) +#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param) + + +/* the actual warnings, triggered by calling the _curl_easy_setopt_err* + * functions */ + +/* To define a new warning, use _CURL_WARNING(identifier, "message") */ +#define CURLWARNING(id, message) \ + static void __attribute__((__warning__(message))) \ + __attribute__((__unused__)) __attribute__((__noinline__)) \ + id(void) { __asm__(""); } + +CURLWARNING(_curl_easy_setopt_err_long, + "curl_easy_setopt expects a long argument for this option") +CURLWARNING(_curl_easy_setopt_err_curl_off_t, + "curl_easy_setopt expects a curl_off_t argument for this option") +CURLWARNING(_curl_easy_setopt_err_string, + "curl_easy_setopt expects a " + "string ('char *' or char[]) argument for this option" + ) +CURLWARNING(_curl_easy_setopt_err_write_callback, + "curl_easy_setopt expects a curl_write_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_resolver_start_callback, + "curl_easy_setopt expects a " + "curl_resolver_start_callback argument for this option" + ) +CURLWARNING(_curl_easy_setopt_err_read_cb, + "curl_easy_setopt expects a curl_read_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_ioctl_cb, + "curl_easy_setopt expects a curl_ioctl_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_sockopt_cb, + "curl_easy_setopt expects a curl_sockopt_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_opensocket_cb, + "curl_easy_setopt expects a " + "curl_opensocket_callback argument for this option" + ) +CURLWARNING(_curl_easy_setopt_err_progress_cb, + "curl_easy_setopt expects a curl_progress_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_debug_cb, + "curl_easy_setopt expects a curl_debug_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb, + "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_conv_cb, + "curl_easy_setopt expects a curl_conv_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_seek_cb, + "curl_easy_setopt expects a curl_seek_callback argument for this option") +CURLWARNING(_curl_easy_setopt_err_cb_data, + "curl_easy_setopt expects a " + "private data pointer as argument for this option") +CURLWARNING(_curl_easy_setopt_err_error_buffer, + "curl_easy_setopt expects a " + "char buffer of CURL_ERROR_SIZE as argument for this option") +CURLWARNING(_curl_easy_setopt_err_FILE, + "curl_easy_setopt expects a 'FILE *' argument for this option") +CURLWARNING(_curl_easy_setopt_err_postfields, + "curl_easy_setopt expects a 'void *' or 'char *' argument for this option") +CURLWARNING(_curl_easy_setopt_err_curl_httpost, + "curl_easy_setopt expects a 'struct curl_httppost *' " + "argument for this option") +CURLWARNING(_curl_easy_setopt_err_curl_mimepost, + "curl_easy_setopt expects a 'curl_mime *' " + "argument for this option") +CURLWARNING(_curl_easy_setopt_err_curl_slist, + "curl_easy_setopt expects a 'struct curl_slist *' argument for this option") +CURLWARNING(_curl_easy_setopt_err_CURLSH, + "curl_easy_setopt expects a CURLSH* argument for this option") + +CURLWARNING(_curl_easy_getinfo_err_string, + "curl_easy_getinfo expects a pointer to 'char *' for this info") +CURLWARNING(_curl_easy_getinfo_err_long, + "curl_easy_getinfo expects a pointer to long for this info") +CURLWARNING(_curl_easy_getinfo_err_double, + "curl_easy_getinfo expects a pointer to double for this info") +CURLWARNING(_curl_easy_getinfo_err_curl_slist, + "curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info") +CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo, + "curl_easy_getinfo expects a pointer to " + "'struct curl_tlssessioninfo *' for this info") +CURLWARNING(_curl_easy_getinfo_err_curl_certinfo, + "curl_easy_getinfo expects a pointer to " + "'struct curl_certinfo *' for this info") +CURLWARNING(_curl_easy_getinfo_err_curl_socket, + "curl_easy_getinfo expects a pointer to curl_socket_t for this info") +CURLWARNING(_curl_easy_getinfo_err_curl_off_t, + "curl_easy_getinfo expects a pointer to curl_off_t for this info") + +/* groups of curl_easy_setops options that take the same type of argument */ + +/* To add a new option to one of the groups, just add + * (option) == CURLOPT_SOMETHING + * to the or-expression. If the option takes a long or curl_off_t, you don't + * have to do anything + */ + +/* evaluates to true if option takes a long argument */ +#define curlcheck_long_option(option) \ + (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT) + +#define curlcheck_off_t_option(option) \ + (((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB)) + +/* evaluates to true if option takes a char* argument */ +#define curlcheck_string_option(option) \ + ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \ + (option) == CURLOPT_ACCEPT_ENCODING || \ + (option) == CURLOPT_ALTSVC || \ + (option) == CURLOPT_CAINFO || \ + (option) == CURLOPT_CAPATH || \ + (option) == CURLOPT_COOKIE || \ + (option) == CURLOPT_COOKIEFILE || \ + (option) == CURLOPT_COOKIEJAR || \ + (option) == CURLOPT_COOKIELIST || \ + (option) == CURLOPT_CRLFILE || \ + (option) == CURLOPT_CUSTOMREQUEST || \ + (option) == CURLOPT_DEFAULT_PROTOCOL || \ + (option) == CURLOPT_DNS_INTERFACE || \ + (option) == CURLOPT_DNS_LOCAL_IP4 || \ + (option) == CURLOPT_DNS_LOCAL_IP6 || \ + (option) == CURLOPT_DNS_SERVERS || \ + (option) == CURLOPT_DOH_URL || \ + (option) == CURLOPT_EGDSOCKET || \ + (option) == CURLOPT_FTPPORT || \ + (option) == CURLOPT_FTP_ACCOUNT || \ + (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \ + (option) == CURLOPT_HSTS || \ + (option) == CURLOPT_INTERFACE || \ + (option) == CURLOPT_ISSUERCERT || \ + (option) == CURLOPT_KEYPASSWD || \ + (option) == CURLOPT_KRBLEVEL || \ + (option) == CURLOPT_LOGIN_OPTIONS || \ + (option) == CURLOPT_MAIL_AUTH || \ + (option) == CURLOPT_MAIL_FROM || \ + (option) == CURLOPT_NETRC_FILE || \ + (option) == CURLOPT_NOPROXY || \ + (option) == CURLOPT_PASSWORD || \ + (option) == CURLOPT_PINNEDPUBLICKEY || \ + (option) == CURLOPT_PRE_PROXY || \ + (option) == CURLOPT_PROXY || \ + (option) == CURLOPT_PROXYPASSWORD || \ + (option) == CURLOPT_PROXYUSERNAME || \ + (option) == CURLOPT_PROXYUSERPWD || \ + (option) == CURLOPT_PROXY_CAINFO || \ + (option) == CURLOPT_PROXY_CAPATH || \ + (option) == CURLOPT_PROXY_CRLFILE || \ + (option) == CURLOPT_PROXY_ISSUERCERT || \ + (option) == CURLOPT_PROXY_KEYPASSWD || \ + (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \ + (option) == CURLOPT_PROXY_SERVICE_NAME || \ + (option) == CURLOPT_PROXY_SSLCERT || \ + (option) == CURLOPT_PROXY_SSLCERTTYPE || \ + (option) == CURLOPT_PROXY_SSLKEY || \ + (option) == CURLOPT_PROXY_SSLKEYTYPE || \ + (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \ + (option) == CURLOPT_PROXY_TLS13_CIPHERS || \ + (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \ + (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \ + (option) == CURLOPT_RANDOM_FILE || \ + (option) == CURLOPT_RANGE || \ + (option) == CURLOPT_REFERER || \ + (option) == CURLOPT_REQUEST_TARGET || \ + (option) == CURLOPT_RTSP_SESSION_ID || \ + (option) == CURLOPT_RTSP_STREAM_URI || \ + (option) == CURLOPT_RTSP_TRANSPORT || \ + (option) == CURLOPT_SASL_AUTHZID || \ + (option) == CURLOPT_SERVICE_NAME || \ + (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \ + (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \ + (option) == CURLOPT_SSH_KNOWNHOSTS || \ + (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \ + (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \ + (option) == CURLOPT_SSLCERT || \ + (option) == CURLOPT_SSLCERTTYPE || \ + (option) == CURLOPT_SSLENGINE || \ + (option) == CURLOPT_SSLKEY || \ + (option) == CURLOPT_SSLKEYTYPE || \ + (option) == CURLOPT_SSL_CIPHER_LIST || \ + (option) == CURLOPT_TLS13_CIPHERS || \ + (option) == CURLOPT_TLSAUTH_PASSWORD || \ + (option) == CURLOPT_TLSAUTH_TYPE || \ + (option) == CURLOPT_TLSAUTH_USERNAME || \ + (option) == CURLOPT_UNIX_SOCKET_PATH || \ + (option) == CURLOPT_URL || \ + (option) == CURLOPT_USERAGENT || \ + (option) == CURLOPT_USERNAME || \ + (option) == CURLOPT_AWS_SIGV4 || \ + (option) == CURLOPT_USERPWD || \ + (option) == CURLOPT_XOAUTH2_BEARER || \ + (option) == CURLOPT_SSL_EC_CURVES || \ + 0) + +/* evaluates to true if option takes a curl_write_callback argument */ +#define curlcheck_write_cb_option(option) \ + ((option) == CURLOPT_HEADERFUNCTION || \ + (option) == CURLOPT_WRITEFUNCTION) + +/* evaluates to true if option takes a curl_conv_callback argument */ +#define curlcheck_conv_cb_option(option) \ + ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \ + (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION) + +/* evaluates to true if option takes a data argument to pass to a callback */ +#define curlcheck_cb_data_option(option) \ + ((option) == CURLOPT_CHUNK_DATA || \ + (option) == CURLOPT_CLOSESOCKETDATA || \ + (option) == CURLOPT_DEBUGDATA || \ + (option) == CURLOPT_FNMATCH_DATA || \ + (option) == CURLOPT_HEADERDATA || \ + (option) == CURLOPT_HSTSREADDATA || \ + (option) == CURLOPT_HSTSWRITEDATA || \ + (option) == CURLOPT_INTERLEAVEDATA || \ + (option) == CURLOPT_IOCTLDATA || \ + (option) == CURLOPT_OPENSOCKETDATA || \ + (option) == CURLOPT_PROGRESSDATA || \ + (option) == CURLOPT_READDATA || \ + (option) == CURLOPT_SEEKDATA || \ + (option) == CURLOPT_SOCKOPTDATA || \ + (option) == CURLOPT_SSH_KEYDATA || \ + (option) == CURLOPT_SSL_CTX_DATA || \ + (option) == CURLOPT_WRITEDATA || \ + (option) == CURLOPT_RESOLVER_START_DATA || \ + (option) == CURLOPT_TRAILERDATA || \ + 0) + +/* evaluates to true if option takes a POST data argument (void* or char*) */ +#define curlcheck_postfields_option(option) \ + ((option) == CURLOPT_POSTFIELDS || \ + (option) == CURLOPT_COPYPOSTFIELDS || \ + 0) + +/* evaluates to true if option takes a struct curl_slist * argument */ +#define curlcheck_slist_option(option) \ + ((option) == CURLOPT_HTTP200ALIASES || \ + (option) == CURLOPT_HTTPHEADER || \ + (option) == CURLOPT_MAIL_RCPT || \ + (option) == CURLOPT_POSTQUOTE || \ + (option) == CURLOPT_PREQUOTE || \ + (option) == CURLOPT_PROXYHEADER || \ + (option) == CURLOPT_QUOTE || \ + (option) == CURLOPT_RESOLVE || \ + (option) == CURLOPT_TELNETOPTIONS || \ + (option) == CURLOPT_CONNECT_TO || \ + 0) + +/* groups of curl_easy_getinfo infos that take the same type of argument */ + +/* evaluates to true if info expects a pointer to char * argument */ +#define curlcheck_string_info(info) \ + (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \ + (info) != CURLINFO_PRIVATE) + +/* evaluates to true if info expects a pointer to long argument */ +#define curlcheck_long_info(info) \ + (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE) + +/* evaluates to true if info expects a pointer to double argument */ +#define curlcheck_double_info(info) \ + (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST) + +/* true if info expects a pointer to struct curl_slist * argument */ +#define curlcheck_slist_info(info) \ + (((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST)) + +/* true if info expects a pointer to struct curl_tlssessioninfo * argument */ +#define curlcheck_tlssessioninfo_info(info) \ + (((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION)) + +/* true if info expects a pointer to struct curl_certinfo * argument */ +#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO) + +/* true if info expects a pointer to struct curl_socket_t argument */ +#define curlcheck_socket_info(info) \ + (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T) + +/* true if info expects a pointer to curl_off_t argument */ +#define curlcheck_off_t_info(info) \ + (CURLINFO_OFF_T < (info)) + + +/* typecheck helpers -- check whether given expression has requested type*/ + +/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros, + * otherwise define a new macro. Search for __builtin_types_compatible_p + * in the GCC manual. + * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is + * the actual expression passed to the curl_easy_setopt macro. This + * means that you can only apply the sizeof and __typeof__ operators, no + * == or whatsoever. + */ + +/* XXX: should evaluate to true if expr is a pointer */ +#define curlcheck_any_ptr(expr) \ + (sizeof(expr) == sizeof(void *)) + +/* evaluates to true if expr is NULL */ +/* XXX: must not evaluate expr, so this check is not accurate */ +#define curlcheck_NULL(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL))) + +/* evaluates to true if expr is type*, const type* or NULL */ +#define curlcheck_ptr(expr, type) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), type *) || \ + __builtin_types_compatible_p(__typeof__(expr), const type *)) + +/* evaluates to true if expr is one of type[], type*, NULL or const type* */ +#define curlcheck_arr(expr, type) \ + (curlcheck_ptr((expr), type) || \ + __builtin_types_compatible_p(__typeof__(expr), type [])) + +/* evaluates to true if expr is a string */ +#define curlcheck_string(expr) \ + (curlcheck_arr((expr), char) || \ + curlcheck_arr((expr), signed char) || \ + curlcheck_arr((expr), unsigned char)) + +/* evaluates to true if expr is a long (no matter the signedness) + * XXX: for now, int is also accepted (and therefore short and char, which + * are promoted to int when passed to a variadic function) */ +#define curlcheck_long(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), long) || \ + __builtin_types_compatible_p(__typeof__(expr), signed long) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \ + __builtin_types_compatible_p(__typeof__(expr), int) || \ + __builtin_types_compatible_p(__typeof__(expr), signed int) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \ + __builtin_types_compatible_p(__typeof__(expr), short) || \ + __builtin_types_compatible_p(__typeof__(expr), signed short) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \ + __builtin_types_compatible_p(__typeof__(expr), char) || \ + __builtin_types_compatible_p(__typeof__(expr), signed char) || \ + __builtin_types_compatible_p(__typeof__(expr), unsigned char)) + +/* evaluates to true if expr is of type curl_off_t */ +#define curlcheck_off_t(expr) \ + (__builtin_types_compatible_p(__typeof__(expr), curl_off_t)) + +/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */ +/* XXX: also check size of an char[] array? */ +#define curlcheck_error_buffer(expr) \ + (curlcheck_NULL(expr) || \ + __builtin_types_compatible_p(__typeof__(expr), char *) || \ + __builtin_types_compatible_p(__typeof__(expr), char[])) + +/* evaluates to true if expr is of type (const) void* or (const) FILE* */ +#if 0 +#define curlcheck_cb_data(expr) \ + (curlcheck_ptr((expr), void) || \ + curlcheck_ptr((expr), FILE)) +#else /* be less strict */ +#define curlcheck_cb_data(expr) \ + curlcheck_any_ptr(expr) +#endif + +/* evaluates to true if expr is of type FILE* */ +#define curlcheck_FILE(expr) \ + (curlcheck_NULL(expr) || \ + (__builtin_types_compatible_p(__typeof__(expr), FILE *))) + +/* evaluates to true if expr can be passed as POST data (void* or char*) */ +#define curlcheck_postfields(expr) \ + (curlcheck_ptr((expr), void) || \ + curlcheck_arr((expr), char) || \ + curlcheck_arr((expr), unsigned char)) + +/* helper: __builtin_types_compatible_p distinguishes between functions and + * function pointers, hide it */ +#define curlcheck_cb_compatible(func, type) \ + (__builtin_types_compatible_p(__typeof__(func), type) || \ + __builtin_types_compatible_p(__typeof__(func) *, type)) + +/* evaluates to true if expr is of type curl_resolver_start_callback */ +#define curlcheck_resolver_start_callback(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_resolver_start_callback)) + +/* evaluates to true if expr is of type curl_read_callback or "similar" */ +#define curlcheck_read_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), __typeof__(fread) *) || \ + curlcheck_cb_compatible((expr), curl_read_callback) || \ + curlcheck_cb_compatible((expr), _curl_read_callback1) || \ + curlcheck_cb_compatible((expr), _curl_read_callback2) || \ + curlcheck_cb_compatible((expr), _curl_read_callback3) || \ + curlcheck_cb_compatible((expr), _curl_read_callback4) || \ + curlcheck_cb_compatible((expr), _curl_read_callback5) || \ + curlcheck_cb_compatible((expr), _curl_read_callback6)) +typedef size_t (*_curl_read_callback1)(char *, size_t, size_t, void *); +typedef size_t (*_curl_read_callback2)(char *, size_t, size_t, const void *); +typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *); +typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *); +typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *); +typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *); + +/* evaluates to true if expr is of type curl_write_callback or "similar" */ +#define curlcheck_write_cb(expr) \ + (curlcheck_read_cb(expr) || \ + curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \ + curlcheck_cb_compatible((expr), curl_write_callback) || \ + curlcheck_cb_compatible((expr), _curl_write_callback1) || \ + curlcheck_cb_compatible((expr), _curl_write_callback2) || \ + curlcheck_cb_compatible((expr), _curl_write_callback3) || \ + curlcheck_cb_compatible((expr), _curl_write_callback4) || \ + curlcheck_cb_compatible((expr), _curl_write_callback5) || \ + curlcheck_cb_compatible((expr), _curl_write_callback6)) +typedef size_t (*_curl_write_callback1)(const char *, size_t, size_t, void *); +typedef size_t (*_curl_write_callback2)(const char *, size_t, size_t, + const void *); +typedef size_t (*_curl_write_callback3)(const char *, size_t, size_t, FILE *); +typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *); +typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t, + const void *); +typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *); + +/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */ +#define curlcheck_ioctl_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_ioctl_callback) || \ + curlcheck_cb_compatible((expr), _curl_ioctl_callback1) || \ + curlcheck_cb_compatible((expr), _curl_ioctl_callback2) || \ + curlcheck_cb_compatible((expr), _curl_ioctl_callback3) || \ + curlcheck_cb_compatible((expr), _curl_ioctl_callback4)) +typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *); +typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *); +typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *); +typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *); + +/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */ +#define curlcheck_sockopt_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_sockopt_callback) || \ + curlcheck_cb_compatible((expr), _curl_sockopt_callback1) || \ + curlcheck_cb_compatible((expr), _curl_sockopt_callback2)) +typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype); +typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t, + curlsocktype); + +/* evaluates to true if expr is of type curl_opensocket_callback or + "similar" */ +#define curlcheck_opensocket_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_opensocket_callback) || \ + curlcheck_cb_compatible((expr), _curl_opensocket_callback1) || \ + curlcheck_cb_compatible((expr), _curl_opensocket_callback2) || \ + curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \ + curlcheck_cb_compatible((expr), _curl_opensocket_callback4)) +typedef curl_socket_t (*_curl_opensocket_callback1) + (void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (*_curl_opensocket_callback2) + (void *, curlsocktype, const struct curl_sockaddr *); +typedef curl_socket_t (*_curl_opensocket_callback3) + (const void *, curlsocktype, struct curl_sockaddr *); +typedef curl_socket_t (*_curl_opensocket_callback4) + (const void *, curlsocktype, const struct curl_sockaddr *); + +/* evaluates to true if expr is of type curl_progress_callback or "similar" */ +#define curlcheck_progress_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_progress_callback) || \ + curlcheck_cb_compatible((expr), _curl_progress_callback1) || \ + curlcheck_cb_compatible((expr), _curl_progress_callback2)) +typedef int (*_curl_progress_callback1)(void *, + double, double, double, double); +typedef int (*_curl_progress_callback2)(const void *, + double, double, double, double); + +/* evaluates to true if expr is of type curl_debug_callback or "similar" */ +#define curlcheck_debug_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_debug_callback) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback1) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback2) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback3) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback4) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback5) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback6) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback7) || \ + curlcheck_cb_compatible((expr), _curl_debug_callback8)) +typedef int (*_curl_debug_callback1) (CURL *, + curl_infotype, char *, size_t, void *); +typedef int (*_curl_debug_callback2) (CURL *, + curl_infotype, char *, size_t, const void *); +typedef int (*_curl_debug_callback3) (CURL *, + curl_infotype, const char *, size_t, void *); +typedef int (*_curl_debug_callback4) (CURL *, + curl_infotype, const char *, size_t, const void *); +typedef int (*_curl_debug_callback5) (CURL *, + curl_infotype, unsigned char *, size_t, void *); +typedef int (*_curl_debug_callback6) (CURL *, + curl_infotype, unsigned char *, size_t, const void *); +typedef int (*_curl_debug_callback7) (CURL *, + curl_infotype, const unsigned char *, size_t, void *); +typedef int (*_curl_debug_callback8) (CURL *, + curl_infotype, const unsigned char *, size_t, const void *); + +/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */ +/* this is getting even messier... */ +#define curlcheck_ssl_ctx_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback1) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback2) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback3) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback4) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback5) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback6) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback7) || \ + curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback8)) +typedef CURLcode (*_curl_ssl_ctx_callback1)(CURL *, void *, void *); +typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *); +typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *); +typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *, + const void *); +#ifdef HEADER_SSL_H +/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX + * this will of course break if we're included before OpenSSL headers... + */ +typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *); +typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *); +typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *); +typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX *, + const void *); +#else +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7; +typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8; +#endif + +/* evaluates to true if expr is of type curl_conv_callback or "similar" */ +#define curlcheck_conv_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_conv_callback) || \ + curlcheck_cb_compatible((expr), _curl_conv_callback1) || \ + curlcheck_cb_compatible((expr), _curl_conv_callback2) || \ + curlcheck_cb_compatible((expr), _curl_conv_callback3) || \ + curlcheck_cb_compatible((expr), _curl_conv_callback4)) +typedef CURLcode (*_curl_conv_callback1)(char *, size_t length); +typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length); +typedef CURLcode (*_curl_conv_callback3)(void *, size_t length); +typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length); + +/* evaluates to true if expr is of type curl_seek_callback or "similar" */ +#define curlcheck_seek_cb(expr) \ + (curlcheck_NULL(expr) || \ + curlcheck_cb_compatible((expr), curl_seek_callback) || \ + curlcheck_cb_compatible((expr), _curl_seek_callback1) || \ + curlcheck_cb_compatible((expr), _curl_seek_callback2)) +typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int); +typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int); + + +#endif /* CURLINC_TYPECHECK_GCC_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/urlapi.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/urlapi.h new file mode 100644 index 0000000000000000000000000000000000000000..1d70880117e4943799c713a0f1d6069beff9fcb6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/curl/urlapi.h @@ -0,0 +1,126 @@ +#ifndef CURLINC_URLAPI_H +#define CURLINC_URLAPI_H +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 2018 - 2021, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at https://curl.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ + +#include "curl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* the error codes for the URL API */ +typedef enum { + CURLUE_OK, + CURLUE_BAD_HANDLE, /* 1 */ + CURLUE_BAD_PARTPOINTER, /* 2 */ + CURLUE_MALFORMED_INPUT, /* 3 */ + CURLUE_BAD_PORT_NUMBER, /* 4 */ + CURLUE_UNSUPPORTED_SCHEME, /* 5 */ + CURLUE_URLDECODE, /* 6 */ + CURLUE_OUT_OF_MEMORY, /* 7 */ + CURLUE_USER_NOT_ALLOWED, /* 8 */ + CURLUE_UNKNOWN_PART, /* 9 */ + CURLUE_NO_SCHEME, /* 10 */ + CURLUE_NO_USER, /* 11 */ + CURLUE_NO_PASSWORD, /* 12 */ + CURLUE_NO_OPTIONS, /* 13 */ + CURLUE_NO_HOST, /* 14 */ + CURLUE_NO_PORT, /* 15 */ + CURLUE_NO_QUERY, /* 16 */ + CURLUE_NO_FRAGMENT /* 17 */ +} CURLUcode; + +typedef enum { + CURLUPART_URL, + CURLUPART_SCHEME, + CURLUPART_USER, + CURLUPART_PASSWORD, + CURLUPART_OPTIONS, + CURLUPART_HOST, + CURLUPART_PORT, + CURLUPART_PATH, + CURLUPART_QUERY, + CURLUPART_FRAGMENT, + CURLUPART_ZONEID /* added in 7.65.0 */ +} CURLUPart; + +#define CURLU_DEFAULT_PORT (1<<0) /* return default port number */ +#define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set, + if the port number matches the + default for the scheme */ +#define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if + missing */ +#define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */ +#define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */ +#define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */ +#define CURLU_URLDECODE (1<<6) /* URL decode on get */ +#define CURLU_URLENCODE (1<<7) /* URL encode on set */ +#define CURLU_APPENDQUERY (1<<8) /* append a form style part */ +#define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */ +#define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the + scheme is unknown. */ +#define CURLU_ALLOW_SPACE (1<<11) /* Allow spaces in the URL */ + +typedef struct Curl_URL CURLU; + +/* + * curl_url() creates a new CURLU handle and returns a pointer to it. + * Must be freed with curl_url_cleanup(). + */ +CURL_EXTERN CURLU *curl_url(void); + +/* + * curl_url_cleanup() frees the CURLU handle and related resources used for + * the URL parsing. It will not free strings previously returned with the URL + * API. + */ +CURL_EXTERN void curl_url_cleanup(CURLU *handle); + +/* + * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new + * handle must also be freed with curl_url_cleanup(). + */ +CURL_EXTERN CURLU *curl_url_dup(CURLU *in); + +/* + * curl_url_get() extracts a specific part of the URL from a CURLU + * handle. Returns error code. The returned pointer MUST be freed with + * curl_free() afterwards. + */ +CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what, + char **part, unsigned int flags); + +/* + * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns + * error code. The passed in string will be copied. Passing a NULL instead of + * a part string, clears that part. + */ +CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what, + const char *part, unsigned int flags); + + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif + +#endif /* CURLINC_URLAPI_H */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgeol b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgeol new file mode 100644 index 0000000000000000000000000000000000000000..5327df161536cc2b12f8884e9935daaca82690b1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgeol @@ -0,0 +1,11 @@ +[patterns] +*.sh = LF +*.MINPACK = CRLF +scripts/*.in = LF +debug/msvc/*.dat = CRLF +debug/msvc/*.natvis = CRLF +unsupported/test/mpreal/*.* = CRLF +** = native + +[repository] +native = LF diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgignore b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgignore new file mode 100644 index 0000000000000000000000000000000000000000..fada7ec5ec794601033fe123f4b885ee5de4c1c9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/.hgignore @@ -0,0 +1,34 @@ +syntax: glob +qrc_*cxx +*.orig +*.pyc +*.diff +diff +*.save +save +*.old +*.gmo +*.qm +core +core.* +*.bak +*~ +*build* +*.moc.* +*.moc +ui_* +CMakeCache.txt +tags +.*.swp +activity.png +*.out +*.php* +*.log +*.orig +*.rej +log +patch +a +a.* +lapack/testing +lapack/reference diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..2bfb6d560b63f1c0d27b2bf2d3125d7b73435f03 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CMakeLists.txt @@ -0,0 +1,616 @@ +project(Eigen3) + +cmake_minimum_required(VERSION 2.8.5) + +# guard against in-source builds + +if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) + message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt. ") +endif() + +# Alias Eigen_*_DIR to Eigen3_*_DIR: + +set(Eigen_SOURCE_DIR ${Eigen3_SOURCE_DIR}) +set(Eigen_BINARY_DIR ${Eigen3_BINARY_DIR}) + +# guard against bad build-type strings + +if (NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE "Release") +endif() + +string(TOLOWER "${CMAKE_BUILD_TYPE}" cmake_build_type_tolower) +if( NOT cmake_build_type_tolower STREQUAL "debug" + AND NOT cmake_build_type_tolower STREQUAL "release" + AND NOT cmake_build_type_tolower STREQUAL "relwithdebinfo") + message(FATAL_ERROR "Unknown build type \"${CMAKE_BUILD_TYPE}\". Allowed values are Debug, Release, RelWithDebInfo (case-insensitive).") +endif() + + +############################################################################# +# retrieve version infomation # +############################################################################# + +# automatically parse the version number +file(READ "${PROJECT_SOURCE_DIR}/Eigen/src/Core/util/Macros.h" _eigen_version_header) +string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen_world_version_match "${_eigen_version_header}") +set(EIGEN_WORLD_VERSION "${CMAKE_MATCH_1}") +string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen_major_version_match "${_eigen_version_header}") +set(EIGEN_MAJOR_VERSION "${CMAKE_MATCH_1}") +string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen_minor_version_match "${_eigen_version_header}") +set(EIGEN_MINOR_VERSION "${CMAKE_MATCH_1}") +set(EIGEN_VERSION_NUMBER ${EIGEN_WORLD_VERSION}.${EIGEN_MAJOR_VERSION}.${EIGEN_MINOR_VERSION}) + +# if we are not in a mercurial clone +if(IS_DIRECTORY ${CMAKE_SOURCE_DIR}/.hg) + # if the mercurial program is absent or this will leave the EIGEN_HG_CHANGESET string empty, + # but won't stop CMake. + execute_process(COMMAND hg tip -R ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE EIGEN_HGTIP_OUTPUT) + execute_process(COMMAND hg branch -R ${CMAKE_SOURCE_DIR} OUTPUT_VARIABLE EIGEN_BRANCH_OUTPUT) +endif() + +# if this is the default (aka development) branch, extract the mercurial changeset number from the hg tip output... +if(EIGEN_BRANCH_OUTPUT MATCHES "default") +string(REGEX MATCH "^changeset: *[0-9]*:([0-9;a-f]+).*" EIGEN_HG_CHANGESET_MATCH "${EIGEN_HGTIP_OUTPUT}") +set(EIGEN_HG_CHANGESET "${CMAKE_MATCH_1}") +endif(EIGEN_BRANCH_OUTPUT MATCHES "default") +#...and show it next to the version number +if(EIGEN_HG_CHANGESET) + set(EIGEN_VERSION "${EIGEN_VERSION_NUMBER} (mercurial changeset ${EIGEN_HG_CHANGESET})") +else(EIGEN_HG_CHANGESET) + set(EIGEN_VERSION "${EIGEN_VERSION_NUMBER}") +endif(EIGEN_HG_CHANGESET) + + +include(CheckCXXCompilerFlag) +include(GNUInstallDirs) + +set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake) + + +option(EIGEN_TEST_CXX11 "Enable testing with C++11 and C++11 features (e.g. Tensor module)." OFF) + + +macro(ei_add_cxx_compiler_flag FLAG) + string(REGEX REPLACE "-" "" SFLAG1 ${FLAG}) + string(REGEX REPLACE "\\+" "p" SFLAG ${SFLAG1}) + check_cxx_compiler_flag(${FLAG} COMPILER_SUPPORT_${SFLAG}) + if(COMPILER_SUPPORT_${SFLAG}) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLAG}") + endif() +endmacro(ei_add_cxx_compiler_flag) + +check_cxx_compiler_flag("-std=c++11" EIGEN_COMPILER_SUPPORT_CPP11) + +if(EIGEN_TEST_CXX11) + set(CMAKE_CXX_STANDARD 11) + set(CMAKE_CXX_EXTENSIONS OFF) + if(EIGEN_COMPILER_SUPPORT_CPP11) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") + endif() +else() + #set(CMAKE_CXX_STANDARD 03) + #set(CMAKE_CXX_EXTENSIONS OFF) + ei_add_cxx_compiler_flag("-std=c++03") +endif() + +############################################################################# +# find how to link to the standard libraries # +############################################################################# + +find_package(StandardMathLibrary) + + +set(EIGEN_TEST_CUSTOM_LINKER_FLAGS "" CACHE STRING "Additional linker flags when linking unit tests.") +set(EIGEN_TEST_CUSTOM_CXX_FLAGS "" CACHE STRING "Additional compiler flags when compiling unit tests.") + +set(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO "") + +if(NOT STANDARD_MATH_LIBRARY_FOUND) + + message(FATAL_ERROR + "Can't link to the standard math library. Please report to the Eigen developers, telling them about your platform.") + +else() + + if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) + set(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO "${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO} ${STANDARD_MATH_LIBRARY}") + else() + set(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO "${STANDARD_MATH_LIBRARY}") + endif() + +endif() + +if(EIGEN_STANDARD_LIBRARIES_TO_LINK_TO) + message(STATUS "Standard libraries to link to explicitly: ${EIGEN_STANDARD_LIBRARIES_TO_LINK_TO}") +else() + message(STATUS "Standard libraries to link to explicitly: none") +endif() + +option(EIGEN_BUILD_BTL "Build benchmark suite" OFF) + +# Disable pkgconfig only for native Windows builds +if(NOT WIN32 OR NOT CMAKE_HOST_SYSTEM_NAME MATCHES Windows) + option(EIGEN_BUILD_PKGCONFIG "Build pkg-config .pc file for Eigen" ON) +endif() + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +option(EIGEN_SPLIT_LARGE_TESTS "Split large tests into smaller executables" ON) + +option(EIGEN_DEFAULT_TO_ROW_MAJOR "Use row-major as default matrix storage order" OFF) +if(EIGEN_DEFAULT_TO_ROW_MAJOR) + add_definitions("-DEIGEN_DEFAULT_TO_ROW_MAJOR") +endif() + +set(EIGEN_TEST_MAX_SIZE "320" CACHE STRING "Maximal matrix/vector size, default is 320") + +if(NOT MSVC) + # We assume that other compilers are partly compatible with GNUCC + + # clang outputs some warnings for unknown flags that are not caught by check_cxx_compiler_flag + # adding -Werror turns such warnings into errors + check_cxx_compiler_flag("-Werror" COMPILER_SUPPORT_WERROR) + if(COMPILER_SUPPORT_WERROR) + set(CMAKE_REQUIRED_FLAGS "-Werror") + endif() + ei_add_cxx_compiler_flag("-pedantic") + ei_add_cxx_compiler_flag("-Wall") + ei_add_cxx_compiler_flag("-Wextra") + #ei_add_cxx_compiler_flag("-Weverything") # clang + + ei_add_cxx_compiler_flag("-Wundef") + ei_add_cxx_compiler_flag("-Wcast-align") + ei_add_cxx_compiler_flag("-Wchar-subscripts") + ei_add_cxx_compiler_flag("-Wnon-virtual-dtor") + ei_add_cxx_compiler_flag("-Wunused-local-typedefs") + ei_add_cxx_compiler_flag("-Wpointer-arith") + ei_add_cxx_compiler_flag("-Wwrite-strings") + ei_add_cxx_compiler_flag("-Wformat-security") + ei_add_cxx_compiler_flag("-Wshorten-64-to-32") + ei_add_cxx_compiler_flag("-Wlogical-op") + ei_add_cxx_compiler_flag("-Wenum-conversion") + ei_add_cxx_compiler_flag("-Wc++11-extensions") + ei_add_cxx_compiler_flag("-Wdouble-promotion") +# ei_add_cxx_compiler_flag("-Wconversion") + + # -Wshadow is insanely too strict with gcc, hopefully it will become usable with gcc 6 + # if(NOT CMAKE_COMPILER_IS_GNUCXX OR (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "5.0.0")) + if(NOT CMAKE_COMPILER_IS_GNUCXX) + ei_add_cxx_compiler_flag("-Wshadow") + endif() + + ei_add_cxx_compiler_flag("-Wno-psabi") + ei_add_cxx_compiler_flag("-Wno-variadic-macros") + ei_add_cxx_compiler_flag("-Wno-long-long") + + ei_add_cxx_compiler_flag("-fno-check-new") + ei_add_cxx_compiler_flag("-fno-common") + ei_add_cxx_compiler_flag("-fstrict-aliasing") + ei_add_cxx_compiler_flag("-wd981") # disable ICC's "operands are evaluated in unspecified order" remark + ei_add_cxx_compiler_flag("-wd2304") # disable ICC's "warning #2304: non-explicit constructor with single argument may cause implicit type conversion" produced by -Wnon-virtual-dtor + + + # The -ansi flag must be added last, otherwise it is also used as a linker flag by check_cxx_compiler_flag making it fails + # Moreover we should not set both -strict-ansi and -ansi + check_cxx_compiler_flag("-strict-ansi" COMPILER_SUPPORT_STRICTANSI) + ei_add_cxx_compiler_flag("-Qunused-arguments") # disable clang warning: argument unused during compilation: '-ansi' + + if(COMPILER_SUPPORT_STRICTANSI) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -strict-ansi") + else() + ei_add_cxx_compiler_flag("-ansi") + endif() + + if(ANDROID_NDK) + ei_add_cxx_compiler_flag("-pie") + ei_add_cxx_compiler_flag("-fPIE") + endif() + + set(CMAKE_REQUIRED_FLAGS "") + + option(EIGEN_TEST_SSE2 "Enable/Disable SSE2 in tests/examples" OFF) + if(EIGEN_TEST_SSE2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse2") + message(STATUS "Enabling SSE2 in tests/examples") + endif() + + option(EIGEN_TEST_SSE3 "Enable/Disable SSE3 in tests/examples" OFF) + if(EIGEN_TEST_SSE3) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse3") + message(STATUS "Enabling SSE3 in tests/examples") + endif() + + option(EIGEN_TEST_SSSE3 "Enable/Disable SSSE3 in tests/examples" OFF) + if(EIGEN_TEST_SSSE3) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mssse3") + message(STATUS "Enabling SSSE3 in tests/examples") + endif() + + option(EIGEN_TEST_SSE4_1 "Enable/Disable SSE4.1 in tests/examples" OFF) + if(EIGEN_TEST_SSE4_1) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1") + message(STATUS "Enabling SSE4.1 in tests/examples") + endif() + + option(EIGEN_TEST_SSE4_2 "Enable/Disable SSE4.2 in tests/examples" OFF) + if(EIGEN_TEST_SSE4_2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.2") + message(STATUS "Enabling SSE4.2 in tests/examples") + endif() + + option(EIGEN_TEST_AVX "Enable/Disable AVX in tests/examples" OFF) + if(EIGEN_TEST_AVX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx") + message(STATUS "Enabling AVX in tests/examples") + endif() + + option(EIGEN_TEST_FMA "Enable/Disable FMA in tests/examples" OFF) + if(EIGEN_TEST_FMA AND NOT EIGEN_TEST_NEON) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfma") + message(STATUS "Enabling FMA in tests/examples") + endif() + + option(EIGEN_TEST_AVX512 "Enable/Disable AVX512 in tests/examples" OFF) + if(EIGEN_TEST_AVX512) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx512f -fabi-version=6 -DEIGEN_ENABLE_AVX512") + message(STATUS "Enabling AVX512 in tests/examples") + endif() + + option(EIGEN_TEST_F16C "Enable/Disable F16C in tests/examples" OFF) + if(EIGEN_TEST_F16C) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mf16c") + message(STATUS "Enabling F16C in tests/examples") + endif() + + option(EIGEN_TEST_ALTIVEC "Enable/Disable AltiVec in tests/examples" OFF) + if(EIGEN_TEST_ALTIVEC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -maltivec -mabi=altivec") + message(STATUS "Enabling AltiVec in tests/examples") + endif() + + option(EIGEN_TEST_VSX "Enable/Disable VSX in tests/examples" OFF) + if(EIGEN_TEST_VSX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m64 -mvsx") + message(STATUS "Enabling VSX in tests/examples") + endif() + + option(EIGEN_TEST_NEON "Enable/Disable Neon in tests/examples" OFF) + if(EIGEN_TEST_NEON) + if(EIGEN_TEST_FMA) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon-vfpv4") + else() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpu=neon") + endif() + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfloat-abi=hard") + message(STATUS "Enabling NEON in tests/examples") + endif() + + option(EIGEN_TEST_NEON64 "Enable/Disable Neon in tests/examples" OFF) + if(EIGEN_TEST_NEON64) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + message(STATUS "Enabling NEON in tests/examples") + endif() + + option(EIGEN_TEST_ZVECTOR "Enable/Disable S390X(zEC13) ZVECTOR in tests/examples" OFF) + if(EIGEN_TEST_ZVECTOR) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -march=z13 -mzvector") + message(STATUS "Enabling S390X(zEC13) ZVECTOR in tests/examples") + endif() + + check_cxx_compiler_flag("-fopenmp" COMPILER_SUPPORT_OPENMP) + if(COMPILER_SUPPORT_OPENMP) + option(EIGEN_TEST_OPENMP "Enable/Disable OpenMP in tests/examples" OFF) + if(EIGEN_TEST_OPENMP) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp") + message(STATUS "Enabling OpenMP in tests/examples") + endif() + endif() + +else(NOT MSVC) + + # C4127 - conditional expression is constant + # C4714 - marked as __forceinline not inlined (I failed to deactivate it selectively) + # We can disable this warning in the unit tests since it is clear that it occurs + # because we are oftentimes returning objects that have a destructor or may + # throw exceptions - in particular in the unit tests we are throwing extra many + # exceptions to cover indexing errors. + # C4505 - unreferenced local function has been removed (impossible to deactive selectively) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc /wd4127 /wd4505 /wd4714") + + # replace all /Wx by /W4 + string(REGEX REPLACE "/W[0-9]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") + + check_cxx_compiler_flag("/openmp" COMPILER_SUPPORT_OPENMP) + if(COMPILER_SUPPORT_OPENMP) + option(EIGEN_TEST_OPENMP "Enable/Disable OpenMP in tests/examples" OFF) + if(EIGEN_TEST_OPENMP) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /openmp") + message(STATUS "Enabling OpenMP in tests/examples") + endif() + endif() + + option(EIGEN_TEST_SSE2 "Enable/Disable SSE2 in tests/examples" OFF) + if(EIGEN_TEST_SSE2) + if(NOT CMAKE_CL_64) + # arch is not supported on 64 bit systems, SSE is enabled automatically. + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE2") + endif(NOT CMAKE_CL_64) + message(STATUS "Enabling SSE2 in tests/examples") + endif(EIGEN_TEST_SSE2) +endif(NOT MSVC) + +option(EIGEN_TEST_NO_EXPLICIT_VECTORIZATION "Disable explicit vectorization in tests/examples" OFF) +option(EIGEN_TEST_X87 "Force using X87 instructions. Implies no vectorization." OFF) +option(EIGEN_TEST_32BIT "Force generating 32bit code." OFF) + +if(EIGEN_TEST_X87) + set(EIGEN_TEST_NO_EXPLICIT_VECTORIZATION ON) + if(CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mfpmath=387") + message(STATUS "Forcing use of x87 instructions in tests/examples") + else() + message(STATUS "EIGEN_TEST_X87 ignored on your compiler") + endif() +endif() + +if(EIGEN_TEST_32BIT) + if(CMAKE_COMPILER_IS_GNUCXX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32") + message(STATUS "Forcing generation of 32-bit code in tests/examples") + else() + message(STATUS "EIGEN_TEST_32BIT ignored on your compiler") + endif() +endif() + +if(EIGEN_TEST_NO_EXPLICIT_VECTORIZATION) + add_definitions(-DEIGEN_DONT_VECTORIZE=1) + message(STATUS "Disabling vectorization in tests/examples") +endif() + +option(EIGEN_TEST_NO_EXPLICIT_ALIGNMENT "Disable explicit alignment (hence vectorization) in tests/examples" OFF) +if(EIGEN_TEST_NO_EXPLICIT_ALIGNMENT) + add_definitions(-DEIGEN_DONT_ALIGN=1) + message(STATUS "Disabling alignment in tests/examples") +endif() + +option(EIGEN_TEST_NO_EXCEPTIONS "Disables C++ exceptions" OFF) +if(EIGEN_TEST_NO_EXCEPTIONS) + ei_add_cxx_compiler_flag("-fno-exceptions") + message(STATUS "Disabling exceptions in tests/examples") +endif() + +set(EIGEN_CUDA_COMPUTE_ARCH 30 CACHE STRING "The CUDA compute architecture level to target when compiling CUDA code") + +include_directories(${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) + +# Backward compatibility support for EIGEN_INCLUDE_INSTALL_DIR +if(EIGEN_INCLUDE_INSTALL_DIR) + message(WARNING "EIGEN_INCLUDE_INSTALL_DIR is deprecated. Use INCLUDE_INSTALL_DIR instead.") +endif() + +if(EIGEN_INCLUDE_INSTALL_DIR AND NOT INCLUDE_INSTALL_DIR) + set(INCLUDE_INSTALL_DIR ${EIGEN_INCLUDE_INSTALL_DIR} + CACHE PATH "The directory relative to CMAKE_PREFIX_PATH where Eigen header files are installed") +else() + set(INCLUDE_INSTALL_DIR + "${CMAKE_INSTALL_INCLUDEDIR}/eigen3" + CACHE PATH "The directory relative to CMAKE_PREFIX_PATH where Eigen header files are installed" + ) +endif() +set(CMAKEPACKAGE_INSTALL_DIR + "${CMAKE_INSTALL_DATADIR}/eigen3/cmake" + CACHE PATH "The directory relative to CMAKE_PREFIX_PATH where Eigen3Config.cmake is installed" + ) +set(PKGCONFIG_INSTALL_DIR + "${CMAKE_INSTALL_DATADIR}/pkgconfig" + CACHE PATH "The directory relative to CMAKE_PREFIX_PATH where eigen3.pc is installed" + ) + + +# similar to set_target_properties but append the property instead of overwriting it +macro(ei_add_target_property target prop value) + + get_target_property(previous ${target} ${prop}) + # if the property wasn't previously set, ${previous} is now "previous-NOTFOUND" which cmake allows catching with plain if() + if(NOT previous) + set(previous "") + endif(NOT previous) + set_target_properties(${target} PROPERTIES ${prop} "${previous} ${value}") +endmacro(ei_add_target_property) + +install(FILES + signature_of_eigen3_matrix_library + DESTINATION ${INCLUDE_INSTALL_DIR} COMPONENT Devel + ) + +if(EIGEN_BUILD_PKGCONFIG) + configure_file(eigen3.pc.in eigen3.pc @ONLY) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/eigen3.pc + DESTINATION ${PKGCONFIG_INSTALL_DIR} + ) +endif() + +add_subdirectory(Eigen) + +add_subdirectory(doc EXCLUDE_FROM_ALL) + +option(BUILD_TESTING "Enable creation of Eigen tests." ON) +if(BUILD_TESTING) + include(EigenConfigureTesting) + + if(EIGEN_LEAVE_TEST_IN_ALL_TARGET) + add_subdirectory(test) # can't do EXCLUDE_FROM_ALL here, breaks CTest + else() + add_subdirectory(test EXCLUDE_FROM_ALL) + endif() +endif() + +if(EIGEN_LEAVE_TEST_IN_ALL_TARGET) + add_subdirectory(blas) + add_subdirectory(lapack) +else() + add_subdirectory(blas EXCLUDE_FROM_ALL) + add_subdirectory(lapack EXCLUDE_FROM_ALL) +endif() + +# add SYCL +option(EIGEN_TEST_SYCL "Add Sycl support." OFF) +if(EIGEN_TEST_SYCL) + set (CMAKE_MODULE_PATH "${CMAKE_ROOT}/Modules" "cmake/Modules/" "${CMAKE_MODULE_PATH}") + include(FindComputeCpp) +endif() + +add_subdirectory(unsupported) + +add_subdirectory(demos EXCLUDE_FROM_ALL) + +# must be after test and unsupported, for configuring buildtests.in +add_subdirectory(scripts EXCLUDE_FROM_ALL) + +# TODO: consider also replacing EIGEN_BUILD_BTL by a custom target "make btl"? +if(EIGEN_BUILD_BTL) + add_subdirectory(bench/btl EXCLUDE_FROM_ALL) +endif(EIGEN_BUILD_BTL) + +if(NOT WIN32) + add_subdirectory(bench/spbench EXCLUDE_FROM_ALL) +endif(NOT WIN32) + +configure_file(scripts/cdashtesting.cmake.in cdashtesting.cmake @ONLY) + +if(BUILD_TESTING) + ei_testing_print_summary() +endif() + +message(STATUS "") +message(STATUS "Configured Eigen ${EIGEN_VERSION_NUMBER}") +message(STATUS "") + +option(EIGEN_FAILTEST "Enable failtests." OFF) +if(EIGEN_FAILTEST) + add_subdirectory(failtest) +endif() + +string(TOLOWER "${CMAKE_GENERATOR}" cmake_generator_tolower) +if(cmake_generator_tolower MATCHES "makefile") + message(STATUS "Some things you can do now:") + message(STATUS "--------------+--------------------------------------------------------------") + message(STATUS "Command | Description") + message(STATUS "--------------+--------------------------------------------------------------") + message(STATUS "make install | Install Eigen. Headers will be installed to:") + message(STATUS " | /") + message(STATUS " | Using the following values:") + message(STATUS " | CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}") + message(STATUS " | INCLUDE_INSTALL_DIR: ${INCLUDE_INSTALL_DIR}") + message(STATUS " | Change the install location of Eigen headers using:") + message(STATUS " | cmake . -DCMAKE_INSTALL_PREFIX=yourprefix") + message(STATUS " | Or:") + message(STATUS " | cmake . -DINCLUDE_INSTALL_DIR=yourdir") + message(STATUS "make doc | Generate the API documentation, requires Doxygen & LaTeX") + message(STATUS "make check | Build and run the unit-tests. Read this page:") + message(STATUS " | http://eigen.tuxfamily.org/index.php?title=Tests") + message(STATUS "make blas | Build BLAS library (not the same thing as Eigen)") + message(STATUS "make uninstall| Removes files installed by make install") + message(STATUS "--------------+--------------------------------------------------------------") +else() + message(STATUS "To build/run the unit tests, read this page:") + message(STATUS " http://eigen.tuxfamily.org/index.php?title=Tests") +endif() + +message(STATUS "") + + +set ( EIGEN_VERSION_STRING ${EIGEN_VERSION_NUMBER} ) +set ( EIGEN_VERSION_MAJOR ${EIGEN_WORLD_VERSION} ) +set ( EIGEN_VERSION_MINOR ${EIGEN_MAJOR_VERSION} ) +set ( EIGEN_VERSION_PATCH ${EIGEN_MINOR_VERSION} ) +set ( EIGEN_DEFINITIONS "") +set ( EIGEN_INCLUDE_DIR "${CMAKE_INSTALL_PREFIX}/${INCLUDE_INSTALL_DIR}" ) +set ( EIGEN_ROOT_DIR ${CMAKE_INSTALL_PREFIX} ) + +# Interface libraries require at least CMake 3.0 +if (NOT CMAKE_VERSION VERSION_LESS 3.0) + include (CMakePackageConfigHelpers) + + # Imported target support + add_library (eigen INTERFACE) + + target_compile_definitions (eigen INTERFACE ${EIGEN_DEFINITIONS}) + target_include_directories (eigen INTERFACE + $ + $ + ) + + # Export as title case Eigen + set_target_properties (eigen PROPERTIES EXPORT_NAME Eigen) + + install (TARGETS eigen EXPORT Eigen3Targets) + + configure_package_config_file ( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Eigen3Config.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake + PATH_VARS EIGEN_INCLUDE_DIR EIGEN_ROOT_DIR + INSTALL_DESTINATION ${CMAKEPACKAGE_INSTALL_DIR} + NO_CHECK_REQUIRED_COMPONENTS_MACRO # Eigen does not provide components + ) + # Remove CMAKE_SIZEOF_VOID_P from Eigen3ConfigVersion.cmake since Eigen does + # not depend on architecture specific settings or libraries. More + # specifically, an Eigen3Config.cmake generated from a 64 bit target can be + # used for 32 bit targets as well (and vice versa). + set (_Eigen3_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) + unset (CMAKE_SIZEOF_VOID_P) + write_basic_package_version_file (Eigen3ConfigVersion.cmake + VERSION ${EIGEN_VERSION_NUMBER} + COMPATIBILITY SameMajorVersion) + set (CMAKE_SIZEOF_VOID_P ${_Eigen3_CMAKE_SIZEOF_VOID_P}) + + # The Eigen target will be located in the Eigen3 namespace. Other CMake + # targets can refer to it using Eigen3::Eigen. + export (TARGETS eigen NAMESPACE Eigen3:: FILE Eigen3Targets.cmake) + # Export Eigen3 package to CMake registry such that it can be easily found by + # CMake even if it has not been installed to a standard directory. + export (PACKAGE Eigen3) + + install (EXPORT Eigen3Targets NAMESPACE Eigen3:: DESTINATION ${CMAKEPACKAGE_INSTALL_DIR}) + +else (NOT CMAKE_VERSION VERSION_LESS 3.0) + # Fallback to legacy Eigen3Config.cmake without the imported target + + # If CMakePackageConfigHelpers module is available (CMake >= 2.8.8) + # create a relocatable Config file, otherwise leave the hardcoded paths + include(CMakePackageConfigHelpers OPTIONAL RESULT_VARIABLE CPCH_PATH) + + if(CPCH_PATH) + configure_package_config_file ( + ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Eigen3ConfigLegacy.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake + PATH_VARS EIGEN_INCLUDE_DIR EIGEN_ROOT_DIR + INSTALL_DESTINATION ${CMAKEPACKAGE_INSTALL_DIR} + NO_CHECK_REQUIRED_COMPONENTS_MACRO # Eigen does not provide components + ) + else() + # The PACKAGE_* variables are defined by the configure_package_config_file + # but without it we define them manually to the hardcoded paths + set(PACKAGE_INIT "") + set(PACKAGE_EIGEN_INCLUDE_DIR ${EIGEN_INCLUDE_DIR}) + set(PACKAGE_EIGEN_ROOT_DIR ${EIGEN_ROOT_DIR}) + configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Eigen3ConfigLegacy.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake + @ONLY ESCAPE_QUOTES ) + endif() + + write_basic_package_version_file( Eigen3ConfigVersion.cmake + VERSION ${EIGEN_VERSION_NUMBER} + COMPATIBILITY SameMajorVersion ) + +endif (NOT CMAKE_VERSION VERSION_LESS 3.0) + +install ( FILES ${CMAKE_CURRENT_SOURCE_DIR}/cmake/UseEigen3.cmake + ${CMAKE_CURRENT_BINARY_DIR}/Eigen3Config.cmake + ${CMAKE_CURRENT_BINARY_DIR}/Eigen3ConfigVersion.cmake + DESTINATION ${CMAKEPACKAGE_INSTALL_DIR} ) + +# Add uninstall target +add_custom_target ( uninstall + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_SOURCE_DIR}/cmake/EigenUninstall.cmake) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.BSD b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.BSD new file mode 100644 index 0000000000000000000000000000000000000000..11971ffe25ba29dd65800b77864490ee6df251c2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.BSD @@ -0,0 +1,26 @@ +/* + Copyright (c) 2011, Intel Corporation. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.GPL b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.GPL new file mode 100644 index 0000000000000000000000000000000000000000..94a9ed024d3859793618152ea559a168bbcbb5e2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.GPL @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.LGPL b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.LGPL new file mode 100644 index 0000000000000000000000000000000000000000..4362b49151d7b34ef83b3067a8f9c9f877d72a0e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.LGPL @@ -0,0 +1,502 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MINPACK b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MINPACK new file mode 100644 index 0000000000000000000000000000000000000000..ae7984daec98f7311b0a4e288583e24c9cd6a7bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MINPACK @@ -0,0 +1,52 @@ +Minpack Copyright Notice (1999) University of Chicago. All rights reserved + +Redistribution and use in source and binary forms, with or +without modification, are permitted provided that the +following conditions are met: + +1. Redistributions of source code must retain the above +copyright notice, this list of conditions and the following +disclaimer. + +2. Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following +disclaimer in the documentation and/or other materials +provided with the distribution. + +3. The end-user documentation included with the +redistribution, if any, must include the following +acknowledgment: + + "This product includes software developed by the + University of Chicago, as Operator of Argonne National + Laboratory. + +Alternately, this acknowledgment may appear in the software +itself, if and wherever such third-party acknowledgments +normally appear. + +4. WARRANTY DISCLAIMER. THE SOFTWARE IS SUPPLIED "AS IS" +WITHOUT WARRANTY OF ANY KIND. THE COPYRIGHT HOLDER, THE +UNITED STATES, THE UNITED STATES DEPARTMENT OF ENERGY, AND +THEIR EMPLOYEES: (1) DISCLAIM ANY WARRANTIES, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE +OR NON-INFRINGEMENT, (2) DO NOT ASSUME ANY LEGAL LIABILITY +OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS, OR +USEFULNESS OF THE SOFTWARE, (3) DO NOT REPRESENT THAT USE OF +THE SOFTWARE WOULD NOT INFRINGE PRIVATELY OWNED RIGHTS, (4) +DO NOT WARRANT THAT THE SOFTWARE WILL FUNCTION +UNINTERRUPTED, THAT IT IS ERROR-FREE OR THAT ANY ERRORS WILL +BE CORRECTED. + +5. LIMITATION OF LIABILITY. IN NO EVENT WILL THE COPYRIGHT +HOLDER, THE UNITED STATES, THE UNITED STATES DEPARTMENT OF +ENERGY, OR THEIR EMPLOYEES: BE LIABLE FOR ANY INDIRECT, +INCIDENTAL, CONSEQUENTIAL, SPECIAL OR PUNITIVE DAMAGES OF +ANY KIND OR NATURE, INCLUDING BUT NOT LIMITED TO LOSS OF +PROFITS OR LOSS OF DATA, FOR ANY REASON WHATSOEVER, WHETHER +SUCH LIABILITY IS ASSERTED ON THE BASIS OF CONTRACT, TORT +(INCLUDING NEGLIGENCE OR STRICT LIABILITY), OR OTHERWISE, +EVEN IF ANY OF SAID PARTIES HAS BEEN WARNED OF THE +POSSIBILITY OF SUCH LOSS OR DAMAGES. + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MPL2 b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MPL2 new file mode 100644 index 0000000000000000000000000000000000000000..14e2f777f6c395e7e04ab4aa306bbcc4b0c1120e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.MPL2 @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.README b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.README new file mode 100644 index 0000000000000000000000000000000000000000..de5b6321582327d85c88749388edf2576cd242c8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/COPYING.README @@ -0,0 +1,18 @@ +Eigen is primarily MPL2 licensed. See COPYING.MPL2 and these links: + http://www.mozilla.org/MPL/2.0/ + http://www.mozilla.org/MPL/2.0/FAQ.html + +Some files contain third-party code under BSD or LGPL licenses, whence the other +COPYING.* files here. + +All the LGPL code is either LGPL 2.1-only, or LGPL 2.1-or-later. +For this reason, the COPYING.LGPL file contains the LGPL 2.1 text. + +If you want to guarantee that the Eigen code that you are #including is licensed +under the MPL2 and possibly more permissive licenses (like BSD), #define this +preprocessor symbol: + EIGEN_MPL2_ONLY +For example, with most compilers, you could add this to your project CXXFLAGS: + -DEIGEN_MPL2_ONLY +This will cause a compilation error to be generated if you #include any code that is +LGPL licensed. diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestConfig.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestConfig.cmake new file mode 100644 index 0000000000000000000000000000000000000000..0039bf8acd810f7cbd107de6c5fcc493043c37c7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestConfig.cmake @@ -0,0 +1,13 @@ +## This file should be placed in the root directory of your project. +## Then modify the CMakeLists.txt file in the root directory of your +## project to incorporate the testing dashboard. +## # The following are required to uses Dart and the Cdash dashboard +## ENABLE_TESTING() +## INCLUDE(CTest) +set(CTEST_PROJECT_NAME "Eigen 3.3") +set(CTEST_NIGHTLY_START_TIME "00:00:00 UTC") + +set(CTEST_DROP_METHOD "http") +set(CTEST_DROP_SITE "manao.inria.fr") +set(CTEST_DROP_LOCATION "/CDash/submit.php?project=Eigen+3.3") +set(CTEST_DROP_SITE_CDASH TRUE) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestCustom.cmake.in b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestCustom.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..89e487f05a0d19e336302e09747f6b94df43db03 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/CTestCustom.cmake.in @@ -0,0 +1,4 @@ + +set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_WARNINGS "2000") +set(CTEST_CUSTOM_MAXIMUM_NUMBER_OF_ERRORS "2000") +list(APPEND CTEST_CUSTOM_ERROR_EXCEPTION @EIGEN_CTEST_ERROR_EXCEPTION@) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9eb502b792d4a9607e2d323f2d8114939b43c209 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CMakeLists.txt @@ -0,0 +1,19 @@ +include(RegexUtils) +test_escape_string_as_regex() + +file(GLOB Eigen_directory_files "*") + +escape_string_as_regex(ESCAPED_CMAKE_CURRENT_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}") + +foreach(f ${Eigen_directory_files}) + if(NOT f MATCHES "\\.txt" AND NOT f MATCHES "${ESCAPED_CMAKE_CURRENT_SOURCE_DIR}/[.].+" AND NOT f MATCHES "${ESCAPED_CMAKE_CURRENT_SOURCE_DIR}/src") + list(APPEND Eigen_directory_files_to_install ${f}) + endif() +endforeach(f ${Eigen_directory_files}) + +install(FILES + ${Eigen_directory_files_to_install} + DESTINATION ${INCLUDE_INSTALL_DIR}/Eigen COMPONENT Devel + ) + +install(DIRECTORY src DESTINATION ${INCLUDE_INSTALL_DIR}/Eigen COMPONENT Devel FILES_MATCHING PATTERN "*.h") diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Cholesky b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Cholesky new file mode 100644 index 0000000000000000000000000000000000000000..1332b540d838247e671ac3e256512501ac985846 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Cholesky @@ -0,0 +1,46 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLESKY_MODULE_H +#define EIGEN_CHOLESKY_MODULE_H + +#include "Core" +#include "Jacobi" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Cholesky_Module Cholesky module + * + * + * + * This module provides two variants of the Cholesky decomposition for selfadjoint (hermitian) matrices. + * Those decompositions are also accessible via the following methods: + * - MatrixBase::llt() + * - MatrixBase::ldlt() + * - SelfAdjointView::llt() + * - SelfAdjointView::ldlt() + * + * \code + * #include + * \endcode + */ + +#include "src/Cholesky/LLT.h" +#include "src/Cholesky/LDLT.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/Cholesky/LLT_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CHOLESKY_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CholmodSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CholmodSupport new file mode 100644 index 0000000000000000000000000000000000000000..bed8924d31e0b3f46713cf74ba3deb6a63f9f590 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/CholmodSupport @@ -0,0 +1,48 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLMODSUPPORT_MODULE_H +#define EIGEN_CHOLMODSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { + #include +} + +/** \ingroup Support_modules + * \defgroup CholmodSupport_Module CholmodSupport module + * + * This module provides an interface to the Cholmod library which is part of the suitesparse package. + * It provides the two following main factorization classes: + * - class CholmodSupernodalLLT: a supernodal LLT Cholesky factorization. + * - class CholmodDecomposiiton: a general L(D)LT Cholesky factorization with automatic or explicit runtime selection of the underlying factorization method (supernodal or simplicial). + * + * For the sake of completeness, this module also propose the two following classes: + * - class CholmodSimplicialLLT + * - class CholmodSimplicialLDLT + * Note that these classes does not bring any particular advantage compared to the built-in + * SimplicialLLT and SimplicialLDLT factorization classes. + * + * \code + * #include + * \endcode + * + * In order to use this module, the cholmod headers must be accessible from the include paths, and your binary must be linked to the cholmod library and its dependencies. + * The dependencies depend on how cholmod has been compiled. + * For a cmake based project, you can use our FindCholmod.cmake module to help you in this task. + * + */ + +#include "src/CholmodSupport/CholmodSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CHOLMODSUPPORT_MODULE_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Core b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Core new file mode 100644 index 0000000000000000000000000000000000000000..b923b8c000cb61bc60fecc3b449b3beb6f12ed34 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Core @@ -0,0 +1,537 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2007-2011 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CORE_H +#define EIGEN_CORE_H + +// first thing Eigen does: stop the compiler from committing suicide +#include "src/Core/util/DisableStupidWarnings.h" + +#if defined(__CUDACC__) && !defined(EIGEN_NO_CUDA) + #define EIGEN_CUDACC __CUDACC__ +#endif + +#if defined(__CUDA_ARCH__) && !defined(EIGEN_NO_CUDA) + #define EIGEN_CUDA_ARCH __CUDA_ARCH__ +#endif + +#if defined(__CUDACC_VER_MAJOR__) && (__CUDACC_VER_MAJOR__ >= 9) +#define EIGEN_CUDACC_VER ((__CUDACC_VER_MAJOR__ * 10000) + (__CUDACC_VER_MINOR__ * 100)) +#elif defined(__CUDACC_VER__) +#define EIGEN_CUDACC_VER __CUDACC_VER__ +#else +#define EIGEN_CUDACC_VER 0 +#endif + +// Handle NVCC/CUDA/SYCL +#if defined(__CUDACC__) || defined(__SYCL_DEVICE_ONLY__) + // Do not try asserts on CUDA and SYCL! + #ifndef EIGEN_NO_DEBUG + #define EIGEN_NO_DEBUG + #endif + + #ifdef EIGEN_INTERNAL_DEBUGGING + #undef EIGEN_INTERNAL_DEBUGGING + #endif + + #ifdef EIGEN_EXCEPTIONS + #undef EIGEN_EXCEPTIONS + #endif + + // All functions callable from CUDA code must be qualified with __device__ + #ifdef __CUDACC__ + // Do not try to vectorize on CUDA and SYCL! + #ifndef EIGEN_DONT_VECTORIZE + #define EIGEN_DONT_VECTORIZE + #endif + + #define EIGEN_DEVICE_FUNC __host__ __device__ + // We need cuda_runtime.h to ensure that that EIGEN_USING_STD_MATH macro + // works properly on the device side + #include + #else + #define EIGEN_DEVICE_FUNC + #endif + +#else + #define EIGEN_DEVICE_FUNC + +#endif + +// When compiling CUDA device code with NVCC, pull in math functions from the +// global namespace. In host mode, and when device doee with clang, use the +// std versions. +#if defined(__CUDA_ARCH__) && defined(__NVCC__) + #define EIGEN_USING_STD_MATH(FUNC) using ::FUNC; +#else + #define EIGEN_USING_STD_MATH(FUNC) using std::FUNC; +#endif + +#if (defined(_CPPUNWIND) || defined(__EXCEPTIONS)) && !defined(__CUDA_ARCH__) && !defined(EIGEN_EXCEPTIONS) && !defined(EIGEN_USE_SYCL) + #define EIGEN_EXCEPTIONS +#endif + +#ifdef EIGEN_EXCEPTIONS + #include +#endif + +// then include this file where all our macros are defined. It's really important to do it first because +// it's where we do all the alignment settings (platform detection and honoring the user's will if he +// defined e.g. EIGEN_DONT_ALIGN) so it needs to be done before we do anything with vectorization. +#include "src/Core/util/Macros.h" + +// Disable the ipa-cp-clone optimization flag with MinGW 6.x or newer (enabled by default with -O3) +// See http://eigen.tuxfamily.org/bz/show_bug.cgi?id=556 for details. +#if EIGEN_COMP_MINGW && EIGEN_GNUC_AT_LEAST(4,6) + #pragma GCC optimize ("-fno-ipa-cp-clone") +#endif + +#include + +// this include file manages BLAS and MKL related macros +// and inclusion of their respective header files +#include "src/Core/util/MKL_support.h" + +// if alignment is disabled, then disable vectorization. Note: EIGEN_MAX_ALIGN_BYTES is the proper check, it takes into +// account both the user's will (EIGEN_MAX_ALIGN_BYTES,EIGEN_DONT_ALIGN) and our own platform checks +#if EIGEN_MAX_ALIGN_BYTES==0 + #ifndef EIGEN_DONT_VECTORIZE + #define EIGEN_DONT_VECTORIZE + #endif +#endif + +#if EIGEN_COMP_MSVC + #include // for _aligned_malloc -- need it regardless of whether vectorization is enabled + #if (EIGEN_COMP_MSVC >= 1500) // 2008 or later + // Remember that usage of defined() in a #define is undefined by the standard. + // a user reported that in 64-bit mode, MSVC doesn't care to define _M_IX86_FP. + #if (defined(_M_IX86_FP) && (_M_IX86_FP >= 2)) || EIGEN_ARCH_x86_64 + #define EIGEN_SSE2_ON_MSVC_2008_OR_LATER + #endif + #endif +#else + // Remember that usage of defined() in a #define is undefined by the standard + #if (defined __SSE2__) && ( (!EIGEN_COMP_GNUC) || EIGEN_COMP_ICC || EIGEN_GNUC_AT_LEAST(4,2) ) + #define EIGEN_SSE2_ON_NON_MSVC_BUT_NOT_OLD_GCC + #endif +#endif + +#ifndef EIGEN_DONT_VECTORIZE + + #if defined (EIGEN_SSE2_ON_NON_MSVC_BUT_NOT_OLD_GCC) || defined(EIGEN_SSE2_ON_MSVC_2008_OR_LATER) + + // Defines symbols for compile-time detection of which instructions are + // used. + // EIGEN_VECTORIZE_YY is defined if and only if the instruction set YY is used + #define EIGEN_VECTORIZE + #define EIGEN_VECTORIZE_SSE + #define EIGEN_VECTORIZE_SSE2 + + // Detect sse3/ssse3/sse4: + // gcc and icc defines __SSE3__, ... + // there is no way to know about this on msvc. You can define EIGEN_VECTORIZE_SSE* if you + // want to force the use of those instructions with msvc. + #ifdef __SSE3__ + #define EIGEN_VECTORIZE_SSE3 + #endif + #ifdef __SSSE3__ + #define EIGEN_VECTORIZE_SSSE3 + #endif + #ifdef __SSE4_1__ + #define EIGEN_VECTORIZE_SSE4_1 + #endif + #ifdef __SSE4_2__ + #define EIGEN_VECTORIZE_SSE4_2 + #endif + #ifdef __AVX__ + #define EIGEN_VECTORIZE_AVX + #define EIGEN_VECTORIZE_SSE3 + #define EIGEN_VECTORIZE_SSSE3 + #define EIGEN_VECTORIZE_SSE4_1 + #define EIGEN_VECTORIZE_SSE4_2 + #endif + #ifdef __AVX2__ + #define EIGEN_VECTORIZE_AVX2 + #endif + #ifdef __FMA__ + #define EIGEN_VECTORIZE_FMA + #endif + #if defined(__AVX512F__) && defined(EIGEN_ENABLE_AVX512) + #define EIGEN_VECTORIZE_AVX512 + #define EIGEN_VECTORIZE_AVX2 + #define EIGEN_VECTORIZE_AVX + #define EIGEN_VECTORIZE_FMA + #ifdef __AVX512DQ__ + #define EIGEN_VECTORIZE_AVX512DQ + #endif + #ifdef __AVX512ER__ + #define EIGEN_VECTORIZE_AVX512ER + #endif + #endif + + // include files + + // This extern "C" works around a MINGW-w64 compilation issue + // https://sourceforge.net/tracker/index.php?func=detail&aid=3018394&group_id=202880&atid=983354 + // In essence, intrin.h is included by windows.h and also declares intrinsics (just as emmintrin.h etc. below do). + // However, intrin.h uses an extern "C" declaration, and g++ thus complains of duplicate declarations + // with conflicting linkage. The linkage for intrinsics doesn't matter, but at that stage the compiler doesn't know; + // so, to avoid compile errors when windows.h is included after Eigen/Core, ensure intrinsics are extern "C" here too. + // notice that since these are C headers, the extern "C" is theoretically needed anyways. + extern "C" { + // In theory we should only include immintrin.h and not the other *mmintrin.h header files directly. + // Doing so triggers some issues with ICC. However old gcc versions seems to not have this file, thus: + #if EIGEN_COMP_ICC >= 1110 + #include + #else + #include + #include + #include + #ifdef EIGEN_VECTORIZE_SSE3 + #include + #endif + #ifdef EIGEN_VECTORIZE_SSSE3 + #include + #endif + #ifdef EIGEN_VECTORIZE_SSE4_1 + #include + #endif + #ifdef EIGEN_VECTORIZE_SSE4_2 + #include + #endif + #if defined(EIGEN_VECTORIZE_AVX) || defined(EIGEN_VECTORIZE_AVX512) + #include + #endif + #endif + } // end extern "C" + #elif defined __VSX__ + #define EIGEN_VECTORIZE + #define EIGEN_VECTORIZE_VSX + #include + // We need to #undef all these ugly tokens defined in + // => use __vector instead of vector + #undef bool + #undef vector + #undef pixel + #elif defined __ALTIVEC__ + #define EIGEN_VECTORIZE + #define EIGEN_VECTORIZE_ALTIVEC + #include + // We need to #undef all these ugly tokens defined in + // => use __vector instead of vector + #undef bool + #undef vector + #undef pixel + #elif (defined __ARM_NEON) || (defined __ARM_NEON__) + #define EIGEN_VECTORIZE + #define EIGEN_VECTORIZE_NEON + #include + #elif (defined __s390x__ && defined __VEC__) + #define EIGEN_VECTORIZE + #define EIGEN_VECTORIZE_ZVECTOR + #include + #endif +#endif + +#if defined(__F16C__) && !defined(EIGEN_COMP_CLANG) + // We can use the optimized fp16 to float and float to fp16 conversion routines + #define EIGEN_HAS_FP16_C +#endif + +#if defined __CUDACC__ + #define EIGEN_VECTORIZE_CUDA + #include + #if EIGEN_CUDACC_VER >= 70500 + #define EIGEN_HAS_CUDA_FP16 + #endif +#endif + +#if defined EIGEN_HAS_CUDA_FP16 + #include + #include +#endif + +#if (defined _OPENMP) && (!defined EIGEN_DONT_PARALLELIZE) + #define EIGEN_HAS_OPENMP +#endif + +#ifdef EIGEN_HAS_OPENMP +#include +#endif + +// MSVC for windows mobile does not have the errno.h file +#if !(EIGEN_COMP_MSVC && EIGEN_OS_WINCE) && !EIGEN_COMP_ARM +#define EIGEN_HAS_ERRNO +#endif + +#ifdef EIGEN_HAS_ERRNO +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for CHAR_BIT +// for min/max: +#include + +// for std::is_nothrow_move_assignable +#ifdef EIGEN_INCLUDE_TYPE_TRAITS +#include +#endif + +// for outputting debug info +#ifdef EIGEN_DEBUG_ASSIGN +#include +#endif + +// required for __cpuid, needs to be included after cmath +#if EIGEN_COMP_MSVC && EIGEN_ARCH_i386_OR_x86_64 && !EIGEN_OS_WINCE + #include +#endif + +/** \brief Namespace containing all symbols from the %Eigen library. */ +namespace Eigen { + +inline static const char *SimdInstructionSetsInUse(void) { +#if defined(EIGEN_VECTORIZE_AVX512) + return "AVX512, FMA, AVX2, AVX, SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2"; +#elif defined(EIGEN_VECTORIZE_AVX) + return "AVX SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2"; +#elif defined(EIGEN_VECTORIZE_SSE4_2) + return "SSE, SSE2, SSE3, SSSE3, SSE4.1, SSE4.2"; +#elif defined(EIGEN_VECTORIZE_SSE4_1) + return "SSE, SSE2, SSE3, SSSE3, SSE4.1"; +#elif defined(EIGEN_VECTORIZE_SSSE3) + return "SSE, SSE2, SSE3, SSSE3"; +#elif defined(EIGEN_VECTORIZE_SSE3) + return "SSE, SSE2, SSE3"; +#elif defined(EIGEN_VECTORIZE_SSE2) + return "SSE, SSE2"; +#elif defined(EIGEN_VECTORIZE_ALTIVEC) + return "AltiVec"; +#elif defined(EIGEN_VECTORIZE_VSX) + return "VSX"; +#elif defined(EIGEN_VECTORIZE_NEON) + return "ARM NEON"; +#elif defined(EIGEN_VECTORIZE_ZVECTOR) + return "S390X ZVECTOR"; +#else + return "None"; +#endif +} + +} // end namespace Eigen + +#if defined EIGEN2_SUPPORT_STAGE40_FULL_EIGEN3_STRICTNESS || defined EIGEN2_SUPPORT_STAGE30_FULL_EIGEN3_API || defined EIGEN2_SUPPORT_STAGE20_RESOLVE_API_CONFLICTS || defined EIGEN2_SUPPORT_STAGE10_FULL_EIGEN2_API || defined EIGEN2_SUPPORT +// This will generate an error message: +#error Eigen2-support is only available up to version 3.2. Please go to "http://eigen.tuxfamily.org/index.php?title=Eigen2" for further information +#endif + +namespace Eigen { + +// we use size_t frequently and we'll never remember to prepend it with std:: everytime just to +// ensure QNX/QCC support +using std::size_t; +// gcc 4.6.0 wants std:: for ptrdiff_t +using std::ptrdiff_t; + +} + +/** \defgroup Core_Module Core module + * This is the main module of Eigen providing dense matrix and vector support + * (both fixed and dynamic size) with all the features corresponding to a BLAS library + * and much more... + * + * \code + * #include + * \endcode + */ + +#include "src/Core/util/Constants.h" +#include "src/Core/util/Meta.h" +#include "src/Core/util/ForwardDeclarations.h" +#include "src/Core/util/StaticAssert.h" +#include "src/Core/util/XprHelper.h" +#include "src/Core/util/Memory.h" + +#include "src/Core/NumTraits.h" +#include "src/Core/MathFunctions.h" +#include "src/Core/GenericPacketMath.h" +#include "src/Core/MathFunctionsImpl.h" +#include "src/Core/arch/Default/ConjHelper.h" + +#if defined EIGEN_VECTORIZE_AVX512 + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/AVX/PacketMath.h" + #include "src/Core/arch/AVX512/PacketMath.h" + #include "src/Core/arch/AVX512/MathFunctions.h" +#elif defined EIGEN_VECTORIZE_AVX + // Use AVX for floats and doubles, SSE for integers + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/SSE/Complex.h" + #include "src/Core/arch/SSE/MathFunctions.h" + #include "src/Core/arch/AVX/PacketMath.h" + #include "src/Core/arch/AVX/MathFunctions.h" + #include "src/Core/arch/AVX/Complex.h" + #include "src/Core/arch/AVX/TypeCasting.h" + #include "src/Core/arch/SSE/TypeCasting.h" +#elif defined EIGEN_VECTORIZE_SSE + #include "src/Core/arch/SSE/PacketMath.h" + #include "src/Core/arch/SSE/MathFunctions.h" + #include "src/Core/arch/SSE/Complex.h" + #include "src/Core/arch/SSE/TypeCasting.h" +#elif defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) + #include "src/Core/arch/AltiVec/PacketMath.h" + #include "src/Core/arch/AltiVec/MathFunctions.h" + #include "src/Core/arch/AltiVec/Complex.h" +#elif defined EIGEN_VECTORIZE_NEON + #include "src/Core/arch/NEON/PacketMath.h" + #include "src/Core/arch/NEON/MathFunctions.h" + #include "src/Core/arch/NEON/Complex.h" +#elif defined EIGEN_VECTORIZE_ZVECTOR + #include "src/Core/arch/ZVector/PacketMath.h" + #include "src/Core/arch/ZVector/MathFunctions.h" + #include "src/Core/arch/ZVector/Complex.h" +#endif + +// Half float support +#include "src/Core/arch/CUDA/Half.h" +#include "src/Core/arch/CUDA/PacketMathHalf.h" +#include "src/Core/arch/CUDA/TypeCasting.h" + +#if defined EIGEN_VECTORIZE_CUDA + #include "src/Core/arch/CUDA/PacketMath.h" + #include "src/Core/arch/CUDA/MathFunctions.h" +#endif + +#include "src/Core/arch/Default/Settings.h" + +#include "src/Core/functors/TernaryFunctors.h" +#include "src/Core/functors/BinaryFunctors.h" +#include "src/Core/functors/UnaryFunctors.h" +#include "src/Core/functors/NullaryFunctors.h" +#include "src/Core/functors/StlFunctors.h" +#include "src/Core/functors/AssignmentFunctors.h" + +// Specialized functors to enable the processing of complex numbers +// on CUDA devices +#include "src/Core/arch/CUDA/Complex.h" + +#include "src/Core/IO.h" +#include "src/Core/DenseCoeffsBase.h" +#include "src/Core/DenseBase.h" +#include "src/Core/MatrixBase.h" +#include "src/Core/EigenBase.h" + +#include "src/Core/Product.h" +#include "src/Core/CoreEvaluators.h" +#include "src/Core/AssignEvaluator.h" + +#ifndef EIGEN_PARSED_BY_DOXYGEN // work around Doxygen bug triggered by Assign.h r814874 + // at least confirmed with Doxygen 1.5.5 and 1.5.6 + #include "src/Core/Assign.h" +#endif + +#include "src/Core/ArrayBase.h" +#include "src/Core/util/BlasUtil.h" +#include "src/Core/DenseStorage.h" +#include "src/Core/NestByValue.h" + +// #include "src/Core/ForceAlignedAccess.h" + +#include "src/Core/ReturnByValue.h" +#include "src/Core/NoAlias.h" +#include "src/Core/PlainObjectBase.h" +#include "src/Core/Matrix.h" +#include "src/Core/Array.h" +#include "src/Core/CwiseTernaryOp.h" +#include "src/Core/CwiseBinaryOp.h" +#include "src/Core/CwiseUnaryOp.h" +#include "src/Core/CwiseNullaryOp.h" +#include "src/Core/CwiseUnaryView.h" +#include "src/Core/SelfCwiseBinaryOp.h" +#include "src/Core/Dot.h" +#include "src/Core/StableNorm.h" +#include "src/Core/Stride.h" +#include "src/Core/MapBase.h" +#include "src/Core/Map.h" +#include "src/Core/Ref.h" +#include "src/Core/Block.h" +#include "src/Core/VectorBlock.h" +#include "src/Core/Transpose.h" +#include "src/Core/DiagonalMatrix.h" +#include "src/Core/Diagonal.h" +#include "src/Core/DiagonalProduct.h" +#include "src/Core/Redux.h" +#include "src/Core/Visitor.h" +#include "src/Core/Fuzzy.h" +#include "src/Core/Swap.h" +#include "src/Core/CommaInitializer.h" +#include "src/Core/GeneralProduct.h" +#include "src/Core/Solve.h" +#include "src/Core/Inverse.h" +#include "src/Core/SolverBase.h" +#include "src/Core/PermutationMatrix.h" +#include "src/Core/Transpositions.h" +#include "src/Core/TriangularMatrix.h" +#include "src/Core/SelfAdjointView.h" +#include "src/Core/products/GeneralBlockPanelKernel.h" +#include "src/Core/products/Parallelizer.h" +#include "src/Core/ProductEvaluators.h" +#include "src/Core/products/GeneralMatrixVector.h" +#include "src/Core/products/GeneralMatrixMatrix.h" +#include "src/Core/SolveTriangular.h" +#include "src/Core/products/GeneralMatrixMatrixTriangular.h" +#include "src/Core/products/SelfadjointMatrixVector.h" +#include "src/Core/products/SelfadjointMatrixMatrix.h" +#include "src/Core/products/SelfadjointProduct.h" +#include "src/Core/products/SelfadjointRank2Update.h" +#include "src/Core/products/TriangularMatrixVector.h" +#include "src/Core/products/TriangularMatrixMatrix.h" +#include "src/Core/products/TriangularSolverMatrix.h" +#include "src/Core/products/TriangularSolverVector.h" +#include "src/Core/BandMatrix.h" +#include "src/Core/CoreIterators.h" +#include "src/Core/ConditionEstimator.h" + +#include "src/Core/BooleanRedux.h" +#include "src/Core/Select.h" +#include "src/Core/VectorwiseOp.h" +#include "src/Core/Random.h" +#include "src/Core/Replicate.h" +#include "src/Core/Reverse.h" +#include "src/Core/ArrayWrapper.h" + +#ifdef EIGEN_USE_BLAS +#include "src/Core/products/GeneralMatrixMatrix_BLAS.h" +#include "src/Core/products/GeneralMatrixVector_BLAS.h" +#include "src/Core/products/GeneralMatrixMatrixTriangular_BLAS.h" +#include "src/Core/products/SelfadjointMatrixMatrix_BLAS.h" +#include "src/Core/products/SelfadjointMatrixVector_BLAS.h" +#include "src/Core/products/TriangularMatrixMatrix_BLAS.h" +#include "src/Core/products/TriangularMatrixVector_BLAS.h" +#include "src/Core/products/TriangularSolverMatrix_BLAS.h" +#endif // EIGEN_USE_BLAS + +#ifdef EIGEN_USE_MKL_VML +#include "src/Core/Assign_MKL.h" +#endif + +#include "src/Core/GlobalFunctions.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_CORE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Dense b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Dense new file mode 100644 index 0000000000000000000000000000000000000000..5768910bd88c43f0761f2f345c6f0e3b46a4d8ec --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Dense @@ -0,0 +1,7 @@ +#include "Core" +#include "LU" +#include "Cholesky" +#include "QR" +#include "SVD" +#include "Geometry" +#include "Eigenvalues" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigen b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigen new file mode 100644 index 0000000000000000000000000000000000000000..654c8dc6380f7bb21d3ba1a9ce916006043552aa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigen @@ -0,0 +1,2 @@ +#include "Dense" +#include "Sparse" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigenvalues b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigenvalues new file mode 100644 index 0000000000000000000000000000000000000000..f3f661b074bf31bfc603047cc5699c8cf071882e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Eigenvalues @@ -0,0 +1,61 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EIGENVALUES_MODULE_H +#define EIGEN_EIGENVALUES_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "Cholesky" +#include "Jacobi" +#include "Householder" +#include "LU" +#include "Geometry" + +/** \defgroup Eigenvalues_Module Eigenvalues module + * + * + * + * This module mainly provides various eigenvalue solvers. + * This module also provides some MatrixBase methods, including: + * - MatrixBase::eigenvalues(), + * - MatrixBase::operatorNorm() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/RealSvd2x2.h" +#include "src/Eigenvalues/Tridiagonalization.h" +#include "src/Eigenvalues/RealSchur.h" +#include "src/Eigenvalues/EigenSolver.h" +#include "src/Eigenvalues/SelfAdjointEigenSolver.h" +#include "src/Eigenvalues/GeneralizedSelfAdjointEigenSolver.h" +#include "src/Eigenvalues/HessenbergDecomposition.h" +#include "src/Eigenvalues/ComplexSchur.h" +#include "src/Eigenvalues/ComplexEigenSolver.h" +#include "src/Eigenvalues/RealQZ.h" +#include "src/Eigenvalues/GeneralizedEigenSolver.h" +#include "src/Eigenvalues/MatrixBaseEigenvalues.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/Eigenvalues/RealSchur_LAPACKE.h" +#include "src/Eigenvalues/ComplexSchur_LAPACKE.h" +#include "src/Eigenvalues/SelfAdjointEigenSolver_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_EIGENVALUES_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Geometry b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Geometry new file mode 100644 index 0000000000000000000000000000000000000000..716d529529a7fa5e504c743bcbfe5b959391958f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Geometry @@ -0,0 +1,62 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GEOMETRY_MODULE_H +#define EIGEN_GEOMETRY_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "SVD" +#include "LU" +#include + +/** \defgroup Geometry_Module Geometry module + * + * This module provides support for: + * - fixed-size homogeneous transformations + * - translation, scaling, 2D and 3D rotations + * - \link Quaternion quaternions \endlink + * - cross products (\ref MatrixBase::cross, \ref MatrixBase::cross3) + * - orthognal vector generation (\ref MatrixBase::unitOrthogonal) + * - some linear components: \link ParametrizedLine parametrized-lines \endlink and \link Hyperplane hyperplanes \endlink + * - \link AlignedBox axis aligned bounding boxes \endlink + * - \link umeyama least-square transformation fitting \endlink + * + * \code + * #include + * \endcode + */ + +#include "src/Geometry/OrthoMethods.h" +#include "src/Geometry/EulerAngles.h" + +#include "src/Geometry/Homogeneous.h" +#include "src/Geometry/RotationBase.h" +#include "src/Geometry/Rotation2D.h" +#include "src/Geometry/Quaternion.h" +#include "src/Geometry/AngleAxis.h" +#include "src/Geometry/Transform.h" +#include "src/Geometry/Translation.h" +#include "src/Geometry/Scaling.h" +#include "src/Geometry/Hyperplane.h" +#include "src/Geometry/ParametrizedLine.h" +#include "src/Geometry/AlignedBox.h" +#include "src/Geometry/Umeyama.h" + +// Use the SSE optimized version whenever possible. At the moment the +// SSE version doesn't compile when AVX is enabled +#if defined EIGEN_VECTORIZE_SSE && !defined EIGEN_VECTORIZE_AVX +#include "src/Geometry/arch/Geometry_SSE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_GEOMETRY_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Householder b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Householder new file mode 100644 index 0000000000000000000000000000000000000000..89cd81b1afbcff1d01d37585174c3136598a90bb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Householder @@ -0,0 +1,30 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_HOUSEHOLDER_MODULE_H +#define EIGEN_HOUSEHOLDER_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Householder_Module Householder module + * This module provides Householder transformations. + * + * \code + * #include + * \endcode + */ + +#include "src/Householder/Householder.h" +#include "src/Householder/HouseholderSequence.h" +#include "src/Householder/BlockHouseholder.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_HOUSEHOLDER_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/IterativeLinearSolvers b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/IterativeLinearSolvers new file mode 100644 index 0000000000000000000000000000000000000000..957d5750b2cd6f9a429c7140335487a4d8b87b25 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/IterativeLinearSolvers @@ -0,0 +1,48 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ITERATIVELINEARSOLVERS_MODULE_H +#define EIGEN_ITERATIVELINEARSOLVERS_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup IterativeLinearSolvers_Module IterativeLinearSolvers module + * + * This module currently provides iterative methods to solve problems of the form \c A \c x = \c b, where \c A is a squared matrix, usually very large and sparse. + * Those solvers are accessible via the following classes: + * - ConjugateGradient for selfadjoint (hermitian) matrices, + * - LeastSquaresConjugateGradient for rectangular least-square problems, + * - BiCGSTAB for general square matrices. + * + * These iterative solvers are associated with some preconditioners: + * - IdentityPreconditioner - not really useful + * - DiagonalPreconditioner - also called Jacobi preconditioner, work very well on diagonal dominant matrices. + * - IncompleteLUT - incomplete LU factorization with dual thresholding + * + * Such problems can also be solved using the direct sparse decomposition modules: SparseCholesky, CholmodSupport, UmfPackSupport, SuperLUSupport. + * + \code + #include + \endcode + */ + +#include "src/IterativeLinearSolvers/SolveWithGuess.h" +#include "src/IterativeLinearSolvers/IterativeSolverBase.h" +#include "src/IterativeLinearSolvers/BasicPreconditioners.h" +#include "src/IterativeLinearSolvers/ConjugateGradient.h" +#include "src/IterativeLinearSolvers/LeastSquareConjugateGradient.h" +#include "src/IterativeLinearSolvers/BiCGSTAB.h" +#include "src/IterativeLinearSolvers/IncompleteLUT.h" +#include "src/IterativeLinearSolvers/IncompleteCholesky.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ITERATIVELINEARSOLVERS_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Jacobi b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Jacobi new file mode 100644 index 0000000000000000000000000000000000000000..17c1d785a16280bb93e8d87e50bd62c0ea6c340d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Jacobi @@ -0,0 +1,33 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_JACOBI_MODULE_H +#define EIGEN_JACOBI_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup Jacobi_Module Jacobi module + * This module provides Jacobi and Givens rotations. + * + * \code + * #include + * \endcode + * + * In addition to listed classes, it defines the two following MatrixBase methods to apply a Jacobi or Givens rotation: + * - MatrixBase::applyOnTheLeft() + * - MatrixBase::applyOnTheRight(). + */ + +#include "src/Jacobi/Jacobi.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_JACOBI_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/LU b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/LU new file mode 100644 index 0000000000000000000000000000000000000000..6418a86e1925bf1326e5099fe8babdf32be8a449 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/LU @@ -0,0 +1,50 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LU_MODULE_H +#define EIGEN_LU_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup LU_Module LU module + * This module includes %LU decomposition and related notions such as matrix inversion and determinant. + * This module defines the following MatrixBase methods: + * - MatrixBase::inverse() + * - MatrixBase::determinant() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/Kernel.h" +#include "src/misc/Image.h" +#include "src/LU/FullPivLU.h" +#include "src/LU/PartialPivLU.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/LU/PartialPivLU_LAPACKE.h" +#endif +#include "src/LU/Determinant.h" +#include "src/LU/InverseImpl.h" + +// Use the SSE optimized version whenever possible. At the moment the +// SSE version doesn't compile when AVX is enabled +#if defined EIGEN_VECTORIZE_SSE && !defined EIGEN_VECTORIZE_AVX + #include "src/LU/arch/Inverse_SSE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_LU_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/MetisSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/MetisSupport new file mode 100644 index 0000000000000000000000000000000000000000..85c41bf340013e4583e505c496dfb567dc6ae80a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/MetisSupport @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_METISSUPPORT_MODULE_H +#define EIGEN_METISSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +} + + +/** \ingroup Support_modules + * \defgroup MetisSupport_Module MetisSupport module + * + * \code + * #include + * \endcode + * This module defines an interface to the METIS reordering package (http://glaros.dtc.umn.edu/gkhome/views/metis). + * It can be used just as any other built-in method as explained in \link OrderingMethods_Module here. \endlink + */ + + +#include "src/MetisSupport/MetisSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_METISSUPPORT_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/OrderingMethods b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/OrderingMethods new file mode 100644 index 0000000000000000000000000000000000000000..d8ea36193666f87c8cec6557f575a5b34654bef6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/OrderingMethods @@ -0,0 +1,73 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ORDERINGMETHODS_MODULE_H +#define EIGEN_ORDERINGMETHODS_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup OrderingMethods_Module OrderingMethods module + * + * This module is currently for internal use only + * + * It defines various built-in and external ordering methods for sparse matrices. + * They are typically used to reduce the number of elements during + * the sparse matrix decomposition (LLT, LU, QR). + * Precisely, in a preprocessing step, a permutation matrix P is computed using + * those ordering methods and applied to the columns of the matrix. + * Using for instance the sparse Cholesky decomposition, it is expected that + * the nonzeros elements in LLT(A*P) will be much smaller than that in LLT(A). + * + * + * Usage : + * \code + * #include + * \endcode + * + * A simple usage is as a template parameter in the sparse decomposition classes : + * + * \code + * SparseLU > solver; + * \endcode + * + * \code + * SparseQR > solver; + * \endcode + * + * It is possible as well to call directly a particular ordering method for your own purpose, + * \code + * AMDOrdering ordering; + * PermutationMatrix perm; + * SparseMatrix A; + * //Fill the matrix ... + * + * ordering(A, perm); // Call AMD + * \endcode + * + * \note Some of these methods (like AMD or METIS), need the sparsity pattern + * of the input matrix to be symmetric. When the matrix is structurally unsymmetric, + * Eigen computes internally the pattern of \f$A^T*A\f$ before calling the method. + * If your matrix is already symmetric (at leat in structure), you can avoid that + * by calling the method with a SelfAdjointView type. + * + * \code + * // Call the ordering on the pattern of the lower triangular matrix A + * ordering(A.selfadjointView(), perm); + * \endcode + */ + +#ifndef EIGEN_MPL2_ONLY +#include "src/OrderingMethods/Amd.h" +#endif + +#include "src/OrderingMethods/Ordering.h" +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_ORDERINGMETHODS_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PaStiXSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PaStiXSupport new file mode 100644 index 0000000000000000000000000000000000000000..de3a63b4d1264e6fa8c15582b702c13ddf8e195d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PaStiXSupport @@ -0,0 +1,48 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PASTIXSUPPORT_MODULE_H +#define EIGEN_PASTIXSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +#include +} + +#ifdef complex +#undef complex +#endif + +/** \ingroup Support_modules + * \defgroup PaStiXSupport_Module PaStiXSupport module + * + * This module provides an interface to the PaSTiX library. + * PaSTiX is a general \b supernodal, \b parallel and \b opensource sparse solver. + * It provides the two following main factorization classes: + * - class PastixLLT : a supernodal, parallel LLt Cholesky factorization. + * - class PastixLDLT: a supernodal, parallel LDLt Cholesky factorization. + * - class PastixLU : a supernodal, parallel LU factorization (optimized for a symmetric pattern). + * + * \code + * #include + * \endcode + * + * In order to use this module, the PaSTiX headers must be accessible from the include paths, and your binary must be linked to the PaSTiX library and its dependencies. + * The dependencies depend on how PaSTiX has been compiled. + * For a cmake based project, you can use our FindPaSTiX.cmake module to help you in this task. + * + */ + +#include "src/PaStiXSupport/PaStiXSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_PASTIXSUPPORT_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PardisoSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PardisoSupport new file mode 100644 index 0000000000000000000000000000000000000000..340edf51fe2d678294bef93f4cc413a95af0075d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/PardisoSupport @@ -0,0 +1,35 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PARDISOSUPPORT_MODULE_H +#define EIGEN_PARDISOSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include + +/** \ingroup Support_modules + * \defgroup PardisoSupport_Module PardisoSupport module + * + * This module brings support for the Intel(R) MKL PARDISO direct sparse solvers. + * + * \code + * #include + * \endcode + * + * In order to use this module, the MKL headers must be accessible from the include paths, and your binary must be linked to the MKL library and its dependencies. + * See this \ref TopicUsingIntelMKL "page" for more information on MKL-Eigen integration. + * + */ + +#include "src/PardisoSupport/PardisoSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_PARDISOSUPPORT_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QR b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QR new file mode 100644 index 0000000000000000000000000000000000000000..c7e91446994959a9b43f3a25dc26bf6fcb8bd806 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QR @@ -0,0 +1,51 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_QR_MODULE_H +#define EIGEN_QR_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "Cholesky" +#include "Jacobi" +#include "Householder" + +/** \defgroup QR_Module QR module + * + * + * + * This module provides various QR decompositions + * This module also provides some MatrixBase methods, including: + * - MatrixBase::householderQr() + * - MatrixBase::colPivHouseholderQr() + * - MatrixBase::fullPivHouseholderQr() + * + * \code + * #include + * \endcode + */ + +#include "src/QR/HouseholderQR.h" +#include "src/QR/FullPivHouseholderQR.h" +#include "src/QR/ColPivHouseholderQR.h" +#include "src/QR/CompleteOrthogonalDecomposition.h" +#ifdef EIGEN_USE_LAPACKE +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/QR/HouseholderQR_LAPACKE.h" +#include "src/QR/ColPivHouseholderQR_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_QR_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QtAlignedMalloc b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QtAlignedMalloc new file mode 100644 index 0000000000000000000000000000000000000000..4f07df02ae90fe15921ab6b6896c25c2dd530160 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/QtAlignedMalloc @@ -0,0 +1,40 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_QTMALLOC_MODULE_H +#define EIGEN_QTMALLOC_MODULE_H + +#include "Core" + +#if (!EIGEN_MALLOC_ALREADY_ALIGNED) + +#include "src/Core/util/DisableStupidWarnings.h" + +void *qMalloc(std::size_t size) +{ + return Eigen::internal::aligned_malloc(size); +} + +void qFree(void *ptr) +{ + Eigen::internal::aligned_free(ptr); +} + +void *qRealloc(void *ptr, std::size_t size) +{ + void* newPtr = Eigen::internal::aligned_malloc(size); + std::memcpy(newPtr, ptr, size); + Eigen::internal::aligned_free(ptr); + return newPtr; +} + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif + +#endif // EIGEN_QTMALLOC_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SPQRSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SPQRSupport new file mode 100644 index 0000000000000000000000000000000000000000..f70390c17661f10d87eafd69784af67368247dae --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SPQRSupport @@ -0,0 +1,34 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPQRSUPPORT_MODULE_H +#define EIGEN_SPQRSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include "SuiteSparseQR.hpp" + +/** \ingroup Support_modules + * \defgroup SPQRSupport_Module SuiteSparseQR module + * + * This module provides an interface to the SPQR library, which is part of the suitesparse package. + * + * \code + * #include + * \endcode + * + * In order to use this module, the SPQR headers must be accessible from the include paths, and your binary must be linked to the SPQR library and its dependencies (Cholmod, AMD, COLAMD,...). + * For a cmake based project, you can use our FindSPQR.cmake and FindCholmod.Cmake modules + * + */ + +#include "src/CholmodSupport/CholmodSupport.h" +#include "src/SPQRSupport/SuiteSparseQRSupport.h" + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SVD b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SVD new file mode 100644 index 0000000000000000000000000000000000000000..5d0e75f7f755c382ab8e6b5c606565f9ed43dd87 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SVD @@ -0,0 +1,51 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SVD_MODULE_H +#define EIGEN_SVD_MODULE_H + +#include "QR" +#include "Householder" +#include "Jacobi" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup SVD_Module SVD module + * + * + * + * This module provides SVD decomposition for matrices (both real and complex). + * Two decomposition algorithms are provided: + * - JacobiSVD implementing two-sided Jacobi iterations is numerically very accurate, fast for small matrices, but very slow for larger ones. + * - BDCSVD implementing a recursive divide & conquer strategy on top of an upper-bidiagonalization which remains fast for large problems. + * These decompositions are accessible via the respective classes and following MatrixBase methods: + * - MatrixBase::jacobiSvd() + * - MatrixBase::bdcSvd() + * + * \code + * #include + * \endcode + */ + +#include "src/misc/RealSvd2x2.h" +#include "src/SVD/UpperBidiagonalization.h" +#include "src/SVD/SVDBase.h" +#include "src/SVD/JacobiSVD.h" +#include "src/SVD/BDCSVD.h" +#if defined(EIGEN_USE_LAPACKE) && !defined(EIGEN_USE_LAPACKE_STRICT) +#ifdef EIGEN_USE_MKL +#include "mkl_lapacke.h" +#else +#include "src/misc/lapacke.h" +#endif +#include "src/SVD/JacobiSVD_LAPACKE.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SVD_MODULE_H +/* vim: set filetype=cpp et sw=2 ts=2 ai: */ diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Sparse b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Sparse new file mode 100644 index 0000000000000000000000000000000000000000..136e681a1f66cc70d61285ef7eaa64399162581f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/Sparse @@ -0,0 +1,36 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSE_MODULE_H +#define EIGEN_SPARSE_MODULE_H + +/** \defgroup Sparse_Module Sparse meta-module + * + * Meta-module including all related modules: + * - \ref SparseCore_Module + * - \ref OrderingMethods_Module + * - \ref SparseCholesky_Module + * - \ref SparseLU_Module + * - \ref SparseQR_Module + * - \ref IterativeLinearSolvers_Module + * + \code + #include + \endcode + */ + +#include "SparseCore" +#include "OrderingMethods" +#ifndef EIGEN_MPL2_ONLY +#include "SparseCholesky" +#endif +#include "SparseLU" +#include "SparseQR" +#include "IterativeLinearSolvers" + +#endif // EIGEN_SPARSE_MODULE_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCholesky b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCholesky new file mode 100644 index 0000000000000000000000000000000000000000..b6a320c4027b4a3c7f21b7b9f00bcf1e3aeb24ed --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCholesky @@ -0,0 +1,45 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2013 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSECHOLESKY_MODULE_H +#define EIGEN_SPARSECHOLESKY_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" + +#include "src/Core/util/DisableStupidWarnings.h" + +/** + * \defgroup SparseCholesky_Module SparseCholesky module + * + * This module currently provides two variants of the direct sparse Cholesky decomposition for selfadjoint (hermitian) matrices. + * Those decompositions are accessible via the following classes: + * - SimplicialLLt, + * - SimplicialLDLt + * + * Such problems can also be solved using the ConjugateGradient solver from the IterativeLinearSolvers module. + * + * \code + * #include + * \endcode + */ + +#ifdef EIGEN_MPL2_ONLY +#error The SparseCholesky module has nothing to offer in MPL2 only mode +#endif + +#include "src/SparseCholesky/SimplicialCholesky.h" + +#ifndef EIGEN_MPL2_ONLY +#include "src/SparseCholesky/SimplicialCholesky_impl.h" +#endif + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSECHOLESKY_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCore b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCore new file mode 100644 index 0000000000000000000000000000000000000000..76966c4c4cb12da2ad59e0fdd7672b052baab6e3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseCore @@ -0,0 +1,69 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSECORE_MODULE_H +#define EIGEN_SPARSECORE_MODULE_H + +#include "Core" + +#include "src/Core/util/DisableStupidWarnings.h" + +#include +#include +#include +#include +#include + +/** + * \defgroup SparseCore_Module SparseCore module + * + * This module provides a sparse matrix representation, and basic associated matrix manipulations + * and operations. + * + * See the \ref TutorialSparse "Sparse tutorial" + * + * \code + * #include + * \endcode + * + * This module depends on: Core. + */ + +#include "src/SparseCore/SparseUtil.h" +#include "src/SparseCore/SparseMatrixBase.h" +#include "src/SparseCore/SparseAssign.h" +#include "src/SparseCore/CompressedStorage.h" +#include "src/SparseCore/AmbiVector.h" +#include "src/SparseCore/SparseCompressedBase.h" +#include "src/SparseCore/SparseMatrix.h" +#include "src/SparseCore/SparseMap.h" +#include "src/SparseCore/MappedSparseMatrix.h" +#include "src/SparseCore/SparseVector.h" +#include "src/SparseCore/SparseRef.h" +#include "src/SparseCore/SparseCwiseUnaryOp.h" +#include "src/SparseCore/SparseCwiseBinaryOp.h" +#include "src/SparseCore/SparseTranspose.h" +#include "src/SparseCore/SparseBlock.h" +#include "src/SparseCore/SparseDot.h" +#include "src/SparseCore/SparseRedux.h" +#include "src/SparseCore/SparseView.h" +#include "src/SparseCore/SparseDiagonalProduct.h" +#include "src/SparseCore/ConservativeSparseSparseProduct.h" +#include "src/SparseCore/SparseSparseProductWithPruning.h" +#include "src/SparseCore/SparseProduct.h" +#include "src/SparseCore/SparseDenseProduct.h" +#include "src/SparseCore/SparseSelfAdjointView.h" +#include "src/SparseCore/SparseTriangularView.h" +#include "src/SparseCore/TriangularSolver.h" +#include "src/SparseCore/SparsePermutation.h" +#include "src/SparseCore/SparseFuzzy.h" +#include "src/SparseCore/SparseSolverBase.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SPARSECORE_MODULE_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseLU b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseLU new file mode 100644 index 0000000000000000000000000000000000000000..38b38b531d1c87cb4d5b8f1819687d8d4dd335eb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseLU @@ -0,0 +1,46 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSELU_MODULE_H +#define EIGEN_SPARSELU_MODULE_H + +#include "SparseCore" + +/** + * \defgroup SparseLU_Module SparseLU module + * This module defines a supernodal factorization of general sparse matrices. + * The code is fully optimized for supernode-panel updates with specialized kernels. + * Please, see the documentation of the SparseLU class for more details. + */ + +// Ordering interface +#include "OrderingMethods" + +#include "src/SparseLU/SparseLU_gemm_kernel.h" + +#include "src/SparseLU/SparseLU_Structs.h" +#include "src/SparseLU/SparseLU_SupernodalMatrix.h" +#include "src/SparseLU/SparseLUImpl.h" +#include "src/SparseCore/SparseColEtree.h" +#include "src/SparseLU/SparseLU_Memory.h" +#include "src/SparseLU/SparseLU_heap_relax_snode.h" +#include "src/SparseLU/SparseLU_relax_snode.h" +#include "src/SparseLU/SparseLU_pivotL.h" +#include "src/SparseLU/SparseLU_panel_dfs.h" +#include "src/SparseLU/SparseLU_kernel_bmod.h" +#include "src/SparseLU/SparseLU_panel_bmod.h" +#include "src/SparseLU/SparseLU_column_dfs.h" +#include "src/SparseLU/SparseLU_column_bmod.h" +#include "src/SparseLU/SparseLU_copy_to_ucol.h" +#include "src/SparseLU/SparseLU_pruneL.h" +#include "src/SparseLU/SparseLU_Utils.h" +#include "src/SparseLU/SparseLU.h" + +#endif // EIGEN_SPARSELU_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseQR b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseQR new file mode 100644 index 0000000000000000000000000000000000000000..a6f3b7f7d75c4e0c1631d54c04a854b5c607a3e5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SparseQR @@ -0,0 +1,37 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SPARSEQR_MODULE_H +#define EIGEN_SPARSEQR_MODULE_H + +#include "SparseCore" +#include "OrderingMethods" +#include "src/Core/util/DisableStupidWarnings.h" + +/** \defgroup SparseQR_Module SparseQR module + * \brief Provides QR decomposition for sparse matrices + * + * This module provides a simplicial version of the left-looking Sparse QR decomposition. + * The columns of the input matrix should be reordered to limit the fill-in during the + * decomposition. Built-in methods (COLAMD, AMD) or external methods (METIS) can be used to this end. + * See the \link OrderingMethods_Module OrderingMethods\endlink module for the list + * of built-in and external ordering methods. + * + * \code + * #include + * \endcode + * + * + */ + +#include "OrderingMethods" +#include "src/SparseCore/SparseColEtree.h" +#include "src/SparseQR/SparseQR.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdDeque b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdDeque new file mode 100644 index 0000000000000000000000000000000000000000..bc68397be259fa9666c2a59f4bdb1b9dd8ab0ce6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdDeque @@ -0,0 +1,27 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDDEQUE_MODULE_H +#define EIGEN_STDDEQUE_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_DEQUE_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdDeque.h" + +#endif + +#endif // EIGEN_STDDEQUE_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdList b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdList new file mode 100644 index 0000000000000000000000000000000000000000..4c6262c08cc26bcc70d4e21e83027b9533a7e36c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdList @@ -0,0 +1,26 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDLIST_MODULE_H +#define EIGEN_STDLIST_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_LIST_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdList.h" + +#endif + +#endif // EIGEN_STDLIST_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdVector b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdVector new file mode 100644 index 0000000000000000000000000000000000000000..0c4697ad5bed5868d793ba7d94bb9dc3fb9bed4c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/StdVector @@ -0,0 +1,27 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2009 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_STDVECTOR_MODULE_H +#define EIGEN_STDVECTOR_MODULE_H + +#include "Core" +#include + +#if EIGEN_COMP_MSVC && EIGEN_OS_WIN64 && (EIGEN_MAX_STATIC_ALIGN_BYTES<=16) /* MSVC auto aligns up to 16 bytes in 64 bit builds */ + +#define EIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(...) + +#else + +#include "src/StlSupport/StdVector.h" + +#endif + +#endif // EIGEN_STDVECTOR_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SuperLUSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SuperLUSupport new file mode 100644 index 0000000000000000000000000000000000000000..59312a82db0703389e21ae6e1b703b261802eadf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/SuperLUSupport @@ -0,0 +1,64 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SUPERLUSUPPORT_MODULE_H +#define EIGEN_SUPERLUSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +#ifdef EMPTY +#define EIGEN_EMPTY_WAS_ALREADY_DEFINED +#endif + +typedef int int_t; +#include +#include +#include + +// slu_util.h defines a preprocessor token named EMPTY which is really polluting, +// so we remove it in favor of a SUPERLU_EMPTY token. +// If EMPTY was already defined then we don't undef it. + +#if defined(EIGEN_EMPTY_WAS_ALREADY_DEFINED) +# undef EIGEN_EMPTY_WAS_ALREADY_DEFINED +#elif defined(EMPTY) +# undef EMPTY +#endif + +#define SUPERLU_EMPTY (-1) + +namespace Eigen { struct SluMatrix; } + +/** \ingroup Support_modules + * \defgroup SuperLUSupport_Module SuperLUSupport module + * + * This module provides an interface to the SuperLU library. + * It provides the following factorization class: + * - class SuperLU: a supernodal sequential LU factorization. + * - class SuperILU: a supernodal sequential incomplete LU factorization (to be used as a preconditioner for iterative methods). + * + * \warning This wrapper requires at least versions 4.0 of SuperLU. The 3.x versions are not supported. + * + * \warning When including this module, you have to use SUPERLU_EMPTY instead of EMPTY which is no longer defined because it is too polluting. + * + * \code + * #include + * \endcode + * + * In order to use this module, the superlu headers must be accessible from the include paths, and your binary must be linked to the superlu library and its dependencies. + * The dependencies depend on how superlu has been compiled. + * For a cmake based project, you can use our FindSuperLU.cmake module to help you in this task. + * + */ + +#include "src/SuperLUSupport/SuperLUSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_SUPERLUSUPPORT_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/UmfPackSupport b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/UmfPackSupport new file mode 100644 index 0000000000000000000000000000000000000000..00eec80875fcb209de0f6f746d0f4d299cd2ce8e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/UmfPackSupport @@ -0,0 +1,40 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_UMFPACKSUPPORT_MODULE_H +#define EIGEN_UMFPACKSUPPORT_MODULE_H + +#include "SparseCore" + +#include "src/Core/util/DisableStupidWarnings.h" + +extern "C" { +#include +} + +/** \ingroup Support_modules + * \defgroup UmfPackSupport_Module UmfPackSupport module + * + * This module provides an interface to the UmfPack library which is part of the suitesparse package. + * It provides the following factorization class: + * - class UmfPackLU: a multifrontal sequential LU factorization. + * + * \code + * #include + * \endcode + * + * In order to use this module, the umfpack headers must be accessible from the include paths, and your binary must be linked to the umfpack library and its dependencies. + * The dependencies depend on how umfpack has been compiled. + * For a cmake based project, you can use our FindUmfPack.cmake module to help you in this task. + * + */ + +#include "src/UmfPackSupport/UmfPackSupport.h" + +#include "src/Core/util/ReenableStupidWarnings.h" + +#endif // EIGEN_UMFPACKSUPPORT_MODULE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LDLT.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LDLT.h new file mode 100644 index 0000000000000000000000000000000000000000..15ccf24f1446c3d4fd33379c1c46dda03b1fd58a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LDLT.h @@ -0,0 +1,673 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2011 Gael Guennebaud +// Copyright (C) 2009 Keir Mierle +// Copyright (C) 2009 Benoit Jacob +// Copyright (C) 2011 Timothy E. Holy +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LDLT_H +#define EIGEN_LDLT_H + +namespace Eigen { + +namespace internal { + template struct LDLT_Traits; + + // PositiveSemiDef means positive semi-definite and non-zero; same for NegativeSemiDef + enum SignMatrix { PositiveSemiDef, NegativeSemiDef, ZeroSign, Indefinite }; +} + +/** \ingroup Cholesky_Module + * + * \class LDLT + * + * \brief Robust Cholesky decomposition of a matrix with pivoting + * + * \tparam _MatrixType the type of the matrix of which to compute the LDL^T Cholesky decomposition + * \tparam _UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper. + * The other triangular part won't be read. + * + * Perform a robust Cholesky decomposition of a positive semidefinite or negative semidefinite + * matrix \f$ A \f$ such that \f$ A = P^TLDL^*P \f$, where P is a permutation matrix, L + * is lower triangular with a unit diagonal and D is a diagonal matrix. + * + * The decomposition uses pivoting to ensure stability, so that L will have + * zeros in the bottom right rank(A) - n submatrix. Avoiding the square root + * on D also stabilizes the computation. + * + * Remember that Cholesky decompositions are not rank-revealing. Also, do not use a Cholesky + * decomposition to determine whether a system of equations has a solution. + * + * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. + * + * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt(), class LLT + */ +template class LDLT +{ + public: + typedef _MatrixType MatrixType; + enum { + RowsAtCompileTime = MatrixType::RowsAtCompileTime, + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, + UpLo = _UpLo + }; + typedef typename MatrixType::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 + typedef typename MatrixType::StorageIndex StorageIndex; + typedef Matrix TmpMatrixType; + + typedef Transpositions TranspositionType; + typedef PermutationMatrix PermutationType; + + typedef internal::LDLT_Traits Traits; + + /** \brief Default Constructor. + * + * The default constructor is useful in cases in which the user intends to + * perform decompositions via LDLT::compute(const MatrixType&). + */ + LDLT() + : m_matrix(), + m_transpositions(), + m_sign(internal::ZeroSign), + m_isInitialized(false) + {} + + /** \brief Default Constructor with memory preallocation + * + * Like the default constructor but with preallocation of the internal data + * according to the specified problem \a size. + * \sa LDLT() + */ + explicit LDLT(Index size) + : m_matrix(size, size), + m_transpositions(size), + m_temporary(size), + m_sign(internal::ZeroSign), + m_isInitialized(false) + {} + + /** \brief Constructor with decomposition + * + * This calculates the decomposition for the input \a matrix. + * + * \sa LDLT(Index size) + */ + template + explicit LDLT(const EigenBase& matrix) + : m_matrix(matrix.rows(), matrix.cols()), + m_transpositions(matrix.rows()), + m_temporary(matrix.rows()), + m_sign(internal::ZeroSign), + m_isInitialized(false) + { + compute(matrix.derived()); + } + + /** \brief Constructs a LDLT factorization from a given matrix + * + * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when \c MatrixType is a Eigen::Ref. + * + * \sa LDLT(const EigenBase&) + */ + template + explicit LDLT(EigenBase& matrix) + : m_matrix(matrix.derived()), + m_transpositions(matrix.rows()), + m_temporary(matrix.rows()), + m_sign(internal::ZeroSign), + m_isInitialized(false) + { + compute(matrix.derived()); + } + + /** Clear any existing decomposition + * \sa rankUpdate(w,sigma) + */ + void setZero() + { + m_isInitialized = false; + } + + /** \returns a view of the upper triangular matrix U */ + inline typename Traits::MatrixU matrixU() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return Traits::getU(m_matrix); + } + + /** \returns a view of the lower triangular matrix L */ + inline typename Traits::MatrixL matrixL() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return Traits::getL(m_matrix); + } + + /** \returns the permutation matrix P as a transposition sequence. + */ + inline const TranspositionType& transpositionsP() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_transpositions; + } + + /** \returns the coefficients of the diagonal matrix D */ + inline Diagonal vectorD() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_matrix.diagonal(); + } + + /** \returns true if the matrix is positive (semidefinite) */ + inline bool isPositive() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_sign == internal::PositiveSemiDef || m_sign == internal::ZeroSign; + } + + /** \returns true if the matrix is negative (semidefinite) */ + inline bool isNegative(void) const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_sign == internal::NegativeSemiDef || m_sign == internal::ZeroSign; + } + + /** \returns a solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * This function also supports in-place solves using the syntax x = decompositionObject.solve(x) . + * + * \note_about_checking_solutions + * + * More precisely, this method solves \f$ A x = b \f$ using the decomposition \f$ A = P^T L D L^* P \f$ + * by solving the systems \f$ P^T y_1 = b \f$, \f$ L y_2 = y_1 \f$, \f$ D y_3 = y_2 \f$, + * \f$ L^* y_4 = y_3 \f$ and \f$ P x = y_4 \f$ in succession. If the matrix \f$ A \f$ is singular, then + * \f$ D \f$ will also be singular (all the other matrices are invertible). In that case, the + * least-square solution of \f$ D y_3 = y_2 \f$ is computed. This does not mean that this function + * computes the least-square solution of \f$ A x = b \f$ is \f$ A \f$ is singular. + * + * \sa MatrixBase::ldlt(), SelfAdjointView::ldlt() + */ + template + inline const Solve + solve(const MatrixBase& b) const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + eigen_assert(m_matrix.rows()==b.rows() + && "LDLT::solve(): invalid number of rows of the right hand side matrix b"); + return Solve(*this, b.derived()); + } + + template + bool solveInPlace(MatrixBase &bAndX) const; + + template + LDLT& compute(const EigenBase& matrix); + + /** \returns an estimate of the reciprocal condition number of the matrix of + * which \c *this is the LDLT decomposition. + */ + RealScalar rcond() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return internal::rcond_estimate_helper(m_l1_norm, *this); + } + + template + LDLT& rankUpdate(const MatrixBase& w, const RealScalar& alpha=1); + + /** \returns the internal LDLT decomposition matrix + * + * TODO: document the storage layout + */ + inline const MatrixType& matrixLDLT() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_matrix; + } + + MatrixType reconstructedMatrix() const; + + /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix is self-adjoint. + * + * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: + * \code x = decomposition.adjoint().solve(b) \endcode + */ + const LDLT& adjoint() const { return *this; }; + + inline Index rows() const { return m_matrix.rows(); } + inline Index cols() const { return m_matrix.cols(); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was succesful, + * \c NumericalIssue if the factorization failed because of a zero pivot. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "LDLT is not initialized."); + return m_info; + } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC + void _solve_impl(const RhsType &rhs, DstType &dst) const; + #endif + + protected: + + static void check_template_parameters() + { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar); + } + + /** \internal + * Used to compute and store the Cholesky decomposition A = L D L^* = U^* D U. + * The strict upper part is used during the decomposition, the strict lower + * part correspond to the coefficients of L (its diagonal is equal to 1 and + * is not stored), and the diagonal entries correspond to D. + */ + MatrixType m_matrix; + RealScalar m_l1_norm; + TranspositionType m_transpositions; + TmpMatrixType m_temporary; + internal::SignMatrix m_sign; + bool m_isInitialized; + ComputationInfo m_info; +}; + +namespace internal { + +template struct ldlt_inplace; + +template<> struct ldlt_inplace +{ + template + static bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign) + { + using std::abs; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename TranspositionType::StorageIndex IndexType; + eigen_assert(mat.rows()==mat.cols()); + const Index size = mat.rows(); + bool found_zero_pivot = false; + bool ret = true; + + if (size <= 1) + { + transpositions.setIdentity(); + if(size==0) sign = ZeroSign; + else if (numext::real(mat.coeff(0,0)) > static_cast(0) ) sign = PositiveSemiDef; + else if (numext::real(mat.coeff(0,0)) < static_cast(0)) sign = NegativeSemiDef; + else sign = ZeroSign; + return true; + } + + for (Index k = 0; k < size; ++k) + { + // Find largest diagonal element + Index index_of_biggest_in_corner; + mat.diagonal().tail(size-k).cwiseAbs().maxCoeff(&index_of_biggest_in_corner); + index_of_biggest_in_corner += k; + + transpositions.coeffRef(k) = IndexType(index_of_biggest_in_corner); + if(k != index_of_biggest_in_corner) + { + // apply the transposition while taking care to consider only + // the lower triangular part + Index s = size-index_of_biggest_in_corner-1; // trailing size after the biggest element + mat.row(k).head(k).swap(mat.row(index_of_biggest_in_corner).head(k)); + mat.col(k).tail(s).swap(mat.col(index_of_biggest_in_corner).tail(s)); + std::swap(mat.coeffRef(k,k),mat.coeffRef(index_of_biggest_in_corner,index_of_biggest_in_corner)); + for(Index i=k+1;i::IsComplex) + mat.coeffRef(index_of_biggest_in_corner,k) = numext::conj(mat.coeff(index_of_biggest_in_corner,k)); + } + + // partition the matrix: + // A00 | - | - + // lu = A10 | A11 | - + // A20 | A21 | A22 + Index rs = size - k - 1; + Block A21(mat,k+1,k,rs,1); + Block A10(mat,k,0,1,k); + Block A20(mat,k+1,0,rs,k); + + if(k>0) + { + temp.head(k) = mat.diagonal().real().head(k).asDiagonal() * A10.adjoint(); + mat.coeffRef(k,k) -= (A10 * temp.head(k)).value(); + if(rs>0) + A21.noalias() -= A20 * temp.head(k); + } + + // In some previous versions of Eigen (e.g., 3.2.1), the scaling was omitted if the pivot + // was smaller than the cutoff value. However, since LDLT is not rank-revealing + // we should only make sure that we do not introduce INF or NaN values. + // Remark that LAPACK also uses 0 as the cutoff value. + RealScalar realAkk = numext::real(mat.coeffRef(k,k)); + bool pivot_is_valid = (abs(realAkk) > RealScalar(0)); + + if(k==0 && !pivot_is_valid) + { + // The entire diagonal is zero, there is nothing more to do + // except filling the transpositions, and checking whether the matrix is zero. + sign = ZeroSign; + for(Index j = 0; j0) && pivot_is_valid) + A21 /= realAkk; + else if(rs>0) + ret = ret && (A21.array()==Scalar(0)).all(); + + if(found_zero_pivot && pivot_is_valid) ret = false; // factorization failed + else if(!pivot_is_valid) found_zero_pivot = true; + + if (sign == PositiveSemiDef) { + if (realAkk < static_cast(0)) sign = Indefinite; + } else if (sign == NegativeSemiDef) { + if (realAkk > static_cast(0)) sign = Indefinite; + } else if (sign == ZeroSign) { + if (realAkk > static_cast(0)) sign = PositiveSemiDef; + else if (realAkk < static_cast(0)) sign = NegativeSemiDef; + } + } + + return ret; + } + + // Reference for the algorithm: Davis and Hager, "Multiple Rank + // Modifications of a Sparse Cholesky Factorization" (Algorithm 1) + // Trivial rearrangements of their computations (Timothy E. Holy) + // allow their algorithm to work for rank-1 updates even if the + // original matrix is not of full rank. + // Here only rank-1 updates are implemented, to reduce the + // requirement for intermediate storage and improve accuracy + template + static bool updateInPlace(MatrixType& mat, MatrixBase& w, const typename MatrixType::RealScalar& sigma=1) + { + using numext::isfinite; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + + const Index size = mat.rows(); + eigen_assert(mat.cols() == size && w.size()==size); + + RealScalar alpha = 1; + + // Apply the update + for (Index j = 0; j < size; j++) + { + // Check for termination due to an original decomposition of low-rank + if (!(isfinite)(alpha)) + break; + + // Update the diagonal terms + RealScalar dj = numext::real(mat.coeff(j,j)); + Scalar wj = w.coeff(j); + RealScalar swj2 = sigma*numext::abs2(wj); + RealScalar gamma = dj*alpha + swj2; + + mat.coeffRef(j,j) += swj2/alpha; + alpha += swj2/dj; + + + // Update the terms of L + Index rs = size-j-1; + w.tail(rs) -= wj * mat.col(j).tail(rs); + if(gamma != 0) + mat.col(j).tail(rs) += (sigma*numext::conj(wj)/gamma)*w.tail(rs); + } + return true; + } + + template + static bool update(MatrixType& mat, const TranspositionType& transpositions, Workspace& tmp, const WType& w, const typename MatrixType::RealScalar& sigma=1) + { + // Apply the permutation to the input w + tmp = transpositions * w; + + return ldlt_inplace::updateInPlace(mat,tmp,sigma); + } +}; + +template<> struct ldlt_inplace +{ + template + static EIGEN_STRONG_INLINE bool unblocked(MatrixType& mat, TranspositionType& transpositions, Workspace& temp, SignMatrix& sign) + { + Transpose matt(mat); + return ldlt_inplace::unblocked(matt, transpositions, temp, sign); + } + + template + static EIGEN_STRONG_INLINE bool update(MatrixType& mat, TranspositionType& transpositions, Workspace& tmp, WType& w, const typename MatrixType::RealScalar& sigma=1) + { + Transpose matt(mat); + return ldlt_inplace::update(matt, transpositions, tmp, w.conjugate(), sigma); + } +}; + +template struct LDLT_Traits +{ + typedef const TriangularView MatrixL; + typedef const TriangularView MatrixU; + static inline MatrixL getL(const MatrixType& m) { return MatrixL(m); } + static inline MatrixU getU(const MatrixType& m) { return MatrixU(m.adjoint()); } +}; + +template struct LDLT_Traits +{ + typedef const TriangularView MatrixL; + typedef const TriangularView MatrixU; + static inline MatrixL getL(const MatrixType& m) { return MatrixL(m.adjoint()); } + static inline MatrixU getU(const MatrixType& m) { return MatrixU(m); } +}; + +} // end namespace internal + +/** Compute / recompute the LDLT decomposition A = L D L^* = U^* D U of \a matrix + */ +template +template +LDLT& LDLT::compute(const EigenBase& a) +{ + check_template_parameters(); + + eigen_assert(a.rows()==a.cols()); + const Index size = a.rows(); + + m_matrix = a.derived(); + + // Compute matrix L1 norm = max abs column sum. + m_l1_norm = RealScalar(0); + // TODO move this code to SelfAdjointView + for (Index col = 0; col < size; ++col) { + RealScalar abs_col_sum; + if (_UpLo == Lower) + abs_col_sum = m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>(); + else + abs_col_sum = m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); + if (abs_col_sum > m_l1_norm) + m_l1_norm = abs_col_sum; + } + + m_transpositions.resize(size); + m_isInitialized = false; + m_temporary.resize(size); + m_sign = internal::ZeroSign; + + m_info = internal::ldlt_inplace::unblocked(m_matrix, m_transpositions, m_temporary, m_sign) ? Success : NumericalIssue; + + m_isInitialized = true; + return *this; +} + +/** Update the LDLT decomposition: given A = L D L^T, efficiently compute the decomposition of A + sigma w w^T. + * \param w a vector to be incorporated into the decomposition. + * \param sigma a scalar, +1 for updates and -1 for "downdates," which correspond to removing previously-added column vectors. Optional; default value is +1. + * \sa setZero() + */ +template +template +LDLT& LDLT::rankUpdate(const MatrixBase& w, const typename LDLT::RealScalar& sigma) +{ + typedef typename TranspositionType::StorageIndex IndexType; + const Index size = w.rows(); + if (m_isInitialized) + { + eigen_assert(m_matrix.rows()==size); + } + else + { + m_matrix.resize(size,size); + m_matrix.setZero(); + m_transpositions.resize(size); + for (Index i = 0; i < size; i++) + m_transpositions.coeffRef(i) = IndexType(i); + m_temporary.resize(size); + m_sign = sigma>=0 ? internal::PositiveSemiDef : internal::NegativeSemiDef; + m_isInitialized = true; + } + + internal::ldlt_inplace::update(m_matrix, m_transpositions, m_temporary, w, sigma); + + return *this; +} + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +template +void LDLT<_MatrixType,_UpLo>::_solve_impl(const RhsType &rhs, DstType &dst) const +{ + eigen_assert(rhs.rows() == rows()); + // dst = P b + dst = m_transpositions * rhs; + + // dst = L^-1 (P b) + matrixL().solveInPlace(dst); + + // dst = D^-1 (L^-1 P b) + // more precisely, use pseudo-inverse of D (see bug 241) + using std::abs; + const typename Diagonal::RealReturnType vecD(vectorD()); + // In some previous versions, tolerance was set to the max of 1/highest (or rather numeric_limits::min()) + // and the maximal diagonal entry * epsilon as motivated by LAPACK's xGELSS: + // RealScalar tolerance = numext::maxi(vecD.array().abs().maxCoeff() * NumTraits::epsilon(),RealScalar(1) / NumTraits::highest()); + // However, LDLT is not rank revealing, and so adjusting the tolerance wrt to the highest + // diagonal element is not well justified and leads to numerical issues in some cases. + // Moreover, Lapack's xSYTRS routines use 0 for the tolerance. + // Using numeric_limits::min() gives us more robustness to denormals. + RealScalar tolerance = (std::numeric_limits::min)(); + + for (Index i = 0; i < vecD.size(); ++i) + { + if(abs(vecD(i)) > tolerance) + dst.row(i) /= vecD(i); + else + dst.row(i).setZero(); + } + + // dst = L^-T (D^-1 L^-1 P b) + matrixU().solveInPlace(dst); + + // dst = P^-1 (L^-T D^-1 L^-1 P b) = A^-1 b + dst = m_transpositions.transpose() * dst; +} +#endif + +/** \internal use x = ldlt_object.solve(x); + * + * This is the \em in-place version of solve(). + * + * \param bAndX represents both the right-hand side matrix b and result x. + * + * \returns true always! If you need to check for existence of solutions, use another decomposition like LU, QR, or SVD. + * + * This version avoids a copy when the right hand side matrix b is not + * needed anymore. + * + * \sa LDLT::solve(), MatrixBase::ldlt() + */ +template +template +bool LDLT::solveInPlace(MatrixBase &bAndX) const +{ + eigen_assert(m_isInitialized && "LDLT is not initialized."); + eigen_assert(m_matrix.rows() == bAndX.rows()); + + bAndX = this->solve(bAndX); + + return true; +} + +/** \returns the matrix represented by the decomposition, + * i.e., it returns the product: P^T L D L^* P. + * This function is provided for debug purpose. */ +template +MatrixType LDLT::reconstructedMatrix() const +{ + eigen_assert(m_isInitialized && "LDLT is not initialized."); + const Index size = m_matrix.rows(); + MatrixType res(size,size); + + // P + res.setIdentity(); + res = transpositionsP() * res; + // L^* P + res = matrixU() * res; + // D(L^*P) + res = vectorD().real().asDiagonal() * res; + // L(DL^*P) + res = matrixL() * res; + // P^T (LDL^*P) + res = transpositionsP().transpose() * res; + + return res; +} + +/** \cholesky_module + * \returns the Cholesky decomposition with full pivoting without square root of \c *this + * \sa MatrixBase::ldlt() + */ +template +inline const LDLT::PlainObject, UpLo> +SelfAdjointView::ldlt() const +{ + return LDLT(m_matrix); +} + +/** \cholesky_module + * \returns the Cholesky decomposition with full pivoting without square root of \c *this + * \sa SelfAdjointView::ldlt() + */ +template +inline const LDLT::PlainObject> +MatrixBase::ldlt() const +{ + return LDLT(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_LDLT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT.h new file mode 100644 index 0000000000000000000000000000000000000000..e1624d21b690961b2603562d3c9cfc338750df87 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT.h @@ -0,0 +1,542 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_LLT_H +#define EIGEN_LLT_H + +namespace Eigen { + +namespace internal{ +template struct LLT_Traits; +} + +/** \ingroup Cholesky_Module + * + * \class LLT + * + * \brief Standard Cholesky decomposition (LL^T) of a matrix and associated features + * + * \tparam _MatrixType the type of the matrix of which we are computing the LL^T Cholesky decomposition + * \tparam _UpLo the triangular part that will be used for the decompositon: Lower (default) or Upper. + * The other triangular part won't be read. + * + * This class performs a LL^T Cholesky decomposition of a symmetric, positive definite + * matrix A such that A = LL^* = U^*U, where L is lower triangular. + * + * While the Cholesky decomposition is particularly useful to solve selfadjoint problems like D^*D x = b, + * for that purpose, we recommend the Cholesky decomposition without square root which is more stable + * and even faster. Nevertheless, this standard Cholesky decomposition remains useful in many other + * situations like generalised eigen problems with hermitian matrices. + * + * Remember that Cholesky decompositions are not rank-revealing. This LLT decomposition is only stable on positive definite matrices, + * use LDLT instead for the semidefinite case. Also, do not use a Cholesky decomposition to determine whether a system of equations + * has a solution. + * + * Example: \include LLT_example.cpp + * Output: \verbinclude LLT_example.out + * + * \b Performance: for best performance, it is recommended to use a column-major storage format + * with the Lower triangular part (the default), or, equivalently, a row-major storage format + * with the Upper triangular part. Otherwise, you might get a 20% slowdown for the full factorization + * step, and rank-updates can be up to 3 times slower. + * + * This class supports the \link InplaceDecomposition inplace decomposition \endlink mechanism. + * + * Note that during the decomposition, only the lower (or upper, as defined by _UpLo) triangular part of A is considered. + * Therefore, the strict lower part does not have to store correct values. + * + * \sa MatrixBase::llt(), SelfAdjointView::llt(), class LDLT + */ +template class LLT +{ + public: + typedef _MatrixType MatrixType; + enum { + RowsAtCompileTime = MatrixType::RowsAtCompileTime, + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + typedef typename MatrixType::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3 + typedef typename MatrixType::StorageIndex StorageIndex; + + enum { + PacketSize = internal::packet_traits::size, + AlignmentMask = int(PacketSize)-1, + UpLo = _UpLo + }; + + typedef internal::LLT_Traits Traits; + + /** + * \brief Default Constructor. + * + * The default constructor is useful in cases in which the user intends to + * perform decompositions via LLT::compute(const MatrixType&). + */ + LLT() : m_matrix(), m_isInitialized(false) {} + + /** \brief Default Constructor with memory preallocation + * + * Like the default constructor but with preallocation of the internal data + * according to the specified problem \a size. + * \sa LLT() + */ + explicit LLT(Index size) : m_matrix(size, size), + m_isInitialized(false) {} + + template + explicit LLT(const EigenBase& matrix) + : m_matrix(matrix.rows(), matrix.cols()), + m_isInitialized(false) + { + compute(matrix.derived()); + } + + /** \brief Constructs a LDLT factorization from a given matrix + * + * This overloaded constructor is provided for \link InplaceDecomposition inplace decomposition \endlink when + * \c MatrixType is a Eigen::Ref. + * + * \sa LLT(const EigenBase&) + */ + template + explicit LLT(EigenBase& matrix) + : m_matrix(matrix.derived()), + m_isInitialized(false) + { + compute(matrix.derived()); + } + + /** \returns a view of the upper triangular matrix U */ + inline typename Traits::MatrixU matrixU() const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return Traits::getU(m_matrix); + } + + /** \returns a view of the lower triangular matrix L */ + inline typename Traits::MatrixL matrixL() const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return Traits::getL(m_matrix); + } + + /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A. + * + * Since this LLT class assumes anyway that the matrix A is invertible, the solution + * theoretically exists and is unique regardless of b. + * + * Example: \include LLT_solve.cpp + * Output: \verbinclude LLT_solve.out + * + * \sa solveInPlace(), MatrixBase::llt(), SelfAdjointView::llt() + */ + template + inline const Solve + solve(const MatrixBase& b) const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + eigen_assert(m_matrix.rows()==b.rows() + && "LLT::solve(): invalid number of rows of the right hand side matrix b"); + return Solve(*this, b.derived()); + } + + template + void solveInPlace(const MatrixBase &bAndX) const; + + template + LLT& compute(const EigenBase& matrix); + + /** \returns an estimate of the reciprocal condition number of the matrix of + * which \c *this is the Cholesky decomposition. + */ + RealScalar rcond() const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + eigen_assert(m_info == Success && "LLT failed because matrix appears to be negative"); + return internal::rcond_estimate_helper(m_l1_norm, *this); + } + + /** \returns the LLT decomposition matrix + * + * TODO: document the storage layout + */ + inline const MatrixType& matrixLLT() const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return m_matrix; + } + + MatrixType reconstructedMatrix() const; + + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was succesful, + * \c NumericalIssue if the matrix.appears not to be positive definite. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "LLT is not initialized."); + return m_info; + } + + /** \returns the adjoint of \c *this, that is, a const reference to the decomposition itself as the underlying matrix is self-adjoint. + * + * This method is provided for compatibility with other matrix decompositions, thus enabling generic code such as: + * \code x = decomposition.adjoint().solve(b) \endcode + */ + const LLT& adjoint() const { return *this; }; + + inline Index rows() const { return m_matrix.rows(); } + inline Index cols() const { return m_matrix.cols(); } + + template + LLT rankUpdate(const VectorType& vec, const RealScalar& sigma = 1); + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC + void _solve_impl(const RhsType &rhs, DstType &dst) const; + #endif + + protected: + + static void check_template_parameters() + { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar); + } + + /** \internal + * Used to compute and store L + * The strict upper part is not used and even not initialized. + */ + MatrixType m_matrix; + RealScalar m_l1_norm; + bool m_isInitialized; + ComputationInfo m_info; +}; + +namespace internal { + +template struct llt_inplace; + +template +static Index llt_rank_update_lower(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) +{ + using std::sqrt; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef typename MatrixType::ColXpr ColXpr; + typedef typename internal::remove_all::type ColXprCleaned; + typedef typename ColXprCleaned::SegmentReturnType ColXprSegment; + typedef Matrix TempVectorType; + typedef typename TempVectorType::SegmentReturnType TempVecSegment; + + Index n = mat.cols(); + eigen_assert(mat.rows()==n && vec.size()==n); + + TempVectorType temp; + + if(sigma>0) + { + // This version is based on Givens rotations. + // It is faster than the other one below, but only works for updates, + // i.e., for sigma > 0 + temp = sqrt(sigma) * vec; + + for(Index i=0; i g; + g.makeGivens(mat(i,i), -temp(i), &mat(i,i)); + + Index rs = n-i-1; + if(rs>0) + { + ColXprSegment x(mat.col(i).tail(rs)); + TempVecSegment y(temp.tail(rs)); + apply_rotation_in_the_plane(x, y, g); + } + } + } + else + { + temp = vec; + RealScalar beta = 1; + for(Index j=0; j struct llt_inplace +{ + typedef typename NumTraits::Real RealScalar; + template + static Index unblocked(MatrixType& mat) + { + using std::sqrt; + + eigen_assert(mat.rows()==mat.cols()); + const Index size = mat.rows(); + for(Index k = 0; k < size; ++k) + { + Index rs = size-k-1; // remaining size + + Block A21(mat,k+1,k,rs,1); + Block A10(mat,k,0,1,k); + Block A20(mat,k+1,0,rs,k); + + RealScalar x = numext::real(mat.coeff(k,k)); + if (k>0) x -= A10.squaredNorm(); + if (x<=RealScalar(0)) + return k; + mat.coeffRef(k,k) = x = sqrt(x); + if (k>0 && rs>0) A21.noalias() -= A20 * A10.adjoint(); + if (rs>0) A21 /= x; + } + return -1; + } + + template + static Index blocked(MatrixType& m) + { + eigen_assert(m.rows()==m.cols()); + Index size = m.rows(); + if(size<32) + return unblocked(m); + + Index blockSize = size/8; + blockSize = (blockSize/16)*16; + blockSize = (std::min)((std::max)(blockSize,Index(8)), Index(128)); + + for (Index k=0; k A11(m,k, k, bs,bs); + Block A21(m,k+bs,k, rs,bs); + Block A22(m,k+bs,k+bs,rs,rs); + + Index ret; + if((ret=unblocked(A11))>=0) return k+ret; + if(rs>0) A11.adjoint().template triangularView().template solveInPlace(A21); + if(rs>0) A22.template selfadjointView().rankUpdate(A21,typename NumTraits::Literal(-1)); // bottleneck + } + return -1; + } + + template + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) + { + return Eigen::internal::llt_rank_update_lower(mat, vec, sigma); + } +}; + +template struct llt_inplace +{ + typedef typename NumTraits::Real RealScalar; + + template + static EIGEN_STRONG_INLINE Index unblocked(MatrixType& mat) + { + Transpose matt(mat); + return llt_inplace::unblocked(matt); + } + template + static EIGEN_STRONG_INLINE Index blocked(MatrixType& mat) + { + Transpose matt(mat); + return llt_inplace::blocked(matt); + } + template + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const RealScalar& sigma) + { + Transpose matt(mat); + return llt_inplace::rankUpdate(matt, vec.conjugate(), sigma); + } +}; + +template struct LLT_Traits +{ + typedef const TriangularView MatrixL; + typedef const TriangularView MatrixU; + static inline MatrixL getL(const MatrixType& m) { return MatrixL(m); } + static inline MatrixU getU(const MatrixType& m) { return MatrixU(m.adjoint()); } + static bool inplace_decomposition(MatrixType& m) + { return llt_inplace::blocked(m)==-1; } +}; + +template struct LLT_Traits +{ + typedef const TriangularView MatrixL; + typedef const TriangularView MatrixU; + static inline MatrixL getL(const MatrixType& m) { return MatrixL(m.adjoint()); } + static inline MatrixU getU(const MatrixType& m) { return MatrixU(m); } + static bool inplace_decomposition(MatrixType& m) + { return llt_inplace::blocked(m)==-1; } +}; + +} // end namespace internal + +/** Computes / recomputes the Cholesky decomposition A = LL^* = U^*U of \a matrix + * + * \returns a reference to *this + * + * Example: \include TutorialLinAlgComputeTwice.cpp + * Output: \verbinclude TutorialLinAlgComputeTwice.out + */ +template +template +LLT& LLT::compute(const EigenBase& a) +{ + check_template_parameters(); + + eigen_assert(a.rows()==a.cols()); + const Index size = a.rows(); + m_matrix.resize(size, size); + if (!internal::is_same_dense(m_matrix, a.derived())) + m_matrix = a.derived(); + + // Compute matrix L1 norm = max abs column sum. + m_l1_norm = RealScalar(0); + // TODO move this code to SelfAdjointView + for (Index col = 0; col < size; ++col) { + RealScalar abs_col_sum; + if (_UpLo == Lower) + abs_col_sum = m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>(); + else + abs_col_sum = m_matrix.col(col).head(col).template lpNorm<1>() + m_matrix.row(col).tail(size - col).template lpNorm<1>(); + if (abs_col_sum > m_l1_norm) + m_l1_norm = abs_col_sum; + } + + m_isInitialized = true; + bool ok = Traits::inplace_decomposition(m_matrix); + m_info = ok ? Success : NumericalIssue; + + return *this; +} + +/** Performs a rank one update (or dowdate) of the current decomposition. + * If A = LL^* before the rank one update, + * then after it we have LL^* = A + sigma * v v^* where \a v must be a vector + * of same dimension. + */ +template +template +LLT<_MatrixType,_UpLo> LLT<_MatrixType,_UpLo>::rankUpdate(const VectorType& v, const RealScalar& sigma) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(VectorType); + eigen_assert(v.size()==m_matrix.cols()); + eigen_assert(m_isInitialized); + if(internal::llt_inplace::rankUpdate(m_matrix,v,sigma)>=0) + m_info = NumericalIssue; + else + m_info = Success; + + return *this; +} + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +template +void LLT<_MatrixType,_UpLo>::_solve_impl(const RhsType &rhs, DstType &dst) const +{ + dst = rhs; + solveInPlace(dst); +} +#endif + +/** \internal use x = llt_object.solve(x); + * + * This is the \em in-place version of solve(). + * + * \param bAndX represents both the right-hand side matrix b and result x. + * + * This version avoids a copy when the right hand side matrix b is not needed anymore. + * + * \warning The parameter is only marked 'const' to make the C++ compiler accept a temporary expression here. + * This function will const_cast it, so constness isn't honored here. + * + * \sa LLT::solve(), MatrixBase::llt() + */ +template +template +void LLT::solveInPlace(const MatrixBase &bAndX) const +{ + eigen_assert(m_isInitialized && "LLT is not initialized."); + eigen_assert(m_matrix.rows()==bAndX.rows()); + matrixL().solveInPlace(bAndX); + matrixU().solveInPlace(bAndX); +} + +/** \returns the matrix represented by the decomposition, + * i.e., it returns the product: L L^*. + * This function is provided for debug purpose. */ +template +MatrixType LLT::reconstructedMatrix() const +{ + eigen_assert(m_isInitialized && "LLT is not initialized."); + return matrixL() * matrixL().adjoint().toDenseMatrix(); +} + +/** \cholesky_module + * \returns the LLT decomposition of \c *this + * \sa SelfAdjointView::llt() + */ +template +inline const LLT::PlainObject> +MatrixBase::llt() const +{ + return LLT(derived()); +} + +/** \cholesky_module + * \returns the LLT decomposition of \c *this + * \sa SelfAdjointView::llt() + */ +template +inline const LLT::PlainObject, UpLo> +SelfAdjointView::llt() const +{ + return LLT(m_matrix); +} + +} // end namespace Eigen + +#endif // EIGEN_LLT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT_LAPACKE.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT_LAPACKE.h new file mode 100644 index 0000000000000000000000000000000000000000..bc6489e69a98328e016d4cc7e0d36a147744d337 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Cholesky/LLT_LAPACKE.h @@ -0,0 +1,99 @@ +/* + Copyright (c) 2011, Intel Corporation. All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ******************************************************************************** + * Content : Eigen bindings to LAPACKe + * LLt decomposition based on LAPACKE_?potrf function. + ******************************************************************************** +*/ + +#ifndef EIGEN_LLT_LAPACKE_H +#define EIGEN_LLT_LAPACKE_H + +namespace Eigen { + +namespace internal { + +template struct lapacke_llt; + +#define EIGEN_LAPACKE_LLT(EIGTYPE, BLASTYPE, LAPACKE_PREFIX) \ +template<> struct lapacke_llt \ +{ \ + template \ + static inline Index potrf(MatrixType& m, char uplo) \ + { \ + lapack_int matrix_order; \ + lapack_int size, lda, info, StorageOrder; \ + EIGTYPE* a; \ + eigen_assert(m.rows()==m.cols()); \ + /* Set up parameters for ?potrf */ \ + size = convert_index(m.rows()); \ + StorageOrder = MatrixType::Flags&RowMajorBit?RowMajor:ColMajor; \ + matrix_order = StorageOrder==RowMajor ? LAPACK_ROW_MAJOR : LAPACK_COL_MAJOR; \ + a = &(m.coeffRef(0,0)); \ + lda = convert_index(m.outerStride()); \ +\ + info = LAPACKE_##LAPACKE_PREFIX##potrf( matrix_order, uplo, size, (BLASTYPE*)a, lda ); \ + info = (info==0) ? -1 : info>0 ? info-1 : size; \ + return info; \ + } \ +}; \ +template<> struct llt_inplace \ +{ \ + template \ + static Index blocked(MatrixType& m) \ + { \ + return lapacke_llt::potrf(m, 'L'); \ + } \ + template \ + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \ + { return Eigen::internal::llt_rank_update_lower(mat, vec, sigma); } \ +}; \ +template<> struct llt_inplace \ +{ \ + template \ + static Index blocked(MatrixType& m) \ + { \ + return lapacke_llt::potrf(m, 'U'); \ + } \ + template \ + static Index rankUpdate(MatrixType& mat, const VectorType& vec, const typename MatrixType::RealScalar& sigma) \ + { \ + Transpose matt(mat); \ + return llt_inplace::rankUpdate(matt, vec.conjugate(), sigma); \ + } \ +}; + +EIGEN_LAPACKE_LLT(double, double, d) +EIGEN_LAPACKE_LLT(float, float, s) +EIGEN_LAPACKE_LLT(dcomplex, lapack_complex_double, z) +EIGEN_LAPACKE_LLT(scomplex, lapack_complex_float, c) + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_LLT_LAPACKE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h new file mode 100644 index 0000000000000000000000000000000000000000..57197202383a6dfb1be48607f84ecaddb715e0e2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/CholmodSupport/CholmodSupport.h @@ -0,0 +1,639 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CHOLMODSUPPORT_H +#define EIGEN_CHOLMODSUPPORT_H + +namespace Eigen { + +namespace internal { + +template struct cholmod_configure_matrix; + +template<> struct cholmod_configure_matrix { + template + static void run(CholmodType& mat) { + mat.xtype = CHOLMOD_REAL; + mat.dtype = CHOLMOD_DOUBLE; + } +}; + +template<> struct cholmod_configure_matrix > { + template + static void run(CholmodType& mat) { + mat.xtype = CHOLMOD_COMPLEX; + mat.dtype = CHOLMOD_DOUBLE; + } +}; + +// Other scalar types are not yet suppotred by Cholmod +// template<> struct cholmod_configure_matrix { +// template +// static void run(CholmodType& mat) { +// mat.xtype = CHOLMOD_REAL; +// mat.dtype = CHOLMOD_SINGLE; +// } +// }; +// +// template<> struct cholmod_configure_matrix > { +// template +// static void run(CholmodType& mat) { +// mat.xtype = CHOLMOD_COMPLEX; +// mat.dtype = CHOLMOD_SINGLE; +// } +// }; + +} // namespace internal + +/** Wraps the Eigen sparse matrix \a mat into a Cholmod sparse matrix object. + * Note that the data are shared. + */ +template +cholmod_sparse viewAsCholmod(Ref > mat) +{ + cholmod_sparse res; + res.nzmax = mat.nonZeros(); + res.nrow = mat.rows(); + res.ncol = mat.cols(); + res.p = mat.outerIndexPtr(); + res.i = mat.innerIndexPtr(); + res.x = mat.valuePtr(); + res.z = 0; + res.sorted = 1; + if(mat.isCompressed()) + { + res.packed = 1; + res.nz = 0; + } + else + { + res.packed = 0; + res.nz = mat.innerNonZeroPtr(); + } + + res.dtype = 0; + res.stype = -1; + + if (internal::is_same<_StorageIndex,int>::value) + { + res.itype = CHOLMOD_INT; + } + else if (internal::is_same<_StorageIndex,long>::value) + { + res.itype = CHOLMOD_LONG; + } + else + { + eigen_assert(false && "Index type not supported yet"); + } + + // setup res.xtype + internal::cholmod_configure_matrix<_Scalar>::run(res); + + res.stype = 0; + + return res; +} + +template +const cholmod_sparse viewAsCholmod(const SparseMatrix<_Scalar,_Options,_Index>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.const_cast_derived())); + return res; +} + +template +const cholmod_sparse viewAsCholmod(const SparseVector<_Scalar,_Options,_Index>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.const_cast_derived())); + return res; +} + +/** Returns a view of the Eigen sparse matrix \a mat as Cholmod sparse matrix. + * The data are not copied but shared. */ +template +cholmod_sparse viewAsCholmod(const SparseSelfAdjointView, UpLo>& mat) +{ + cholmod_sparse res = viewAsCholmod(Ref >(mat.matrix().const_cast_derived())); + + if(UpLo==Upper) res.stype = 1; + if(UpLo==Lower) res.stype = -1; + + return res; +} + +/** Returns a view of the Eigen \b dense matrix \a mat as Cholmod dense matrix. + * The data are not copied but shared. */ +template +cholmod_dense viewAsCholmod(MatrixBase& mat) +{ + EIGEN_STATIC_ASSERT((internal::traits::Flags&RowMajorBit)==0,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + typedef typename Derived::Scalar Scalar; + + cholmod_dense res; + res.nrow = mat.rows(); + res.ncol = mat.cols(); + res.nzmax = res.nrow * res.ncol; + res.d = Derived::IsVectorAtCompileTime ? mat.derived().size() : mat.derived().outerStride(); + res.x = (void*)(mat.derived().data()); + res.z = 0; + + internal::cholmod_configure_matrix::run(res); + + return res; +} + +/** Returns a view of the Cholmod sparse matrix \a cm as an Eigen sparse matrix. + * The data are not copied but shared. */ +template +MappedSparseMatrix viewAsEigen(cholmod_sparse& cm) +{ + return MappedSparseMatrix + (cm.nrow, cm.ncol, static_cast(cm.p)[cm.ncol], + static_cast(cm.p), static_cast(cm.i),static_cast(cm.x) ); +} + +enum CholmodMode { + CholmodAuto, CholmodSimplicialLLt, CholmodSupernodalLLt, CholmodLDLt +}; + + +/** \ingroup CholmodSupport_Module + * \class CholmodBase + * \brief The base class for the direct Cholesky factorization of Cholmod + * \sa class CholmodSupernodalLLT, class CholmodSimplicialLDLT, class CholmodSimplicialLLT + */ +template +class CholmodBase : public SparseSolverBase +{ + protected: + typedef SparseSolverBase Base; + using Base::derived; + using Base::m_isInitialized; + public: + typedef _MatrixType MatrixType; + enum { UpLo = _UpLo }; + typedef typename MatrixType::Scalar Scalar; + typedef typename MatrixType::RealScalar RealScalar; + typedef MatrixType CholMatrixType; + typedef typename MatrixType::StorageIndex StorageIndex; + enum { + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime + }; + + public: + + CholmodBase() + : m_cholmodFactor(0), m_info(Success), m_factorizationIsOk(false), m_analysisIsOk(false) + { + EIGEN_STATIC_ASSERT((internal::is_same::value), CHOLMOD_SUPPORTS_DOUBLE_PRECISION_ONLY); + m_shiftOffset[0] = m_shiftOffset[1] = 0.0; + cholmod_start(&m_cholmod); + } + + explicit CholmodBase(const MatrixType& matrix) + : m_cholmodFactor(0), m_info(Success), m_factorizationIsOk(false), m_analysisIsOk(false) + { + EIGEN_STATIC_ASSERT((internal::is_same::value), CHOLMOD_SUPPORTS_DOUBLE_PRECISION_ONLY); + m_shiftOffset[0] = m_shiftOffset[1] = 0.0; + cholmod_start(&m_cholmod); + compute(matrix); + } + + ~CholmodBase() + { + if(m_cholmodFactor) + cholmod_free_factor(&m_cholmodFactor, &m_cholmod); + cholmod_finish(&m_cholmod); + } + + inline StorageIndex cols() const { return internal::convert_index(m_cholmodFactor->n); } + inline StorageIndex rows() const { return internal::convert_index(m_cholmodFactor->n); } + + /** \brief Reports whether previous computation was successful. + * + * \returns \c Success if computation was succesful, + * \c NumericalIssue if the matrix.appears to be negative. + */ + ComputationInfo info() const + { + eigen_assert(m_isInitialized && "Decomposition is not initialized."); + return m_info; + } + + /** Computes the sparse Cholesky decomposition of \a matrix */ + Derived& compute(const MatrixType& matrix) + { + analyzePattern(matrix); + factorize(matrix); + return derived(); + } + + /** Performs a symbolic decomposition on the sparsity pattern of \a matrix. + * + * This function is particularly useful when solving for several problems having the same structure. + * + * \sa factorize() + */ + void analyzePattern(const MatrixType& matrix) + { + if(m_cholmodFactor) + { + cholmod_free_factor(&m_cholmodFactor, &m_cholmod); + m_cholmodFactor = 0; + } + cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView()); + m_cholmodFactor = cholmod_analyze(&A, &m_cholmod); + + this->m_isInitialized = true; + this->m_info = Success; + m_analysisIsOk = true; + m_factorizationIsOk = false; + } + + /** Performs a numeric decomposition of \a matrix + * + * The given matrix must have the same sparsity pattern as the matrix on which the symbolic decomposition has been performed. + * + * \sa analyzePattern() + */ + void factorize(const MatrixType& matrix) + { + eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); + cholmod_sparse A = viewAsCholmod(matrix.template selfadjointView()); + cholmod_factorize_p(&A, m_shiftOffset, 0, 0, m_cholmodFactor, &m_cholmod); + + // If the factorization failed, minor is the column at which it did. On success minor == n. + this->m_info = (m_cholmodFactor->minor == m_cholmodFactor->n ? Success : NumericalIssue); + m_factorizationIsOk = true; + } + + /** Returns a reference to the Cholmod's configuration structure to get a full control over the performed operations. + * See the Cholmod user guide for details. */ + cholmod_common& cholmod() { return m_cholmod; } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal */ + template + void _solve_impl(const MatrixBase &b, MatrixBase &dest) const + { + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + const Index size = m_cholmodFactor->n; + EIGEN_UNUSED_VARIABLE(size); + eigen_assert(size==b.rows()); + + // Cholmod needs column-major stoarge without inner-stride, which corresponds to the default behavior of Ref. + Ref > b_ref(b.derived()); + + cholmod_dense b_cd = viewAsCholmod(b_ref); + cholmod_dense* x_cd = cholmod_solve(CHOLMOD_A, m_cholmodFactor, &b_cd, &m_cholmod); + if(!x_cd) + { + this->m_info = NumericalIssue; + return; + } + // TODO optimize this copy by swapping when possible (be careful with alignment, etc.) + dest = Matrix::Map(reinterpret_cast(x_cd->x),b.rows(),b.cols()); + cholmod_free_dense(&x_cd, &m_cholmod); + } + + /** \internal */ + template + void _solve_impl(const SparseMatrixBase &b, SparseMatrixBase &dest) const + { + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + const Index size = m_cholmodFactor->n; + EIGEN_UNUSED_VARIABLE(size); + eigen_assert(size==b.rows()); + + // note: cs stands for Cholmod Sparse + Ref > b_ref(b.const_cast_derived()); + cholmod_sparse b_cs = viewAsCholmod(b_ref); + cholmod_sparse* x_cs = cholmod_spsolve(CHOLMOD_A, m_cholmodFactor, &b_cs, &m_cholmod); + if(!x_cs) + { + this->m_info = NumericalIssue; + return; + } + // TODO optimize this copy by swapping when possible (be careful with alignment, etc.) + dest.derived() = viewAsEigen(*x_cs); + cholmod_free_sparse(&x_cs, &m_cholmod); + } + #endif // EIGEN_PARSED_BY_DOXYGEN + + + /** Sets the shift parameter that will be used to adjust the diagonal coefficients during the numerical factorization. + * + * During the numerical factorization, an offset term is added to the diagonal coefficients:\n + * \c d_ii = \a offset + \c d_ii + * + * The default is \a offset=0. + * + * \returns a reference to \c *this. + */ + Derived& setShift(const RealScalar& offset) + { + m_shiftOffset[0] = double(offset); + return derived(); + } + + /** \returns the determinant of the underlying matrix from the current factorization */ + Scalar determinant() const + { + using std::exp; + return exp(logDeterminant()); + } + + /** \returns the log determinant of the underlying matrix from the current factorization */ + Scalar logDeterminant() const + { + using std::log; + using numext::real; + eigen_assert(m_factorizationIsOk && "The decomposition is not in a valid state for solving, you must first call either compute() or symbolic()/numeric()"); + + RealScalar logDet = 0; + Scalar *x = static_cast(m_cholmodFactor->x); + if (m_cholmodFactor->is_super) + { + // Supernodal factorization stored as a packed list of dense column-major blocs, + // as described by the following structure: + + // super[k] == index of the first column of the j-th super node + StorageIndex *super = static_cast(m_cholmodFactor->super); + // pi[k] == offset to the description of row indices + StorageIndex *pi = static_cast(m_cholmodFactor->pi); + // px[k] == offset to the respective dense block + StorageIndex *px = static_cast(m_cholmodFactor->px); + + Index nb_super_nodes = m_cholmodFactor->nsuper; + for (Index k=0; k < nb_super_nodes; ++k) + { + StorageIndex ncols = super[k + 1] - super[k]; + StorageIndex nrows = pi[k + 1] - pi[k]; + + Map, 0, InnerStride<> > sk(x + px[k], ncols, InnerStride<>(nrows+1)); + logDet += sk.real().log().sum(); + } + } + else + { + // Simplicial factorization stored as standard CSC matrix. + StorageIndex *p = static_cast(m_cholmodFactor->p); + Index size = m_cholmodFactor->n; + for (Index k=0; kis_ll) + logDet *= 2.0; + return logDet; + }; + + template + void dumpMemory(Stream& /*s*/) + {} + + protected: + mutable cholmod_common m_cholmod; + cholmod_factor* m_cholmodFactor; + double m_shiftOffset[2]; + mutable ComputationInfo m_info; + int m_factorizationIsOk; + int m_analysisIsOk; +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodSimplicialLLT + * \brief A simplicial direct Cholesky (LLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a simplicial LL^T Cholesky factorization + * using the Cholmod library. + * This simplicial variant is equivalent to Eigen's built-in SimplicialLLT class. Therefore, it has little practical interest. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept, class CholmodSupernodalLLT, class SimplicialLLT + */ +template +class CholmodSimplicialLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSimplicialLLT() : Base() { init(); } + + CholmodSimplicialLLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSimplicialLLT() {} + protected: + void init() + { + m_cholmod.final_asis = 0; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + m_cholmod.final_ll = 1; + } +}; + + +/** \ingroup CholmodSupport_Module + * \class CholmodSimplicialLDLT + * \brief A simplicial direct Cholesky (LDLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a simplicial LDL^T Cholesky factorization + * using the Cholmod library. + * This simplicial variant is equivalent to Eigen's built-in SimplicialLDLT class. Therefore, it has little practical interest. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept, class CholmodSupernodalLLT, class SimplicialLDLT + */ +template +class CholmodSimplicialLDLT : public CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSimplicialLDLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSimplicialLDLT() : Base() { init(); } + + CholmodSimplicialLDLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSimplicialLDLT() {} + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + } +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodSupernodalLLT + * \brief A supernodal Cholesky (LLT) factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a supernodal LL^T Cholesky factorization + * using the Cholmod library. + * This supernodal variant performs best on dense enough problems, e.g., 3D FEM, or very high order 2D FEM. + * The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept + */ +template +class CholmodSupernodalLLT : public CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodSupernodalLLT> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodSupernodalLLT() : Base() { init(); } + + CholmodSupernodalLLT(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodSupernodalLLT() {} + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SUPERNODAL; + } +}; + +/** \ingroup CholmodSupport_Module + * \class CholmodDecomposition + * \brief A general Cholesky factorization and solver based on Cholmod + * + * This class allows to solve for A.X = B sparse linear problems via a LL^T or LDL^T Cholesky factorization + * using the Cholmod library. The sparse matrix A must be selfadjoint and positive definite. The vectors or matrices + * X and B can be either dense or sparse. + * + * This variant permits to change the underlying Cholesky method at runtime. + * On the other hand, it does not provide access to the result of the factorization. + * The default is to let Cholmod automatically choose between a simplicial and supernodal factorization. + * + * \tparam _MatrixType the type of the sparse matrix A, it must be a SparseMatrix<> + * \tparam _UpLo the triangular part that will be used for the computations. It can be Lower + * or Upper. Default is Lower. + * + * \implsparsesolverconcept + * + * This class supports all kind of SparseMatrix<>: row or column major; upper, lower, or both; compressed or non compressed. + * + * \warning Only double precision real and complex scalar types are supported by Cholmod. + * + * \sa \ref TutorialSparseSolverConcept + */ +template +class CholmodDecomposition : public CholmodBase<_MatrixType, _UpLo, CholmodDecomposition<_MatrixType, _UpLo> > +{ + typedef CholmodBase<_MatrixType, _UpLo, CholmodDecomposition> Base; + using Base::m_cholmod; + + public: + + typedef _MatrixType MatrixType; + + CholmodDecomposition() : Base() { init(); } + + CholmodDecomposition(const MatrixType& matrix) : Base() + { + init(); + this->compute(matrix); + } + + ~CholmodDecomposition() {} + + void setMode(CholmodMode mode) + { + switch(mode) + { + case CholmodAuto: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_AUTO; + break; + case CholmodSimplicialLLt: + m_cholmod.final_asis = 0; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + m_cholmod.final_ll = 1; + break; + case CholmodSupernodalLLt: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SUPERNODAL; + break; + case CholmodLDLt: + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_SIMPLICIAL; + break; + default: + break; + } + } + protected: + void init() + { + m_cholmod.final_asis = 1; + m_cholmod.supernodal = CHOLMOD_AUTO; + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CHOLMODSUPPORT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Array.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Array.h new file mode 100644 index 0000000000000000000000000000000000000000..16770fc7b3a2c5a2e0e84da45f3b2761caf2d0fa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Array.h @@ -0,0 +1,329 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ARRAY_H +#define EIGEN_ARRAY_H + +namespace Eigen { + +namespace internal { +template +struct traits > : traits > +{ + typedef ArrayXpr XprKind; + typedef ArrayBase > XprBase; +}; +} + +/** \class Array + * \ingroup Core_Module + * + * \brief General-purpose arrays with easy API for coefficient-wise operations + * + * The %Array class is very similar to the Matrix class. It provides + * general-purpose one- and two-dimensional arrays. The difference between the + * %Array and the %Matrix class is primarily in the API: the API for the + * %Array class provides easy access to coefficient-wise operations, while the + * API for the %Matrix class provides easy access to linear-algebra + * operations. + * + * See documentation of class Matrix for detailed information on the template parameters + * storage layout. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAY_PLUGIN. + * + * \sa \blank \ref TutorialArrayClass, \ref TopicClassHierarchy + */ +template +class Array + : public PlainObjectBase > +{ + public: + + typedef PlainObjectBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Array) + + enum { Options = _Options }; + typedef typename Base::PlainObject PlainObject; + + protected: + template + friend struct internal::conservative_resize_like_impl; + + using Base::m_storage; + + public: + + using Base::base; + using Base::coeff; + using Base::coeffRef; + + /** + * The usage of + * using Base::operator=; + * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped + * the usage of 'using'. This should be done only for operator=. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array& operator=(const EigenBase &other) + { + return Base::operator=(other); + } + + /** Set all the entries to \a value. + * \sa DenseBase::setConstant(), DenseBase::fill() + */ + /* This overload is needed because the usage of + * using Base::operator=; + * fails on MSVC. Since the code below is working with GCC and MSVC, we skipped + * the usage of 'using'. This should be done only for operator=. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array& operator=(const Scalar &value) + { + Base::setConstant(value); + return *this; + } + + /** Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array& operator=(const DenseBase& other) + { + return Base::_set(other); + } + + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array& operator=(const Array& other) + { + return Base::_set(other); + } + + /** Default constructor. + * + * For fixed-size matrices, does nothing. + * + * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix + * is called a null matrix. This constructor is the unique way to create null matrices: resizing + * a matrix to 0 is not supported. + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array() : Base() + { + Base::_check_template_params(); + EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + // FIXME is it still needed ?? + /** \internal */ + EIGEN_DEVICE_FUNC + Array(internal::constructor_without_unaligned_array_assert) + : Base(internal::constructor_without_unaligned_array_assert()) + { + Base::_check_template_params(); + EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } +#endif + +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + Array(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) + : Base(std::move(other)) + { + Base::_check_template_params(); + } + EIGEN_DEVICE_FUNC + Array& operator=(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) + { + other.swap(*this); + return *this; + } +#endif + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE explicit Array(const T& x) + { + Base::_check_template_params(); + Base::template _init1(x); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array(const T0& val0, const T1& val1) + { + Base::_check_template_params(); + this->template _init2(val0, val1); + } + #else + /** \brief Constructs a fixed-sized array initialized with coefficients starting at \a data */ + EIGEN_DEVICE_FUNC explicit Array(const Scalar *data); + /** Constructs a vector or row-vector with given dimension. \only_for_vectors + * + * Note that this is only useful for dynamic-size vectors. For fixed-size vectors, + * it is redundant to pass the dimension here, so it makes more sense to use the default + * constructor Array() instead. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE explicit Array(Index dim); + /** constructs an initialized 1x1 Array with the given coefficient */ + Array(const Scalar& value); + /** constructs an uninitialized array with \a rows rows and \a cols columns. + * + * This is useful for dynamic-size arrays. For fixed-size arrays, + * it is redundant to pass these parameters, so one should use the default constructor + * Array() instead. */ + Array(Index rows, Index cols); + /** constructs an initialized 2D vector with given coefficients */ + Array(const Scalar& val0, const Scalar& val1); + #endif + + /** constructs an initialized 3D vector with given coefficients */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2) + { + Base::_check_template_params(); + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 3) + m_storage.data()[0] = val0; + m_storage.data()[1] = val1; + m_storage.data()[2] = val2; + } + /** constructs an initialized 4D vector with given coefficients */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2, const Scalar& val3) + { + Base::_check_template_params(); + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 4) + m_storage.data()[0] = val0; + m_storage.data()[1] = val1; + m_storage.data()[2] = val2; + m_storage.data()[3] = val3; + } + + /** Copy constructor */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array(const Array& other) + : Base(other) + { } + + private: + struct PrivateType {}; + public: + + /** \sa MatrixBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Array(const EigenBase &other, + typename internal::enable_if::value, + PrivateType>::type = PrivateType()) + : Base(other.derived()) + { } + + EIGEN_DEVICE_FUNC inline Index innerStride() const { return 1; } + EIGEN_DEVICE_FUNC inline Index outerStride() const { return this->innerSize(); } + + #ifdef EIGEN_ARRAY_PLUGIN + #include EIGEN_ARRAY_PLUGIN + #endif + + private: + + template + friend struct internal::matrix_swap_impl; +}; + +/** \defgroup arraytypedefs Global array typedefs + * \ingroup Core_Module + * + * Eigen defines several typedef shortcuts for most common 1D and 2D array types. + * + * The general patterns are the following: + * + * \c ArrayRowsColsType where \c Rows and \c Cols can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size, + * and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd + * for complex double. + * + * For example, \c Array33d is a fixed-size 3x3 array type of doubles, and \c ArrayXXf is a dynamic-size matrix of floats. + * + * There are also \c ArraySizeType which are self-explanatory. For example, \c Array4cf is + * a fixed-size 1D array of 4 complex floats. + * + * \sa class Array + */ + +#define EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ +/** \ingroup arraytypedefs */ \ +typedef Array Array##SizeSuffix##SizeSuffix##TypeSuffix; \ +/** \ingroup arraytypedefs */ \ +typedef Array Array##SizeSuffix##TypeSuffix; + +#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ +/** \ingroup arraytypedefs */ \ +typedef Array Array##Size##X##TypeSuffix; \ +/** \ingroup arraytypedefs */ \ +typedef Array Array##X##Size##TypeSuffix; + +#define EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \ +EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 2, 2) \ +EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 3, 3) \ +EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 4, 4) \ +EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ +EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ +EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ +EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 4) + +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(int, i) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(float, f) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(double, d) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex, cf) +EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex, cd) + +#undef EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES +#undef EIGEN_MAKE_ARRAY_TYPEDEFS + +#undef EIGEN_MAKE_ARRAY_TYPEDEFS_LARGE + +#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, SizeSuffix) \ +using Eigen::Matrix##SizeSuffix##TypeSuffix; \ +using Eigen::Vector##SizeSuffix##TypeSuffix; \ +using Eigen::RowVector##SizeSuffix##TypeSuffix; + +#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(TypeSuffix) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) \ + +#define EIGEN_USING_ARRAY_TYPEDEFS \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(i) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(f) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(d) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cf) \ +EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cd) + +} // end namespace Eigen + +#endif // EIGEN_ARRAY_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayBase.h new file mode 100644 index 0000000000000000000000000000000000000000..3dbc7084cdaa5c69dc16b11945139f4e8d8bc3ce --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayBase.h @@ -0,0 +1,226 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ARRAYBASE_H +#define EIGEN_ARRAYBASE_H + +namespace Eigen { + +template class MatrixWrapper; + +/** \class ArrayBase + * \ingroup Core_Module + * + * \brief Base class for all 1D and 2D array, and related expressions + * + * An array is similar to a dense vector or matrix. While matrices are mathematical + * objects with well defined linear algebra operators, an array is just a collection + * of scalar values arranged in a one or two dimensionnal fashion. As the main consequence, + * all operations applied to an array are performed coefficient wise. Furthermore, + * arrays support scalar math functions of the c++ standard library (e.g., std::sin(x)), and convenient + * constructors allowing to easily write generic code working for both scalar values + * and arrays. + * + * This class is the base that is inherited by all array expression types. + * + * \tparam Derived is the derived type, e.g., an array or an expression type. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAYBASE_PLUGIN. + * + * \sa class MatrixBase, \ref TopicClassHierarchy + */ +template class ArrayBase + : public DenseBase +{ + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** The base class for a given storage type. */ + typedef ArrayBase StorageBaseType; + + typedef ArrayBase Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + typedef DenseBase Base; + using Base::RowsAtCompileTime; + using Base::ColsAtCompileTime; + using Base::SizeAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::IsVectorAtCompileTime; + using Base::Flags; + + using Base::derived; + using Base::const_cast_derived; + using Base::rows; + using Base::cols; + using Base::size; + using Base::coeff; + using Base::coeffRef; + using Base::lazyAssign; + using Base::operator=; + using Base::operator+=; + using Base::operator-=; + using Base::operator*=; + using Base::operator/=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN + +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Base::PlainObject PlainObject; + + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp,PlainObject> ConstantReturnType; +#endif // not EIGEN_PARSED_BY_DOXYGEN + +#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::ArrayBase +#define EIGEN_DOC_UNARY_ADDONS(X,Y) +# include "../plugins/CommonCwiseUnaryOps.h" +# include "../plugins/MatrixCwiseUnaryOps.h" +# include "../plugins/ArrayCwiseUnaryOps.h" +# include "../plugins/CommonCwiseBinaryOps.h" +# include "../plugins/MatrixCwiseBinaryOps.h" +# include "../plugins/ArrayCwiseBinaryOps.h" +# ifdef EIGEN_ARRAYBASE_PLUGIN +# include EIGEN_ARRAYBASE_PLUGIN +# endif +#undef EIGEN_CURRENT_STORAGE_BASE_CLASS +#undef EIGEN_DOC_UNARY_ADDONS + + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const ArrayBase& other) + { + internal::call_assignment(derived(), other.derived()); + return derived(); + } + + /** Set all the entries to \a value. + * \sa DenseBase::setConstant(), DenseBase::fill() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const Scalar &value) + { Base::setConstant(value); return derived(); } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator+=(const Scalar& scalar); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator-=(const Scalar& scalar); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator+=(const ArrayBase& other); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator-=(const ArrayBase& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator*=(const ArrayBase& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator/=(const ArrayBase& other); + + public: + EIGEN_DEVICE_FUNC + ArrayBase& array() { return *this; } + EIGEN_DEVICE_FUNC + const ArrayBase& array() const { return *this; } + + /** \returns an \link Eigen::MatrixBase Matrix \endlink expression of this array + * \sa MatrixBase::array() */ + EIGEN_DEVICE_FUNC + MatrixWrapper matrix() { return MatrixWrapper(derived()); } + EIGEN_DEVICE_FUNC + const MatrixWrapper matrix() const { return MatrixWrapper(derived()); } + +// template +// inline void evalTo(Dest& dst) const { dst = matrix(); } + + protected: + EIGEN_DEVICE_FUNC + ArrayBase() : Base() {} + + private: + explicit ArrayBase(Index); + ArrayBase(Index,Index); + template explicit ArrayBase(const ArrayBase&); + protected: + // mixing arrays and matrices is not legal + template Derived& operator+=(const MatrixBase& ) + {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} + // mixing arrays and matrices is not legal + template Derived& operator-=(const MatrixBase& ) + {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} +}; + +/** replaces \c *this by \c *this - \a other. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & +ArrayBase::operator-=(const ArrayBase &other) +{ + call_assignment(derived(), other.derived(), internal::sub_assign_op()); + return derived(); +} + +/** replaces \c *this by \c *this + \a other. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & +ArrayBase::operator+=(const ArrayBase& other) +{ + call_assignment(derived(), other.derived(), internal::add_assign_op()); + return derived(); +} + +/** replaces \c *this by \c *this * \a other coefficient wise. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & +ArrayBase::operator*=(const ArrayBase& other) +{ + call_assignment(derived(), other.derived(), internal::mul_assign_op()); + return derived(); +} + +/** replaces \c *this by \c *this / \a other coefficient wise. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived & +ArrayBase::operator/=(const ArrayBase& other) +{ + call_assignment(derived(), other.derived(), internal::div_assign_op()); + return derived(); +} + +} // end namespace Eigen + +#endif // EIGEN_ARRAYBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayWrapper.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayWrapper.h new file mode 100644 index 0000000000000000000000000000000000000000..688aadd6260a8839951f3d383d2dd9652716fa5b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ArrayWrapper.h @@ -0,0 +1,209 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ARRAYWRAPPER_H +#define EIGEN_ARRAYWRAPPER_H + +namespace Eigen { + +/** \class ArrayWrapper + * \ingroup Core_Module + * + * \brief Expression of a mathematical vector or matrix as an array object + * + * This class is the return type of MatrixBase::array(), and most of the time + * this is the only way it is use. + * + * \sa MatrixBase::array(), class MatrixWrapper + */ + +namespace internal { +template +struct traits > + : public traits::type > +{ + typedef ArrayXpr XprKind; + // Let's remove NestByRefBit + enum { + Flags0 = traits::type >::Flags, + LvalueBitFlag = is_lvalue::value ? LvalueBit : 0, + Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag + }; +}; +} + +template +class ArrayWrapper : public ArrayBase > +{ + public: + typedef ArrayBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ArrayWrapper) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(ArrayWrapper) + typedef typename internal::remove_all::type NestedExpression; + + typedef typename internal::conditional< + internal::is_lvalue::value, + Scalar, + const Scalar + >::type ScalarWithConstIfNotLvalue; + + typedef typename internal::ref_selector::non_const_type NestedExpressionType; + + using Base::coeffRef; + + EIGEN_DEVICE_FUNC + explicit EIGEN_STRONG_INLINE ArrayWrapper(ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC + inline Index rows() const { return m_expression.rows(); } + EIGEN_DEVICE_FUNC + inline Index cols() const { return m_expression.cols(); } + EIGEN_DEVICE_FUNC + inline Index outerStride() const { return m_expression.outerStride(); } + EIGEN_DEVICE_FUNC + inline Index innerStride() const { return m_expression.innerStride(); } + + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } + EIGEN_DEVICE_FUNC + inline const Scalar* data() const { return m_expression.data(); } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index rowId, Index colId) const + { + return m_expression.coeffRef(rowId, colId); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index index) const + { + return m_expression.coeffRef(index); + } + + template + EIGEN_DEVICE_FUNC + inline void evalTo(Dest& dst) const { dst = m_expression; } + + const typename internal::remove_all::type& + EIGEN_DEVICE_FUNC + nestedExpression() const + { + return m_expression; + } + + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index) */ + EIGEN_DEVICE_FUNC + void resize(Index newSize) { m_expression.resize(newSize); } + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index,Index)*/ + EIGEN_DEVICE_FUNC + void resize(Index rows, Index cols) { m_expression.resize(rows,cols); } + + protected: + NestedExpressionType m_expression; +}; + +/** \class MatrixWrapper + * \ingroup Core_Module + * + * \brief Expression of an array as a mathematical vector or matrix + * + * This class is the return type of ArrayBase::matrix(), and most of the time + * this is the only way it is use. + * + * \sa MatrixBase::matrix(), class ArrayWrapper + */ + +namespace internal { +template +struct traits > + : public traits::type > +{ + typedef MatrixXpr XprKind; + // Let's remove NestByRefBit + enum { + Flags0 = traits::type >::Flags, + LvalueBitFlag = is_lvalue::value ? LvalueBit : 0, + Flags = (Flags0 & ~(NestByRefBit | LvalueBit)) | LvalueBitFlag + }; +}; +} + +template +class MatrixWrapper : public MatrixBase > +{ + public: + typedef MatrixBase > Base; + EIGEN_DENSE_PUBLIC_INTERFACE(MatrixWrapper) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(MatrixWrapper) + typedef typename internal::remove_all::type NestedExpression; + + typedef typename internal::conditional< + internal::is_lvalue::value, + Scalar, + const Scalar + >::type ScalarWithConstIfNotLvalue; + + typedef typename internal::ref_selector::non_const_type NestedExpressionType; + + using Base::coeffRef; + + EIGEN_DEVICE_FUNC + explicit inline MatrixWrapper(ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC + inline Index rows() const { return m_expression.rows(); } + EIGEN_DEVICE_FUNC + inline Index cols() const { return m_expression.cols(); } + EIGEN_DEVICE_FUNC + inline Index outerStride() const { return m_expression.outerStride(); } + EIGEN_DEVICE_FUNC + inline Index innerStride() const { return m_expression.innerStride(); } + + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue* data() { return m_expression.data(); } + EIGEN_DEVICE_FUNC + inline const Scalar* data() const { return m_expression.data(); } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index rowId, Index colId) const + { + return m_expression.derived().coeffRef(rowId, colId); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index index) const + { + return m_expression.coeffRef(index); + } + + EIGEN_DEVICE_FUNC + const typename internal::remove_all::type& + nestedExpression() const + { + return m_expression; + } + + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index) */ + EIGEN_DEVICE_FUNC + void resize(Index newSize) { m_expression.resize(newSize); } + /** Forwards the resizing request to the nested expression + * \sa DenseBase::resize(Index,Index)*/ + EIGEN_DEVICE_FUNC + void resize(Index rows, Index cols) { m_expression.resize(rows,cols); } + + protected: + NestedExpressionType m_expression; +}; + +} // end namespace Eigen + +#endif // EIGEN_ARRAYWRAPPER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign.h new file mode 100644 index 0000000000000000000000000000000000000000..53806ba33c4abbfb38162c3e6bd25993fe30132f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign.h @@ -0,0 +1,90 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2007 Michael Olbrich +// Copyright (C) 2006-2010 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ASSIGN_H +#define EIGEN_ASSIGN_H + +namespace Eigen { + +template +template +EIGEN_STRONG_INLINE Derived& DenseBase + ::lazyAssign(const DenseBase& other) +{ + enum{ + SameType = internal::is_same::value + }; + + EIGEN_STATIC_ASSERT_LVALUE(Derived) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Derived,OtherDerived) + EIGEN_STATIC_ASSERT(SameType,YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY) + + eigen_assert(rows() == other.rows() && cols() == other.cols()); + internal::call_assignment_no_alias(derived(),other.derived()); + + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) +{ + internal::call_assignment(derived(), other.derived()); + return derived(); +} + +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& DenseBase::operator=(const DenseBase& other) +{ + internal::call_assignment(derived(), other.derived()); + return derived(); +} + +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const MatrixBase& other) +{ + internal::call_assignment(derived(), other.derived()); + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const DenseBase& other) +{ + internal::call_assignment(derived(), other.derived()); + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const EigenBase& other) +{ + internal::call_assignment(derived(), other.derived()); + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE Derived& MatrixBase::operator=(const ReturnByValue& other) +{ + other.derived().evalTo(derived()); + return derived(); +} + +} // end namespace Eigen + +#endif // EIGEN_ASSIGN_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/AssignEvaluator.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/AssignEvaluator.h new file mode 100644 index 0000000000000000000000000000000000000000..dbe435d86b376dd1099451715686b2123759a553 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/AssignEvaluator.h @@ -0,0 +1,935 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Benoit Jacob +// Copyright (C) 2011-2014 Gael Guennebaud +// Copyright (C) 2011-2012 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ASSIGN_EVALUATOR_H +#define EIGEN_ASSIGN_EVALUATOR_H + +namespace Eigen { + +// This implementation is based on Assign.h + +namespace internal { + +/*************************************************************************** +* Part 1 : the logic deciding a strategy for traversal and unrolling * +***************************************************************************/ + +// copy_using_evaluator_traits is based on assign_traits + +template +struct copy_using_evaluator_traits +{ + typedef typename DstEvaluator::XprType Dst; + typedef typename Dst::Scalar DstScalar; + + enum { + DstFlags = DstEvaluator::Flags, + SrcFlags = SrcEvaluator::Flags + }; + +public: + enum { + DstAlignment = DstEvaluator::Alignment, + SrcAlignment = SrcEvaluator::Alignment, + DstHasDirectAccess = (DstFlags & DirectAccessBit) == DirectAccessBit, + JointAlignment = EIGEN_PLAIN_ENUM_MIN(DstAlignment,SrcAlignment) + }; + +private: + enum { + InnerSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::SizeAtCompileTime) + : int(DstFlags)&RowMajorBit ? int(Dst::ColsAtCompileTime) + : int(Dst::RowsAtCompileTime), + InnerMaxSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::MaxSizeAtCompileTime) + : int(DstFlags)&RowMajorBit ? int(Dst::MaxColsAtCompileTime) + : int(Dst::MaxRowsAtCompileTime), + OuterStride = int(outer_stride_at_compile_time::ret), + MaxSizeAtCompileTime = Dst::SizeAtCompileTime + }; + + // TODO distinguish between linear traversal and inner-traversals + typedef typename find_best_packet::type LinearPacketType; + typedef typename find_best_packet::type InnerPacketType; + + enum { + LinearPacketSize = unpacket_traits::size, + InnerPacketSize = unpacket_traits::size + }; + +public: + enum { + LinearRequiredAlignment = unpacket_traits::alignment, + InnerRequiredAlignment = unpacket_traits::alignment + }; + +private: + enum { + DstIsRowMajor = DstFlags&RowMajorBit, + SrcIsRowMajor = SrcFlags&RowMajorBit, + StorageOrdersAgree = (int(DstIsRowMajor) == int(SrcIsRowMajor)), + MightVectorize = bool(StorageOrdersAgree) + && (int(DstFlags) & int(SrcFlags) & ActualPacketAccessBit) + && bool(functor_traits::PacketAccess), + MayInnerVectorize = MightVectorize + && int(InnerSize)!=Dynamic && int(InnerSize)%int(InnerPacketSize)==0 + && int(OuterStride)!=Dynamic && int(OuterStride)%int(InnerPacketSize)==0 + && (EIGEN_UNALIGNED_VECTORIZE || int(JointAlignment)>=int(InnerRequiredAlignment)), + MayLinearize = bool(StorageOrdersAgree) && (int(DstFlags) & int(SrcFlags) & LinearAccessBit), + MayLinearVectorize = bool(MightVectorize) && bool(MayLinearize) && bool(DstHasDirectAccess) + && (EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment)>=int(LinearRequiredAlignment)) || MaxSizeAtCompileTime == Dynamic), + /* If the destination isn't aligned, we have to do runtime checks and we don't unroll, + so it's only good for large enough sizes. */ + MaySliceVectorize = bool(MightVectorize) && bool(DstHasDirectAccess) + && (int(InnerMaxSize)==Dynamic || int(InnerMaxSize)>=(EIGEN_UNALIGNED_VECTORIZE?InnerPacketSize:(3*InnerPacketSize))) + /* slice vectorization can be slow, so we only want it if the slices are big, which is + indicated by InnerMaxSize rather than InnerSize, think of the case of a dynamic block + in a fixed-size matrix + However, with EIGEN_UNALIGNED_VECTORIZE and unrolling, slice vectorization is still worth it */ + }; + +public: + enum { + Traversal = int(MayLinearVectorize) && (LinearPacketSize>InnerPacketSize) ? int(LinearVectorizedTraversal) + : int(MayInnerVectorize) ? int(InnerVectorizedTraversal) + : int(MayLinearVectorize) ? int(LinearVectorizedTraversal) + : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) + : int(MayLinearize) ? int(LinearTraversal) + : int(DefaultTraversal), + Vectorized = int(Traversal) == InnerVectorizedTraversal + || int(Traversal) == LinearVectorizedTraversal + || int(Traversal) == SliceVectorizedTraversal + }; + + typedef typename conditional::type PacketType; + +private: + enum { + ActualPacketSize = int(Traversal)==LinearVectorizedTraversal ? LinearPacketSize + : Vectorized ? InnerPacketSize + : 1, + UnrollingLimit = EIGEN_UNROLLING_LIMIT * ActualPacketSize, + MayUnrollCompletely = int(Dst::SizeAtCompileTime) != Dynamic + && int(Dst::SizeAtCompileTime) * (int(DstEvaluator::CoeffReadCost)+int(SrcEvaluator::CoeffReadCost)) <= int(UnrollingLimit), + MayUnrollInner = int(InnerSize) != Dynamic + && int(InnerSize) * (int(DstEvaluator::CoeffReadCost)+int(SrcEvaluator::CoeffReadCost)) <= int(UnrollingLimit) + }; + +public: + enum { + Unrolling = (int(Traversal) == int(InnerVectorizedTraversal) || int(Traversal) == int(DefaultTraversal)) + ? ( + int(MayUnrollCompletely) ? int(CompleteUnrolling) + : int(MayUnrollInner) ? int(InnerUnrolling) + : int(NoUnrolling) + ) + : int(Traversal) == int(LinearVectorizedTraversal) + ? ( bool(MayUnrollCompletely) && ( EIGEN_UNALIGNED_VECTORIZE || (int(DstAlignment)>=int(LinearRequiredAlignment))) + ? int(CompleteUnrolling) + : int(NoUnrolling) ) + : int(Traversal) == int(LinearTraversal) + ? ( bool(MayUnrollCompletely) ? int(CompleteUnrolling) + : int(NoUnrolling) ) +#if EIGEN_UNALIGNED_VECTORIZE + : int(Traversal) == int(SliceVectorizedTraversal) + ? ( bool(MayUnrollInner) ? int(InnerUnrolling) + : int(NoUnrolling) ) +#endif + : int(NoUnrolling) + }; + +#ifdef EIGEN_DEBUG_ASSIGN + static void debug() + { + std::cerr << "DstXpr: " << typeid(typename DstEvaluator::XprType).name() << std::endl; + std::cerr << "SrcXpr: " << typeid(typename SrcEvaluator::XprType).name() << std::endl; + std::cerr.setf(std::ios::hex, std::ios::basefield); + std::cerr << "DstFlags" << " = " << DstFlags << " (" << demangle_flags(DstFlags) << " )" << std::endl; + std::cerr << "SrcFlags" << " = " << SrcFlags << " (" << demangle_flags(SrcFlags) << " )" << std::endl; + std::cerr.unsetf(std::ios::hex); + EIGEN_DEBUG_VAR(DstAlignment) + EIGEN_DEBUG_VAR(SrcAlignment) + EIGEN_DEBUG_VAR(LinearRequiredAlignment) + EIGEN_DEBUG_VAR(InnerRequiredAlignment) + EIGEN_DEBUG_VAR(JointAlignment) + EIGEN_DEBUG_VAR(InnerSize) + EIGEN_DEBUG_VAR(InnerMaxSize) + EIGEN_DEBUG_VAR(LinearPacketSize) + EIGEN_DEBUG_VAR(InnerPacketSize) + EIGEN_DEBUG_VAR(ActualPacketSize) + EIGEN_DEBUG_VAR(StorageOrdersAgree) + EIGEN_DEBUG_VAR(MightVectorize) + EIGEN_DEBUG_VAR(MayLinearize) + EIGEN_DEBUG_VAR(MayInnerVectorize) + EIGEN_DEBUG_VAR(MayLinearVectorize) + EIGEN_DEBUG_VAR(MaySliceVectorize) + std::cerr << "Traversal" << " = " << Traversal << " (" << demangle_traversal(Traversal) << ")" << std::endl; + EIGEN_DEBUG_VAR(SrcEvaluator::CoeffReadCost) + EIGEN_DEBUG_VAR(UnrollingLimit) + EIGEN_DEBUG_VAR(MayUnrollCompletely) + EIGEN_DEBUG_VAR(MayUnrollInner) + std::cerr << "Unrolling" << " = " << Unrolling << " (" << demangle_unrolling(Unrolling) << ")" << std::endl; + std::cerr << std::endl; + } +#endif +}; + +/*************************************************************************** +* Part 2 : meta-unrollers +***************************************************************************/ + +/************************ +*** Default traversal *** +************************/ + +template +struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling +{ + // FIXME: this is not very clean, perhaps this information should be provided by the kernel? + typedef typename Kernel::DstEvaluatorType DstEvaluatorType; + typedef typename DstEvaluatorType::XprType DstXprType; + + enum { + outer = Index / DstXprType::InnerSizeAtCompileTime, + inner = Index % DstXprType::InnerSizeAtCompileTime + }; + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + kernel.assignCoeffByOuterInner(outer, inner); + copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); + } +}; + +template +struct copy_using_evaluator_DefaultTraversal_CompleteUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +}; + +template +struct copy_using_evaluator_DefaultTraversal_InnerUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, Index outer) + { + kernel.assignCoeffByOuterInner(outer, Index_); + copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); + } +}; + +template +struct copy_using_evaluator_DefaultTraversal_InnerUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index) { } +}; + +/*********************** +*** Linear traversal *** +***********************/ + +template +struct copy_using_evaluator_LinearTraversal_CompleteUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel& kernel) + { + kernel.assignCoeff(Index); + copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); + } +}; + +template +struct copy_using_evaluator_LinearTraversal_CompleteUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +}; + +/************************** +*** Inner vectorization *** +**************************/ + +template +struct copy_using_evaluator_innervec_CompleteUnrolling +{ + // FIXME: this is not very clean, perhaps this information should be provided by the kernel? + typedef typename Kernel::DstEvaluatorType DstEvaluatorType; + typedef typename DstEvaluatorType::XprType DstXprType; + typedef typename Kernel::PacketType PacketType; + + enum { + outer = Index / DstXprType::InnerSizeAtCompileTime, + inner = Index % DstXprType::InnerSizeAtCompileTime, + SrcAlignment = Kernel::AssignmentTraits::SrcAlignment, + DstAlignment = Kernel::AssignmentTraits::DstAlignment + }; + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + kernel.template assignPacketByOuterInner(outer, inner); + enum { NextIndex = Index + unpacket_traits::size }; + copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); + } +}; + +template +struct copy_using_evaluator_innervec_CompleteUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&) { } +}; + +template +struct copy_using_evaluator_innervec_InnerUnrolling +{ + typedef typename Kernel::PacketType PacketType; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, Index outer) + { + kernel.template assignPacketByOuterInner(outer, Index_); + enum { NextIndex = Index_ + unpacket_traits::size }; + copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); + } +}; + +template +struct copy_using_evaluator_innervec_InnerUnrolling +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &, Index) { } +}; + +/*************************************************************************** +* Part 3 : implementation of all cases +***************************************************************************/ + +// dense_assignment_loop is based on assign_impl + +template +struct dense_assignment_loop; + +/************************ +*** Default traversal *** +************************/ + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static void EIGEN_STRONG_INLINE run(Kernel &kernel) + { + for(Index outer = 0; outer < kernel.outerSize(); ++outer) { + for(Index inner = 0; inner < kernel.innerSize(); ++inner) { + kernel.assignCoeffByOuterInner(outer, inner); + } + } + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + + const Index outerSize = kernel.outerSize(); + for(Index outer = 0; outer < outerSize; ++outer) + copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); + } +}; + +/*************************** +*** Linear vectorization *** +***************************/ + + +// The goal of unaligned_dense_assignment_loop is simply to factorize the handling +// of the non vectorizable beginning and ending parts + +template +struct unaligned_dense_assignment_loop +{ + // if IsAligned = true, then do nothing + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel&, Index, Index) {} +}; + +template <> +struct unaligned_dense_assignment_loop +{ + // MSVC must not inline this functions. If it does, it fails to optimize the + // packet access path. + // FIXME check which version exhibits this issue +#if EIGEN_COMP_MSVC + template + static EIGEN_DONT_INLINE void run(Kernel &kernel, + Index start, + Index end) +#else + template + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel, + Index start, + Index end) +#endif + { + for (Index index = start; index < end; ++index) + kernel.assignCoeff(index); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + const Index size = kernel.size(); + typedef typename Kernel::Scalar Scalar; + typedef typename Kernel::PacketType PacketType; + enum { + requestedAlignment = Kernel::AssignmentTraits::LinearRequiredAlignment, + packetSize = unpacket_traits::size, + dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment)>=int(requestedAlignment), + dstAlignment = packet_traits::AlignedOnScalar ? int(requestedAlignment) + : int(Kernel::AssignmentTraits::DstAlignment), + srcAlignment = Kernel::AssignmentTraits::JointAlignment + }; + const Index alignedStart = dstIsAligned ? 0 : internal::first_aligned(kernel.dstDataPtr(), size); + const Index alignedEnd = alignedStart + ((size-alignedStart)/packetSize)*packetSize; + + unaligned_dense_assignment_loop::run(kernel, 0, alignedStart); + + for(Index index = alignedStart; index < alignedEnd; index += packetSize) + kernel.template assignPacket(index); + + unaligned_dense_assignment_loop<>::run(kernel, alignedEnd, size); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + typedef typename Kernel::PacketType PacketType; + + enum { size = DstXprType::SizeAtCompileTime, + packetSize =unpacket_traits::size, + alignedSize = (size/packetSize)*packetSize }; + + copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); + copy_using_evaluator_DefaultTraversal_CompleteUnrolling::run(kernel); + } +}; + +/************************** +*** Inner vectorization *** +**************************/ + +template +struct dense_assignment_loop +{ + typedef typename Kernel::PacketType PacketType; + enum { + SrcAlignment = Kernel::AssignmentTraits::SrcAlignment, + DstAlignment = Kernel::AssignmentTraits::DstAlignment + }; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + const Index innerSize = kernel.innerSize(); + const Index outerSize = kernel.outerSize(); + const Index packetSize = unpacket_traits::size; + for(Index outer = 0; outer < outerSize; ++outer) + for(Index inner = 0; inner < innerSize; inner+=packetSize) + kernel.template assignPacketByOuterInner(outer, inner); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + copy_using_evaluator_innervec_CompleteUnrolling::run(kernel); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + typedef typename Kernel::AssignmentTraits Traits; + const Index outerSize = kernel.outerSize(); + for(Index outer = 0; outer < outerSize; ++outer) + copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); + } +}; + +/*********************** +*** Linear traversal *** +***********************/ + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + const Index size = kernel.size(); + for(Index i = 0; i < size; ++i) + kernel.assignCoeff(i); + } +}; + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + copy_using_evaluator_LinearTraversal_CompleteUnrolling::run(kernel); + } +}; + +/************************** +*** Slice vectorization *** +***************************/ + +template +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::Scalar Scalar; + typedef typename Kernel::PacketType PacketType; + enum { + packetSize = unpacket_traits::size, + requestedAlignment = int(Kernel::AssignmentTraits::InnerRequiredAlignment), + alignable = packet_traits::AlignedOnScalar || int(Kernel::AssignmentTraits::DstAlignment)>=sizeof(Scalar), + dstIsAligned = int(Kernel::AssignmentTraits::DstAlignment)>=int(requestedAlignment), + dstAlignment = alignable ? int(requestedAlignment) + : int(Kernel::AssignmentTraits::DstAlignment) + }; + const Scalar *dst_ptr = kernel.dstDataPtr(); + if((!bool(dstIsAligned)) && (UIntPtr(dst_ptr) % sizeof(Scalar))>0) + { + // the pointer is not aligend-on scalar, so alignment is not possible + return dense_assignment_loop::run(kernel); + } + const Index packetAlignedMask = packetSize - 1; + const Index innerSize = kernel.innerSize(); + const Index outerSize = kernel.outerSize(); + const Index alignedStep = alignable ? (packetSize - kernel.outerStride() % packetSize) & packetAlignedMask : 0; + Index alignedStart = ((!alignable) || bool(dstIsAligned)) ? 0 : internal::first_aligned(dst_ptr, innerSize); + + for(Index outer = 0; outer < outerSize; ++outer) + { + const Index alignedEnd = alignedStart + ((innerSize-alignedStart) & ~packetAlignedMask); + // do the non-vectorizable part of the assignment + for(Index inner = 0; inner(outer, inner); + + // do the non-vectorizable part of the assignment + for(Index inner = alignedEnd; inner +struct dense_assignment_loop +{ + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE void run(Kernel &kernel) + { + typedef typename Kernel::DstEvaluatorType::XprType DstXprType; + typedef typename Kernel::PacketType PacketType; + + enum { size = DstXprType::InnerSizeAtCompileTime, + packetSize =unpacket_traits::size, + vectorizableSize = (size/packetSize)*packetSize }; + + for(Index outer = 0; outer < kernel.outerSize(); ++outer) + { + copy_using_evaluator_innervec_InnerUnrolling::run(kernel, outer); + copy_using_evaluator_DefaultTraversal_InnerUnrolling::run(kernel, outer); + } + } +}; +#endif + + +/*************************************************************************** +* Part 4 : Generic dense assignment kernel +***************************************************************************/ + +// This class generalize the assignment of a coefficient (or packet) from one dense evaluator +// to another dense writable evaluator. +// It is parametrized by the two evaluators, and the actual assignment functor. +// This abstraction level permits to keep the evaluation loops as simple and as generic as possible. +// One can customize the assignment using this generic dense_assignment_kernel with different +// functors, or by completely overloading it, by-passing a functor. +template +class generic_dense_assignment_kernel +{ +protected: + typedef typename DstEvaluatorTypeT::XprType DstXprType; + typedef typename SrcEvaluatorTypeT::XprType SrcXprType; +public: + + typedef DstEvaluatorTypeT DstEvaluatorType; + typedef SrcEvaluatorTypeT SrcEvaluatorType; + typedef typename DstEvaluatorType::Scalar Scalar; + typedef copy_using_evaluator_traits AssignmentTraits; + typedef typename AssignmentTraits::PacketType PacketType; + + + EIGEN_DEVICE_FUNC generic_dense_assignment_kernel(DstEvaluatorType &dst, const SrcEvaluatorType &src, const Functor &func, DstXprType& dstExpr) + : m_dst(dst), m_src(src), m_functor(func), m_dstExpr(dstExpr) + { + #ifdef EIGEN_DEBUG_ASSIGN + AssignmentTraits::debug(); + #endif + } + + EIGEN_DEVICE_FUNC Index size() const { return m_dstExpr.size(); } + EIGEN_DEVICE_FUNC Index innerSize() const { return m_dstExpr.innerSize(); } + EIGEN_DEVICE_FUNC Index outerSize() const { return m_dstExpr.outerSize(); } + EIGEN_DEVICE_FUNC Index rows() const { return m_dstExpr.rows(); } + EIGEN_DEVICE_FUNC Index cols() const { return m_dstExpr.cols(); } + EIGEN_DEVICE_FUNC Index outerStride() const { return m_dstExpr.outerStride(); } + + EIGEN_DEVICE_FUNC DstEvaluatorType& dstEvaluator() { return m_dst; } + EIGEN_DEVICE_FUNC const SrcEvaluatorType& srcEvaluator() const { return m_src; } + + /// Assign src(row,col) to dst(row,col) through the assignment functor. + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index row, Index col) + { + m_functor.assignCoeff(m_dst.coeffRef(row,col), m_src.coeff(row,col)); + } + + /// \sa assignCoeff(Index,Index) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeff(Index index) + { + m_functor.assignCoeff(m_dst.coeffRef(index), m_src.coeff(index)); + } + + /// \sa assignCoeff(Index,Index) + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignCoeffByOuterInner(Index outer, Index inner) + { + Index row = rowIndexByOuterInner(outer, inner); + Index col = colIndexByOuterInner(outer, inner); + assignCoeff(row, col); + } + + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index row, Index col) + { + m_functor.template assignPacket(&m_dst.coeffRef(row,col), m_src.template packet(row,col)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacket(Index index) + { + m_functor.template assignPacket(&m_dst.coeffRef(index), m_src.template packet(index)); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void assignPacketByOuterInner(Index outer, Index inner) + { + Index row = rowIndexByOuterInner(outer, inner); + Index col = colIndexByOuterInner(outer, inner); + assignPacket(row, col); + } + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) + { + typedef typename DstEvaluatorType::ExpressionTraits Traits; + return int(Traits::RowsAtCompileTime) == 1 ? 0 + : int(Traits::ColsAtCompileTime) == 1 ? inner + : int(DstEvaluatorType::Flags)&RowMajorBit ? outer + : inner; + } + + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) + { + typedef typename DstEvaluatorType::ExpressionTraits Traits; + return int(Traits::ColsAtCompileTime) == 1 ? 0 + : int(Traits::RowsAtCompileTime) == 1 ? inner + : int(DstEvaluatorType::Flags)&RowMajorBit ? inner + : outer; + } + + EIGEN_DEVICE_FUNC const Scalar* dstDataPtr() const + { + return m_dstExpr.data(); + } + +protected: + DstEvaluatorType& m_dst; + const SrcEvaluatorType& m_src; + const Functor &m_functor; + // TODO find a way to avoid the needs of the original expression + DstXprType& m_dstExpr; +}; + +/*************************************************************************** +* Part 5 : Entry point for dense rectangular assignment +***************************************************************************/ + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void resize_if_allowed(DstXprType &dst, const SrcXprType& src, const Functor &/*func*/) +{ + EIGEN_ONLY_USED_FOR_DEBUG(dst); + EIGEN_ONLY_USED_FOR_DEBUG(src); + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void resize_if_allowed(DstXprType &dst, const SrcXprType& src, const internal::assign_op &/*func*/) +{ + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if(((dst.rows()!=dstRows) || (dst.cols()!=dstCols))) + dst.resize(dstRows, dstCols); + eigen_assert(dst.rows() == dstRows && dst.cols() == dstCols); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src, const Functor &func) +{ + typedef evaluator DstEvaluatorType; + typedef evaluator SrcEvaluatorType; + + SrcEvaluatorType srcEvaluator(src); + + // NOTE To properly handle A = (A*A.transpose())/s with A rectangular, + // we need to resize the destination after the source evaluator has been created. + resize_if_allowed(dst, src, func); + + DstEvaluatorType dstEvaluator(dst); + + typedef generic_dense_assignment_kernel Kernel; + Kernel kernel(dstEvaluator, srcEvaluator, func, dst.const_cast_derived()); + + dense_assignment_loop::run(kernel); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void call_dense_assignment_loop(DstXprType& dst, const SrcXprType& src) +{ + call_dense_assignment_loop(dst, src, internal::assign_op()); +} + +/*************************************************************************** +* Part 6 : Generic assignment +***************************************************************************/ + +// Based on the respective shapes of the destination and source, +// the class AssignmentKind determine the kind of assignment mechanism. +// AssignmentKind must define a Kind typedef. +template struct AssignmentKind; + +// Assignement kind defined in this file: +struct Dense2Dense {}; +struct EigenBase2EigenBase {}; + +template struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; +template<> struct AssignmentKind { typedef Dense2Dense Kind; }; + +// This is the main assignment class +template< typename DstXprType, typename SrcXprType, typename Functor, + typename Kind = typename AssignmentKind< typename evaluator_traits::Shape , typename evaluator_traits::Shape >::Kind, + typename EnableIf = void> +struct Assignment; + + +// The only purpose of this call_assignment() function is to deal with noalias() / "assume-aliasing" and automatic transposition. +// Indeed, I (Gael) think that this concept of "assume-aliasing" was a mistake, and it makes thing quite complicated. +// So this intermediate function removes everything related to "assume-aliasing" such that Assignment +// does not has to bother about these annoying details. + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment(Dst& dst, const Src& src) +{ + call_assignment(dst, src, internal::assign_op()); +} +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment(const Dst& dst, const Src& src) +{ + call_assignment(dst, src, internal::assign_op()); +} + +// Deal with "assume-aliasing" +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment(Dst& dst, const Src& src, const Func& func, typename enable_if< evaluator_assume_aliasing::value, void*>::type = 0) +{ + typename plain_matrix_type::type tmp(src); + call_assignment_no_alias(dst, tmp, func); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment(Dst& dst, const Src& src, const Func& func, typename enable_if::value, void*>::type = 0) +{ + call_assignment_no_alias(dst, src, func); +} + +// by-pass "assume-aliasing" +// When there is no aliasing, we require that 'dst' has been properly resized +template class StorageBase, typename Src, typename Func> +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment(NoAlias& dst, const Src& src, const Func& func) +{ + call_assignment_no_alias(dst.expression(), src, func); +} + + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment_no_alias(Dst& dst, const Src& src, const Func& func) +{ + enum { + NeedToTranspose = ( (int(Dst::RowsAtCompileTime) == 1 && int(Src::ColsAtCompileTime) == 1) + || (int(Dst::ColsAtCompileTime) == 1 && int(Src::RowsAtCompileTime) == 1) + ) && int(Dst::SizeAtCompileTime) != 1 + }; + + typedef typename internal::conditional, Dst>::type ActualDstTypeCleaned; + typedef typename internal::conditional, Dst&>::type ActualDstType; + ActualDstType actualDst(dst); + + // TODO check whether this is the right place to perform these checks: + EIGEN_STATIC_ASSERT_LVALUE(Dst) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(ActualDstTypeCleaned,Src) + EIGEN_CHECK_BINARY_COMPATIBILIY(Func,typename ActualDstTypeCleaned::Scalar,typename Src::Scalar); + + Assignment::run(actualDst, src, func); +} +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment_no_alias(Dst& dst, const Src& src) +{ + call_assignment_no_alias(dst, src, internal::assign_op()); +} + +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment_no_alias_no_transpose(Dst& dst, const Src& src, const Func& func) +{ + // TODO check whether this is the right place to perform these checks: + EIGEN_STATIC_ASSERT_LVALUE(Dst) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Dst,Src) + EIGEN_CHECK_BINARY_COMPATIBILIY(Func,typename Dst::Scalar,typename Src::Scalar); + + Assignment::run(dst, src, func); +} +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE +void call_assignment_no_alias_no_transpose(Dst& dst, const Src& src) +{ + call_assignment_no_alias_no_transpose(dst, src, internal::assign_op()); +} + +// forward declaration +template void check_for_aliasing(const Dst &dst, const Src &src); + +// Generic Dense to Dense assignment +// Note that the last template argument "Weak" is needed to make it possible to perform +// both partial specialization+SFINAE without ambiguous specialization +template< typename DstXprType, typename SrcXprType, typename Functor, typename Weak> +struct Assignment +{ + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const Functor &func) + { +#ifndef EIGEN_NO_DEBUG + internal::check_for_aliasing(dst, src); +#endif + + call_dense_assignment_loop(dst, src, func); + } +}; + +// Generic assignment through evalTo. +// TODO: not sure we have to keep that one, but it helps porting current code to new evaluator mechanism. +// Note that the last template argument "Weak" is needed to make it possible to perform +// both partial specialization+SFINAE without ambiguous specialization +template< typename DstXprType, typename SrcXprType, typename Functor, typename Weak> +struct Assignment +{ + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &/*func*/) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); + src.evalTo(dst); + } + + // NOTE The following two functions are templated to avoid their instanciation if not needed + // This is needed because some expressions supports evalTo only and/or have 'void' as scalar type. + template + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &/*func*/) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); + src.addTo(dst); + } + + template + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &/*func*/) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); + src.subTo(dst); + } +}; + +} // namespace internal + +} // end namespace Eigen + +#endif // EIGEN_ASSIGN_EVALUATOR_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign_MKL.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign_MKL.h new file mode 100644 index 0000000000000000000000000000000000000000..6866095bf8a47a3a00f5dc558cca10f8caa3830c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Assign_MKL.h @@ -0,0 +1,178 @@ +/* + Copyright (c) 2011, Intel Corporation. All rights reserved. + Copyright (C) 2015 Gael Guennebaud + + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ******************************************************************************** + * Content : Eigen bindings to Intel(R) MKL + * MKL VML support for coefficient-wise unary Eigen expressions like a=b.sin() + ******************************************************************************** +*/ + +#ifndef EIGEN_ASSIGN_VML_H +#define EIGEN_ASSIGN_VML_H + +namespace Eigen { + +namespace internal { + +template +class vml_assign_traits +{ + private: + enum { + DstHasDirectAccess = Dst::Flags & DirectAccessBit, + SrcHasDirectAccess = Src::Flags & DirectAccessBit, + StorageOrdersAgree = (int(Dst::IsRowMajor) == int(Src::IsRowMajor)), + InnerSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::SizeAtCompileTime) + : int(Dst::Flags)&RowMajorBit ? int(Dst::ColsAtCompileTime) + : int(Dst::RowsAtCompileTime), + InnerMaxSize = int(Dst::IsVectorAtCompileTime) ? int(Dst::MaxSizeAtCompileTime) + : int(Dst::Flags)&RowMajorBit ? int(Dst::MaxColsAtCompileTime) + : int(Dst::MaxRowsAtCompileTime), + MaxSizeAtCompileTime = Dst::SizeAtCompileTime, + + MightEnableVml = StorageOrdersAgree && DstHasDirectAccess && SrcHasDirectAccess && Src::InnerStrideAtCompileTime==1 && Dst::InnerStrideAtCompileTime==1, + MightLinearize = MightEnableVml && (int(Dst::Flags) & int(Src::Flags) & LinearAccessBit), + VmlSize = MightLinearize ? MaxSizeAtCompileTime : InnerMaxSize, + LargeEnough = VmlSize==Dynamic || VmlSize>=EIGEN_MKL_VML_THRESHOLD + }; + public: + enum { + EnableVml = MightEnableVml && LargeEnough, + Traversal = MightLinearize ? LinearTraversal : DefaultTraversal + }; +}; + +#define EIGEN_PP_EXPAND(ARG) ARG +#if !defined (EIGEN_FAST_MATH) || (EIGEN_FAST_MATH != 1) +#define EIGEN_VMLMODE_EXPAND_LA , VML_HA +#else +#define EIGEN_VMLMODE_EXPAND_LA , VML_LA +#endif + +#define EIGEN_VMLMODE_EXPAND__ + +#define EIGEN_VMLMODE_PREFIX_LA vm +#define EIGEN_VMLMODE_PREFIX__ v +#define EIGEN_VMLMODE_PREFIX(VMLMODE) EIGEN_CAT(EIGEN_VMLMODE_PREFIX_,VMLMODE) + +#define EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, VMLOP, EIGENTYPE, VMLTYPE, VMLMODE) \ + template< typename DstXprType, typename SrcXprNested> \ + struct Assignment, SrcXprNested>, assign_op, \ + Dense2Dense, typename enable_if::EnableVml>::type> { \ + typedef CwiseUnaryOp, SrcXprNested> SrcXprType; \ + static void run(DstXprType &dst, const SrcXprType &src, const assign_op &func) { \ + resize_if_allowed(dst, src, func); \ + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); \ + if(vml_assign_traits::Traversal==LinearTraversal) { \ + VMLOP(dst.size(), (const VMLTYPE*)src.nestedExpression().data(), \ + (VMLTYPE*)dst.data() EIGEN_PP_EXPAND(EIGEN_VMLMODE_EXPAND_##VMLMODE) ); \ + } else { \ + const Index outerSize = dst.outerSize(); \ + for(Index outer = 0; outer < outerSize; ++outer) { \ + const EIGENTYPE *src_ptr = src.IsRowMajor ? &(src.nestedExpression().coeffRef(outer,0)) : \ + &(src.nestedExpression().coeffRef(0, outer)); \ + EIGENTYPE *dst_ptr = dst.IsRowMajor ? &(dst.coeffRef(outer,0)) : &(dst.coeffRef(0, outer)); \ + VMLOP( dst.innerSize(), (const VMLTYPE*)src_ptr, \ + (VMLTYPE*)dst_ptr EIGEN_PP_EXPAND(EIGEN_VMLMODE_EXPAND_##VMLMODE)); \ + } \ + } \ + } \ + }; \ + + +#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(EIGENOP, VMLOP, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, EIGEN_CAT(EIGEN_VMLMODE_PREFIX(VMLMODE),s##VMLOP), float, float, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, EIGEN_CAT(EIGEN_VMLMODE_PREFIX(VMLMODE),d##VMLOP), double, double, VMLMODE) + +#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS_CPLX(EIGENOP, VMLOP, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, EIGEN_CAT(EIGEN_VMLMODE_PREFIX(VMLMODE),c##VMLOP), scomplex, MKL_Complex8, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALL(EIGENOP, EIGEN_CAT(EIGEN_VMLMODE_PREFIX(VMLMODE),z##VMLOP), dcomplex, MKL_Complex16, VMLMODE) + +#define EIGEN_MKL_VML_DECLARE_UNARY_CALLS(EIGENOP, VMLOP, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(EIGENOP, VMLOP, VMLMODE) \ + EIGEN_MKL_VML_DECLARE_UNARY_CALLS_CPLX(EIGENOP, VMLOP, VMLMODE) + + +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(sin, Sin, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(asin, Asin, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(sinh, Sinh, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(cos, Cos, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(acos, Acos, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(cosh, Cosh, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(tan, Tan, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(atan, Atan, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(tanh, Tanh, LA) +// EIGEN_MKL_VML_DECLARE_UNARY_CALLS(abs, Abs, _) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(exp, Exp, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(log, Ln, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(log10, Log10, LA) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS(sqrt, Sqrt, _) + +EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(square, Sqr, _) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS_CPLX(arg, Arg, _) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(round, Round, _) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(floor, Floor, _) +EIGEN_MKL_VML_DECLARE_UNARY_CALLS_REAL(ceil, Ceil, _) + +#define EIGEN_MKL_VML_DECLARE_POW_CALL(EIGENOP, VMLOP, EIGENTYPE, VMLTYPE, VMLMODE) \ + template< typename DstXprType, typename SrcXprNested, typename Plain> \ + struct Assignment, SrcXprNested, \ + const CwiseNullaryOp,Plain> >, assign_op, \ + Dense2Dense, typename enable_if::EnableVml>::type> { \ + typedef CwiseBinaryOp, SrcXprNested, \ + const CwiseNullaryOp,Plain> > SrcXprType; \ + static void run(DstXprType &dst, const SrcXprType &src, const assign_op &func) { \ + resize_if_allowed(dst, src, func); \ + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); \ + VMLTYPE exponent = reinterpret_cast(src.rhs().functor().m_other); \ + if(vml_assign_traits::Traversal==LinearTraversal) \ + { \ + VMLOP( dst.size(), (const VMLTYPE*)src.lhs().data(), exponent, \ + (VMLTYPE*)dst.data() EIGEN_PP_EXPAND(EIGEN_VMLMODE_EXPAND_##VMLMODE) ); \ + } else { \ + const Index outerSize = dst.outerSize(); \ + for(Index outer = 0; outer < outerSize; ++outer) { \ + const EIGENTYPE *src_ptr = src.IsRowMajor ? &(src.lhs().coeffRef(outer,0)) : \ + &(src.lhs().coeffRef(0, outer)); \ + EIGENTYPE *dst_ptr = dst.IsRowMajor ? &(dst.coeffRef(outer,0)) : &(dst.coeffRef(0, outer)); \ + VMLOP( dst.innerSize(), (const VMLTYPE*)src_ptr, exponent, \ + (VMLTYPE*)dst_ptr EIGEN_PP_EXPAND(EIGEN_VMLMODE_EXPAND_##VMLMODE)); \ + } \ + } \ + } \ + }; + +EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmsPowx, float, float, LA) +EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmdPowx, double, double, LA) +EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmcPowx, scomplex, MKL_Complex8, LA) +EIGEN_MKL_VML_DECLARE_POW_CALL(pow, vmzPowx, dcomplex, MKL_Complex16, LA) + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_ASSIGN_VML_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BandMatrix.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BandMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..4978c914057f41fbc12e137c3fde78791fdd9ff4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BandMatrix.h @@ -0,0 +1,353 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BANDMATRIX_H +#define EIGEN_BANDMATRIX_H + +namespace Eigen { + +namespace internal { + +template +class BandMatrixBase : public EigenBase +{ + public: + + enum { + Flags = internal::traits::Flags, + CoeffReadCost = internal::traits::CoeffReadCost, + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, + Supers = internal::traits::Supers, + Subs = internal::traits::Subs, + Options = internal::traits::Options + }; + typedef typename internal::traits::Scalar Scalar; + typedef Matrix DenseMatrixType; + typedef typename DenseMatrixType::StorageIndex StorageIndex; + typedef typename internal::traits::CoefficientsType CoefficientsType; + typedef EigenBase Base; + + protected: + enum { + DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) + ? 1 + Supers + Subs + : Dynamic, + SizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime,ColsAtCompileTime) + }; + + public: + + using Base::derived; + using Base::rows; + using Base::cols; + + /** \returns the number of super diagonals */ + inline Index supers() const { return derived().supers(); } + + /** \returns the number of sub diagonals */ + inline Index subs() const { return derived().subs(); } + + /** \returns an expression of the underlying coefficient matrix */ + inline const CoefficientsType& coeffs() const { return derived().coeffs(); } + + /** \returns an expression of the underlying coefficient matrix */ + inline CoefficientsType& coeffs() { return derived().coeffs(); } + + /** \returns a vector expression of the \a i -th column, + * only the meaningful part is returned. + * \warning the internal storage must be column major. */ + inline Block col(Index i) + { + EIGEN_STATIC_ASSERT((Options&RowMajor)==0,THIS_METHOD_IS_ONLY_FOR_COLUMN_MAJOR_MATRICES); + Index start = 0; + Index len = coeffs().rows(); + if (i<=supers()) + { + start = supers()-i; + len = (std::min)(rows(),std::max(0,coeffs().rows() - (supers()-i))); + } + else if (i>=rows()-subs()) + len = std::max(0,coeffs().rows() - (i + 1 - rows() + subs())); + return Block(coeffs(), start, i, len, 1); + } + + /** \returns a vector expression of the main diagonal */ + inline Block diagonal() + { return Block(coeffs(),supers(),0,1,(std::min)(rows(),cols())); } + + /** \returns a vector expression of the main diagonal (const version) */ + inline const Block diagonal() const + { return Block(coeffs(),supers(),0,1,(std::min)(rows(),cols())); } + + template struct DiagonalIntReturnType { + enum { + ReturnOpposite = (Options&SelfAdjoint) && (((Index)>0 && Supers==0) || ((Index)<0 && Subs==0)), + Conjugate = ReturnOpposite && NumTraits::IsComplex, + ActualIndex = ReturnOpposite ? -Index : Index, + DiagonalSize = (RowsAtCompileTime==Dynamic || ColsAtCompileTime==Dynamic) + ? Dynamic + : (ActualIndex<0 + ? EIGEN_SIZE_MIN_PREFER_DYNAMIC(ColsAtCompileTime, RowsAtCompileTime + ActualIndex) + : EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime - ActualIndex)) + }; + typedef Block BuildType; + typedef typename internal::conditional,BuildType >, + BuildType>::type Type; + }; + + /** \returns a vector expression of the \a N -th sub or super diagonal */ + template inline typename DiagonalIntReturnType::Type diagonal() + { + return typename DiagonalIntReturnType::BuildType(coeffs(), supers()-N, (std::max)(0,N), 1, diagonalLength(N)); + } + + /** \returns a vector expression of the \a N -th sub or super diagonal */ + template inline const typename DiagonalIntReturnType::Type diagonal() const + { + return typename DiagonalIntReturnType::BuildType(coeffs(), supers()-N, (std::max)(0,N), 1, diagonalLength(N)); + } + + /** \returns a vector expression of the \a i -th sub or super diagonal */ + inline Block diagonal(Index i) + { + eigen_assert((i<0 && -i<=subs()) || (i>=0 && i<=supers())); + return Block(coeffs(), supers()-i, std::max(0,i), 1, diagonalLength(i)); + } + + /** \returns a vector expression of the \a i -th sub or super diagonal */ + inline const Block diagonal(Index i) const + { + eigen_assert((i<0 && -i<=subs()) || (i>=0 && i<=supers())); + return Block(coeffs(), supers()-i, std::max(0,i), 1, diagonalLength(i)); + } + + template inline void evalTo(Dest& dst) const + { + dst.resize(rows(),cols()); + dst.setZero(); + dst.diagonal() = diagonal(); + for (Index i=1; i<=supers();++i) + dst.diagonal(i) = diagonal(i); + for (Index i=1; i<=subs();++i) + dst.diagonal(-i) = diagonal(-i); + } + + DenseMatrixType toDenseMatrix() const + { + DenseMatrixType res(rows(),cols()); + evalTo(res); + return res; + } + + protected: + + inline Index diagonalLength(Index i) const + { return i<0 ? (std::min)(cols(),rows()+i) : (std::min)(rows(),cols()-i); } +}; + +/** + * \class BandMatrix + * \ingroup Core_Module + * + * \brief Represents a rectangular matrix with a banded storage + * + * \tparam _Scalar Numeric type, i.e. float, double, int + * \tparam _Rows Number of rows, or \b Dynamic + * \tparam _Cols Number of columns, or \b Dynamic + * \tparam _Supers Number of super diagonal + * \tparam _Subs Number of sub diagonal + * \tparam _Options A combination of either \b #RowMajor or \b #ColMajor, and of \b #SelfAdjoint + * The former controls \ref TopicStorageOrders "storage order", and defaults to + * column-major. The latter controls whether the matrix represents a selfadjoint + * matrix in which case either Supers of Subs have to be null. + * + * \sa class TridiagonalMatrix + */ + +template +struct traits > +{ + typedef _Scalar Scalar; + typedef Dense StorageKind; + typedef Eigen::Index StorageIndex; + enum { + CoeffReadCost = NumTraits::ReadCost, + RowsAtCompileTime = _Rows, + ColsAtCompileTime = _Cols, + MaxRowsAtCompileTime = _Rows, + MaxColsAtCompileTime = _Cols, + Flags = LvalueBit, + Supers = _Supers, + Subs = _Subs, + Options = _Options, + DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) ? 1 + Supers + Subs : Dynamic + }; + typedef Matrix CoefficientsType; +}; + +template +class BandMatrix : public BandMatrixBase > +{ + public: + + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::StorageIndex StorageIndex; + typedef typename internal::traits::CoefficientsType CoefficientsType; + + explicit inline BandMatrix(Index rows=Rows, Index cols=Cols, Index supers=Supers, Index subs=Subs) + : m_coeffs(1+supers+subs,cols), + m_rows(rows), m_supers(supers), m_subs(subs) + { + } + + /** \returns the number of columns */ + inline Index rows() const { return m_rows.value(); } + + /** \returns the number of rows */ + inline Index cols() const { return m_coeffs.cols(); } + + /** \returns the number of super diagonals */ + inline Index supers() const { return m_supers.value(); } + + /** \returns the number of sub diagonals */ + inline Index subs() const { return m_subs.value(); } + + inline const CoefficientsType& coeffs() const { return m_coeffs; } + inline CoefficientsType& coeffs() { return m_coeffs; } + + protected: + + CoefficientsType m_coeffs; + internal::variable_if_dynamic m_rows; + internal::variable_if_dynamic m_supers; + internal::variable_if_dynamic m_subs; +}; + +template +class BandMatrixWrapper; + +template +struct traits > +{ + typedef typename _CoefficientsType::Scalar Scalar; + typedef typename _CoefficientsType::StorageKind StorageKind; + typedef typename _CoefficientsType::StorageIndex StorageIndex; + enum { + CoeffReadCost = internal::traits<_CoefficientsType>::CoeffReadCost, + RowsAtCompileTime = _Rows, + ColsAtCompileTime = _Cols, + MaxRowsAtCompileTime = _Rows, + MaxColsAtCompileTime = _Cols, + Flags = LvalueBit, + Supers = _Supers, + Subs = _Subs, + Options = _Options, + DataRowsAtCompileTime = ((Supers!=Dynamic) && (Subs!=Dynamic)) ? 1 + Supers + Subs : Dynamic + }; + typedef _CoefficientsType CoefficientsType; +}; + +template +class BandMatrixWrapper : public BandMatrixBase > +{ + public: + + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::traits::CoefficientsType CoefficientsType; + typedef typename internal::traits::StorageIndex StorageIndex; + + explicit inline BandMatrixWrapper(const CoefficientsType& coeffs, Index rows=_Rows, Index cols=_Cols, Index supers=_Supers, Index subs=_Subs) + : m_coeffs(coeffs), + m_rows(rows), m_supers(supers), m_subs(subs) + { + EIGEN_UNUSED_VARIABLE(cols); + //internal::assert(coeffs.cols()==cols() && (supers()+subs()+1)==coeffs.rows()); + } + + /** \returns the number of columns */ + inline Index rows() const { return m_rows.value(); } + + /** \returns the number of rows */ + inline Index cols() const { return m_coeffs.cols(); } + + /** \returns the number of super diagonals */ + inline Index supers() const { return m_supers.value(); } + + /** \returns the number of sub diagonals */ + inline Index subs() const { return m_subs.value(); } + + inline const CoefficientsType& coeffs() const { return m_coeffs; } + + protected: + + const CoefficientsType& m_coeffs; + internal::variable_if_dynamic m_rows; + internal::variable_if_dynamic m_supers; + internal::variable_if_dynamic m_subs; +}; + +/** + * \class TridiagonalMatrix + * \ingroup Core_Module + * + * \brief Represents a tridiagonal matrix with a compact banded storage + * + * \tparam Scalar Numeric type, i.e. float, double, int + * \tparam Size Number of rows and cols, or \b Dynamic + * \tparam Options Can be 0 or \b SelfAdjoint + * + * \sa class BandMatrix + */ +template +class TridiagonalMatrix : public BandMatrix +{ + typedef BandMatrix Base; + typedef typename Base::StorageIndex StorageIndex; + public: + explicit TridiagonalMatrix(Index size = Size) : Base(size,size,Options&SelfAdjoint?0:1,1) {} + + inline typename Base::template DiagonalIntReturnType<1>::Type super() + { return Base::template diagonal<1>(); } + inline const typename Base::template DiagonalIntReturnType<1>::Type super() const + { return Base::template diagonal<1>(); } + inline typename Base::template DiagonalIntReturnType<-1>::Type sub() + { return Base::template diagonal<-1>(); } + inline const typename Base::template DiagonalIntReturnType<-1>::Type sub() const + { return Base::template diagonal<-1>(); } + protected: +}; + + +struct BandShape {}; + +template +struct evaluator_traits > + : public evaluator_traits_base > +{ + typedef BandShape Shape; +}; + +template +struct evaluator_traits > + : public evaluator_traits_base > +{ + typedef BandShape Shape; +}; + +template<> struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_BANDMATRIX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Block.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Block.h new file mode 100644 index 0000000000000000000000000000000000000000..11de45c2ecbc8ccc6d48d12f091fe067f64399e5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Block.h @@ -0,0 +1,452 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_BLOCK_H +#define EIGEN_BLOCK_H + +namespace Eigen { + +namespace internal { +template +struct traits > : traits +{ + typedef typename traits::Scalar Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::XprKind XprKind; + typedef typename ref_selector::type XprTypeNested; + typedef typename remove_reference::type _XprTypeNested; + enum{ + MatrixRows = traits::RowsAtCompileTime, + MatrixCols = traits::ColsAtCompileTime, + RowsAtCompileTime = MatrixRows == 0 ? 0 : BlockRows, + ColsAtCompileTime = MatrixCols == 0 ? 0 : BlockCols, + MaxRowsAtCompileTime = BlockRows==0 ? 0 + : RowsAtCompileTime != Dynamic ? int(RowsAtCompileTime) + : int(traits::MaxRowsAtCompileTime), + MaxColsAtCompileTime = BlockCols==0 ? 0 + : ColsAtCompileTime != Dynamic ? int(ColsAtCompileTime) + : int(traits::MaxColsAtCompileTime), + + XprTypeIsRowMajor = (int(traits::Flags)&RowMajorBit) != 0, + IsRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 + : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 + : XprTypeIsRowMajor, + HasSameStorageOrderAsXprType = (IsRowMajor == XprTypeIsRowMajor), + InnerSize = IsRowMajor ? int(ColsAtCompileTime) : int(RowsAtCompileTime), + InnerStrideAtCompileTime = HasSameStorageOrderAsXprType + ? int(inner_stride_at_compile_time::ret) + : int(outer_stride_at_compile_time::ret), + OuterStrideAtCompileTime = HasSameStorageOrderAsXprType + ? int(outer_stride_at_compile_time::ret) + : int(inner_stride_at_compile_time::ret), + + // FIXME, this traits is rather specialized for dense object and it needs to be cleaned further + FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, + FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0, + Flags = (traits::Flags & (DirectAccessBit | (InnerPanel?CompressedAccessBit:0))) | FlagsLvalueBit | FlagsRowMajorBit, + // FIXME DirectAccessBit should not be handled by expressions + // + // Alignment is needed by MapBase's assertions + // We can sefely set it to false here. Internal alignment errors will be detected by an eigen_internal_assert in the respective evaluator + Alignment = 0 + }; +}; + +template::ret> class BlockImpl_dense; + +} // end namespace internal + +template class BlockImpl; + +/** \class Block + * \ingroup Core_Module + * + * \brief Expression of a fixed-size or dynamic-size block + * + * \tparam XprType the type of the expression in which we are taking a block + * \tparam BlockRows the number of rows of the block we are taking at compile time (optional) + * \tparam BlockCols the number of columns of the block we are taking at compile time (optional) + * \tparam InnerPanel is true, if the block maps to a set of rows of a row major matrix or + * to set of columns of a column major matrix (optional). The parameter allows to determine + * at compile time whether aligned access is possible on the block expression. + * + * This class represents an expression of either a fixed-size or dynamic-size block. It is the return + * type of DenseBase::block(Index,Index,Index,Index) and DenseBase::block(Index,Index) and + * most of the time this is the only way it is used. + * + * However, if you want to directly maniputate block expressions, + * for instance if you want to write a function returning such an expression, you + * will need to use this class. + * + * Here is an example illustrating the dynamic case: + * \include class_Block.cpp + * Output: \verbinclude class_Block.out + * + * \note Even though this expression has dynamic size, in the case where \a XprType + * has fixed size, this expression inherits a fixed maximal size which means that evaluating + * it does not cause a dynamic memory allocation. + * + * Here is an example illustrating the fixed-size case: + * \include class_FixedBlock.cpp + * Output: \verbinclude class_FixedBlock.out + * + * \sa DenseBase::block(Index,Index,Index,Index), DenseBase::block(Index,Index), class VectorBlock + */ +template class Block + : public BlockImpl::StorageKind> +{ + typedef BlockImpl::StorageKind> Impl; + public: + //typedef typename Impl::Base Base; + typedef Impl Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Block) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Block) + + typedef typename internal::remove_all::type NestedExpression; + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC + inline Block(XprType& xpr, Index i) : Impl(xpr,i) + { + eigen_assert( (i>=0) && ( + ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && i= 0 && BlockRows >= 0 && startRow + BlockRows <= xpr.rows() + && startCol >= 0 && BlockCols >= 0 && startCol + BlockCols <= xpr.cols()); + } + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC + inline Block(XprType& xpr, + Index startRow, Index startCol, + Index blockRows, Index blockCols) + : Impl(xpr, startRow, startCol, blockRows, blockCols) + { + eigen_assert((RowsAtCompileTime==Dynamic || RowsAtCompileTime==blockRows) + && (ColsAtCompileTime==Dynamic || ColsAtCompileTime==blockCols)); + eigen_assert(startRow >= 0 && blockRows >= 0 && startRow <= xpr.rows() - blockRows + && startCol >= 0 && blockCols >= 0 && startCol <= xpr.cols() - blockCols); + } +}; + +// The generic default implementation for dense block simplu forward to the internal::BlockImpl_dense +// that must be specialized for direct and non-direct access... +template +class BlockImpl + : public internal::BlockImpl_dense +{ + typedef internal::BlockImpl_dense Impl; + typedef typename XprType::StorageIndex StorageIndex; + public: + typedef Impl Base; + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl) + EIGEN_DEVICE_FUNC inline BlockImpl(XprType& xpr, Index i) : Impl(xpr,i) {} + EIGEN_DEVICE_FUNC inline BlockImpl(XprType& xpr, Index startRow, Index startCol) : Impl(xpr, startRow, startCol) {} + EIGEN_DEVICE_FUNC + inline BlockImpl(XprType& xpr, Index startRow, Index startCol, Index blockRows, Index blockCols) + : Impl(xpr, startRow, startCol, blockRows, blockCols) {} +}; + +namespace internal { + +/** \internal Internal implementation of dense Blocks in the general case. */ +template class BlockImpl_dense + : public internal::dense_xpr_base >::type +{ + typedef Block BlockType; + typedef typename internal::ref_selector::non_const_type XprTypeNested; + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) + + // class InnerIterator; // FIXME apparently never used + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, Index i) + : m_xpr(xpr), + // It is a row if and only if BlockRows==1 and BlockCols==XprType::ColsAtCompileTime, + // and it is a column if and only if BlockRows==XprType::RowsAtCompileTime and BlockCols==1, + // all other cases are invalid. + // The case a 1x1 matrix seems ambiguous, but the result is the same anyway. + m_startRow( (BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) ? i : 0), + m_startCol( (BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) ? i : 0), + m_blockRows(BlockRows==1 ? 1 : xpr.rows()), + m_blockCols(BlockCols==1 ? 1 : xpr.cols()) + {} + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) + : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), + m_blockRows(BlockRows), m_blockCols(BlockCols) + {} + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, + Index startRow, Index startCol, + Index blockRows, Index blockCols) + : m_xpr(xpr), m_startRow(startRow), m_startCol(startCol), + m_blockRows(blockRows), m_blockCols(blockCols) + {} + + EIGEN_DEVICE_FUNC inline Index rows() const { return m_blockRows.value(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return m_blockCols.value(); } + + EIGEN_DEVICE_FUNC + inline Scalar& coeffRef(Index rowId, Index colId) + { + EIGEN_STATIC_ASSERT_LVALUE(XprType) + return m_xpr.coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index rowId, Index colId) const + { + return m_xpr.derived().coeffRef(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index rowId, Index colId) const + { + return m_xpr.coeff(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + EIGEN_DEVICE_FUNC + inline Scalar& coeffRef(Index index) + { + EIGEN_STATIC_ASSERT_LVALUE(XprType) + return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index index) const + { + return m_xpr.coeffRef(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + EIGEN_DEVICE_FUNC + inline const CoeffReturnType coeff(Index index) const + { + return m_xpr.coeff(m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + template + inline PacketScalar packet(Index rowId, Index colId) const + { + return m_xpr.template packet(rowId + m_startRow.value(), colId + m_startCol.value()); + } + + template + inline void writePacket(Index rowId, Index colId, const PacketScalar& val) + { + m_xpr.template writePacket(rowId + m_startRow.value(), colId + m_startCol.value(), val); + } + + template + inline PacketScalar packet(Index index) const + { + return m_xpr.template packet + (m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0)); + } + + template + inline void writePacket(Index index, const PacketScalar& val) + { + m_xpr.template writePacket + (m_startRow.value() + (RowsAtCompileTime == 1 ? 0 : index), + m_startCol.value() + (RowsAtCompileTime == 1 ? index : 0), val); + } + + #ifdef EIGEN_PARSED_BY_DOXYGEN + /** \sa MapBase::data() */ + EIGEN_DEVICE_FUNC inline const Scalar* data() const; + EIGEN_DEVICE_FUNC inline Index innerStride() const; + EIGEN_DEVICE_FUNC inline Index outerStride() const; + #endif + + EIGEN_DEVICE_FUNC + const typename internal::remove_all::type& nestedExpression() const + { + return m_xpr; + } + + EIGEN_DEVICE_FUNC + XprType& nestedExpression() { return m_xpr; } + + EIGEN_DEVICE_FUNC + StorageIndex startRow() const + { + return m_startRow.value(); + } + + EIGEN_DEVICE_FUNC + StorageIndex startCol() const + { + return m_startCol.value(); + } + + protected: + + XprTypeNested m_xpr; + const internal::variable_if_dynamic m_startRow; + const internal::variable_if_dynamic m_startCol; + const internal::variable_if_dynamic m_blockRows; + const internal::variable_if_dynamic m_blockCols; +}; + +/** \internal Internal implementation of dense Blocks in the direct access case.*/ +template +class BlockImpl_dense + : public MapBase > +{ + typedef Block BlockType; + typedef typename internal::ref_selector::non_const_type XprTypeNested; + enum { + XprTypeIsRowMajor = (int(traits::Flags)&RowMajorBit) != 0 + }; + public: + + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(BlockType) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(BlockImpl_dense) + + /** Column or Row constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, Index i) + : Base(xpr.data() + i * ( ((BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) && (!XprTypeIsRowMajor)) + || ((BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) && ( XprTypeIsRowMajor)) ? xpr.innerStride() : xpr.outerStride()), + BlockRows==1 ? 1 : xpr.rows(), + BlockCols==1 ? 1 : xpr.cols()), + m_xpr(xpr), + m_startRow( (BlockRows==1) && (BlockCols==XprType::ColsAtCompileTime) ? i : 0), + m_startCol( (BlockRows==XprType::RowsAtCompileTime) && (BlockCols==1) ? i : 0) + { + init(); + } + + /** Fixed-size constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, Index startRow, Index startCol) + : Base(xpr.data()+xpr.innerStride()*(XprTypeIsRowMajor?startCol:startRow) + xpr.outerStride()*(XprTypeIsRowMajor?startRow:startCol)), + m_xpr(xpr), m_startRow(startRow), m_startCol(startCol) + { + init(); + } + + /** Dynamic-size constructor + */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, + Index startRow, Index startCol, + Index blockRows, Index blockCols) + : Base(xpr.data()+xpr.innerStride()*(XprTypeIsRowMajor?startCol:startRow) + xpr.outerStride()*(XprTypeIsRowMajor?startRow:startCol), blockRows, blockCols), + m_xpr(xpr), m_startRow(startRow), m_startCol(startCol) + { + init(); + } + + EIGEN_DEVICE_FUNC + const typename internal::remove_all::type& nestedExpression() const + { + return m_xpr; + } + + EIGEN_DEVICE_FUNC + XprType& nestedExpression() { return m_xpr; } + + /** \sa MapBase::innerStride() */ + EIGEN_DEVICE_FUNC + inline Index innerStride() const + { + return internal::traits::HasSameStorageOrderAsXprType + ? m_xpr.innerStride() + : m_xpr.outerStride(); + } + + /** \sa MapBase::outerStride() */ + EIGEN_DEVICE_FUNC + inline Index outerStride() const + { + return m_outerStride; + } + + EIGEN_DEVICE_FUNC + StorageIndex startRow() const + { + return m_startRow.value(); + } + + EIGEN_DEVICE_FUNC + StorageIndex startCol() const + { + return m_startCol.value(); + } + + #ifndef __SUNPRO_CC + // FIXME sunstudio is not friendly with the above friend... + // META-FIXME there is no 'friend' keyword around here. Is this obsolete? + protected: + #endif + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal used by allowAligned() */ + EIGEN_DEVICE_FUNC + inline BlockImpl_dense(XprType& xpr, const Scalar* data, Index blockRows, Index blockCols) + : Base(data, blockRows, blockCols), m_xpr(xpr) + { + init(); + } + #endif + + protected: + EIGEN_DEVICE_FUNC + void init() + { + m_outerStride = internal::traits::HasSameStorageOrderAsXprType + ? m_xpr.outerStride() + : m_xpr.innerStride(); + } + + XprTypeNested m_xpr; + const internal::variable_if_dynamic m_startRow; + const internal::variable_if_dynamic m_startCol; + Index m_outerStride; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_BLOCK_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BooleanRedux.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BooleanRedux.h new file mode 100644 index 0000000000000000000000000000000000000000..8409d8749adc9faf3002cf1ff9fb26a31001b352 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/BooleanRedux.h @@ -0,0 +1,164 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_ALLANDANY_H +#define EIGEN_ALLANDANY_H + +namespace Eigen { + +namespace internal { + +template +struct all_unroller +{ + typedef typename Derived::ExpressionTraits Traits; + enum { + col = (UnrollCount-1) / Traits::RowsAtCompileTime, + row = (UnrollCount-1) % Traits::RowsAtCompileTime + }; + + static inline bool run(const Derived &mat) + { + return all_unroller::run(mat) && mat.coeff(row, col); + } +}; + +template +struct all_unroller +{ + static inline bool run(const Derived &/*mat*/) { return true; } +}; + +template +struct all_unroller +{ + static inline bool run(const Derived &) { return false; } +}; + +template +struct any_unroller +{ + typedef typename Derived::ExpressionTraits Traits; + enum { + col = (UnrollCount-1) / Traits::RowsAtCompileTime, + row = (UnrollCount-1) % Traits::RowsAtCompileTime + }; + + static inline bool run(const Derived &mat) + { + return any_unroller::run(mat) || mat.coeff(row, col); + } +}; + +template +struct any_unroller +{ + static inline bool run(const Derived & /*mat*/) { return false; } +}; + +template +struct any_unroller +{ + static inline bool run(const Derived &) { return false; } +}; + +} // end namespace internal + +/** \returns true if all coefficients are true + * + * Example: \include MatrixBase_all.cpp + * Output: \verbinclude MatrixBase_all.out + * + * \sa any(), Cwise::operator<() + */ +template +inline bool DenseBase::all() const +{ + typedef internal::evaluator Evaluator; + enum { + unroll = SizeAtCompileTime != Dynamic + && SizeAtCompileTime * (Evaluator::CoeffReadCost + NumTraits::AddCost) <= EIGEN_UNROLLING_LIMIT + }; + Evaluator evaluator(derived()); + if(unroll) + return internal::all_unroller::run(evaluator); + else + { + for(Index j = 0; j < cols(); ++j) + for(Index i = 0; i < rows(); ++i) + if (!evaluator.coeff(i, j)) return false; + return true; + } +} + +/** \returns true if at least one coefficient is true + * + * \sa all() + */ +template +inline bool DenseBase::any() const +{ + typedef internal::evaluator Evaluator; + enum { + unroll = SizeAtCompileTime != Dynamic + && SizeAtCompileTime * (Evaluator::CoeffReadCost + NumTraits::AddCost) <= EIGEN_UNROLLING_LIMIT + }; + Evaluator evaluator(derived()); + if(unroll) + return internal::any_unroller::run(evaluator); + else + { + for(Index j = 0; j < cols(); ++j) + for(Index i = 0; i < rows(); ++i) + if (evaluator.coeff(i, j)) return true; + return false; + } +} + +/** \returns the number of coefficients which evaluate to true + * + * \sa all(), any() + */ +template +inline Eigen::Index DenseBase::count() const +{ + return derived().template cast().template cast().sum(); +} + +/** \returns true is \c *this contains at least one Not A Number (NaN). + * + * \sa allFinite() + */ +template +inline bool DenseBase::hasNaN() const +{ +#if EIGEN_COMP_MSVC || (defined __FAST_MATH__) + return derived().array().isNaN().any(); +#else + return !((derived().array()==derived().array()).all()); +#endif +} + +/** \returns true if \c *this contains only finite numbers, i.e., no NaN and no +/-INF values. + * + * \sa hasNaN() + */ +template +inline bool DenseBase::allFinite() const +{ +#if EIGEN_COMP_MSVC || (defined __FAST_MATH__) + return derived().array().isFinite().all(); +#else + return !((derived()-derived()).hasNaN()); +#endif +} + +} // end namespace Eigen + +#endif // EIGEN_ALLANDANY_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CommaInitializer.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CommaInitializer.h new file mode 100644 index 0000000000000000000000000000000000000000..d218e98143f40ec0b1ac74ab5af21b62af3ff8be --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CommaInitializer.h @@ -0,0 +1,160 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_COMMAINITIALIZER_H +#define EIGEN_COMMAINITIALIZER_H + +namespace Eigen { + +/** \class CommaInitializer + * \ingroup Core_Module + * + * \brief Helper class used by the comma initializer operator + * + * This class is internally used to implement the comma initializer feature. It is + * the return type of MatrixBase::operator<<, and most of the time this is the only + * way it is used. + * + * \sa \blank \ref MatrixBaseCommaInitRef "MatrixBase::operator<<", CommaInitializer::finished() + */ +template +struct CommaInitializer +{ + typedef typename XprType::Scalar Scalar; + + EIGEN_DEVICE_FUNC + inline CommaInitializer(XprType& xpr, const Scalar& s) + : m_xpr(xpr), m_row(0), m_col(1), m_currentBlockRows(1) + { + m_xpr.coeffRef(0,0) = s; + } + + template + EIGEN_DEVICE_FUNC + inline CommaInitializer(XprType& xpr, const DenseBase& other) + : m_xpr(xpr), m_row(0), m_col(other.cols()), m_currentBlockRows(other.rows()) + { + m_xpr.block(0, 0, other.rows(), other.cols()) = other; + } + + /* Copy/Move constructor which transfers ownership. This is crucial in + * absence of return value optimization to avoid assertions during destruction. */ + // FIXME in C++11 mode this could be replaced by a proper RValue constructor + EIGEN_DEVICE_FUNC + inline CommaInitializer(const CommaInitializer& o) + : m_xpr(o.m_xpr), m_row(o.m_row), m_col(o.m_col), m_currentBlockRows(o.m_currentBlockRows) { + // Mark original object as finished. In absence of R-value references we need to const_cast: + const_cast(o).m_row = m_xpr.rows(); + const_cast(o).m_col = m_xpr.cols(); + const_cast(o).m_currentBlockRows = 0; + } + + /* inserts a scalar value in the target matrix */ + EIGEN_DEVICE_FUNC + CommaInitializer& operator,(const Scalar& s) + { + if (m_col==m_xpr.cols()) + { + m_row+=m_currentBlockRows; + m_col = 0; + m_currentBlockRows = 1; + eigen_assert(m_row + EIGEN_DEVICE_FUNC + CommaInitializer& operator,(const DenseBase& other) + { + if (m_col==m_xpr.cols() && (other.cols()!=0 || other.rows()!=m_currentBlockRows)) + { + m_row+=m_currentBlockRows; + m_col = 0; + m_currentBlockRows = other.rows(); + eigen_assert(m_row+m_currentBlockRows<=m_xpr.rows() + && "Too many rows passed to comma initializer (operator<<)"); + } + eigen_assert((m_col + other.cols() <= m_xpr.cols()) + && "Too many coefficients passed to comma initializer (operator<<)"); + eigen_assert(m_currentBlockRows==other.rows()); + m_xpr.template block + (m_row, m_col, other.rows(), other.cols()) = other; + m_col += other.cols(); + return *this; + } + + EIGEN_DEVICE_FUNC + inline ~CommaInitializer() +#if defined VERIFY_RAISES_ASSERT && (!defined EIGEN_NO_ASSERTION_CHECKING) && defined EIGEN_EXCEPTIONS + EIGEN_EXCEPTION_SPEC(Eigen::eigen_assert_exception) +#endif + { + finished(); + } + + /** \returns the built matrix once all its coefficients have been set. + * Calling finished is 100% optional. Its purpose is to write expressions + * like this: + * \code + * quaternion.fromRotationMatrix((Matrix3f() << axis0, axis1, axis2).finished()); + * \endcode + */ + EIGEN_DEVICE_FUNC + inline XprType& finished() { + eigen_assert(((m_row+m_currentBlockRows) == m_xpr.rows() || m_xpr.cols() == 0) + && m_col == m_xpr.cols() + && "Too few coefficients passed to comma initializer (operator<<)"); + return m_xpr; + } + + XprType& m_xpr; // target expression + Index m_row; // current row id + Index m_col; // current col id + Index m_currentBlockRows; // current block height +}; + +/** \anchor MatrixBaseCommaInitRef + * Convenient operator to set the coefficients of a matrix. + * + * The coefficients must be provided in a row major order and exactly match + * the size of the matrix. Otherwise an assertion is raised. + * + * Example: \include MatrixBase_set.cpp + * Output: \verbinclude MatrixBase_set.out + * + * \note According the c++ standard, the argument expressions of this comma initializer are evaluated in arbitrary order. + * + * \sa CommaInitializer::finished(), class CommaInitializer + */ +template +inline CommaInitializer DenseBase::operator<< (const Scalar& s) +{ + return CommaInitializer(*static_cast(this), s); +} + +/** \sa operator<<(const Scalar&) */ +template +template +inline CommaInitializer +DenseBase::operator<<(const DenseBase& other) +{ + return CommaInitializer(*static_cast(this), other); +} + +} // end namespace Eigen + +#endif // EIGEN_COMMAINITIALIZER_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ConditionEstimator.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ConditionEstimator.h new file mode 100644 index 0000000000000000000000000000000000000000..51a2e5f1b6f9587ad54fbc889e03c1d11e02d4f4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ConditionEstimator.h @@ -0,0 +1,175 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2016 Rasmus Munk Larsen (rmlarsen@google.com) +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CONDITIONESTIMATOR_H +#define EIGEN_CONDITIONESTIMATOR_H + +namespace Eigen { + +namespace internal { + +template +struct rcond_compute_sign { + static inline Vector run(const Vector& v) { + const RealVector v_abs = v.cwiseAbs(); + return (v_abs.array() == static_cast(0)) + .select(Vector::Ones(v.size()), v.cwiseQuotient(v_abs)); + } +}; + +// Partial specialization to avoid elementwise division for real vectors. +template +struct rcond_compute_sign { + static inline Vector run(const Vector& v) { + return (v.array() < static_cast(0)) + .select(-Vector::Ones(v.size()), Vector::Ones(v.size())); + } +}; + +/** + * \returns an estimate of ||inv(matrix)||_1 given a decomposition of + * \a matrix that implements .solve() and .adjoint().solve() methods. + * + * This function implements Algorithms 4.1 and 5.1 from + * http://www.maths.manchester.ac.uk/~higham/narep/narep135.pdf + * which also forms the basis for the condition number estimators in + * LAPACK. Since at most 10 calls to the solve method of dec are + * performed, the total cost is O(dims^2), as opposed to O(dims^3) + * needed to compute the inverse matrix explicitly. + * + * The most common usage is in estimating the condition number + * ||matrix||_1 * ||inv(matrix)||_1. The first term ||matrix||_1 can be + * computed directly in O(n^2) operations. + * + * Supports the following decompositions: FullPivLU, PartialPivLU, LDLT, and + * LLT. + * + * \sa FullPivLU, PartialPivLU, LDLT, LLT. + */ +template +typename Decomposition::RealScalar rcond_invmatrix_L1_norm_estimate(const Decomposition& dec) +{ + typedef typename Decomposition::MatrixType MatrixType; + typedef typename Decomposition::Scalar Scalar; + typedef typename Decomposition::RealScalar RealScalar; + typedef typename internal::plain_col_type::type Vector; + typedef typename internal::plain_col_type::type RealVector; + const bool is_complex = (NumTraits::IsComplex != 0); + + eigen_assert(dec.rows() == dec.cols()); + const Index n = dec.rows(); + if (n == 0) + return 0; + + // Disable Index to float conversion warning +#ifdef __INTEL_COMPILER + #pragma warning push + #pragma warning ( disable : 2259 ) +#endif + Vector v = dec.solve(Vector::Ones(n) / Scalar(n)); +#ifdef __INTEL_COMPILER + #pragma warning pop +#endif + + // lower_bound is a lower bound on + // ||inv(matrix)||_1 = sup_v ||inv(matrix) v||_1 / ||v||_1 + // and is the objective maximized by the ("super-") gradient ascent + // algorithm below. + RealScalar lower_bound = v.template lpNorm<1>(); + if (n == 1) + return lower_bound; + + // Gradient ascent algorithm follows: We know that the optimum is achieved at + // one of the simplices v = e_i, so in each iteration we follow a + // super-gradient to move towards the optimal one. + RealScalar old_lower_bound = lower_bound; + Vector sign_vector(n); + Vector old_sign_vector; + Index v_max_abs_index = -1; + Index old_v_max_abs_index = v_max_abs_index; + for (int k = 0; k < 4; ++k) + { + sign_vector = internal::rcond_compute_sign::run(v); + if (k > 0 && !is_complex && sign_vector == old_sign_vector) { + // Break if the solution stagnated. + break; + } + // v_max_abs_index = argmax |real( inv(matrix)^T * sign_vector )| + v = dec.adjoint().solve(sign_vector); + v.real().cwiseAbs().maxCoeff(&v_max_abs_index); + if (v_max_abs_index == old_v_max_abs_index) { + // Break if the solution stagnated. + break; + } + // Move to the new simplex e_j, where j = v_max_abs_index. + v = dec.solve(Vector::Unit(n, v_max_abs_index)); // v = inv(matrix) * e_j. + lower_bound = v.template lpNorm<1>(); + if (lower_bound <= old_lower_bound) { + // Break if the gradient step did not increase the lower_bound. + break; + } + if (!is_complex) { + old_sign_vector = sign_vector; + } + old_v_max_abs_index = v_max_abs_index; + old_lower_bound = lower_bound; + } + // The following calculates an independent estimate of ||matrix||_1 by + // multiplying matrix by a vector with entries of slowly increasing + // magnitude and alternating sign: + // v_i = (-1)^{i} (1 + (i / (dim-1))), i = 0,...,dim-1. + // This improvement to Hager's algorithm above is due to Higham. It was + // added to make the algorithm more robust in certain corner cases where + // large elements in the matrix might otherwise escape detection due to + // exact cancellation (especially when op and op_adjoint correspond to a + // sequence of backsubstitutions and permutations), which could cause + // Hager's algorithm to vastly underestimate ||matrix||_1. + Scalar alternating_sign(RealScalar(1)); + for (Index i = 0; i < n; ++i) { + // The static_cast is needed when Scalar is a complex and RealScalar implements expression templates + v[i] = alternating_sign * static_cast(RealScalar(1) + (RealScalar(i) / (RealScalar(n - 1)))); + alternating_sign = -alternating_sign; + } + v = dec.solve(v); + const RealScalar alternate_lower_bound = (2 * v.template lpNorm<1>()) / (3 * RealScalar(n)); + return numext::maxi(lower_bound, alternate_lower_bound); +} + +/** \brief Reciprocal condition number estimator. + * + * Computing a decomposition of a dense matrix takes O(n^3) operations, while + * this method estimates the condition number quickly and reliably in O(n^2) + * operations. + * + * \returns an estimate of the reciprocal condition number + * (1 / (||matrix||_1 * ||inv(matrix)||_1)) of matrix, given ||matrix||_1 and + * its decomposition. Supports the following decompositions: FullPivLU, + * PartialPivLU, LDLT, and LLT. + * + * \sa FullPivLU, PartialPivLU, LDLT, LLT. + */ +template +typename Decomposition::RealScalar +rcond_estimate_helper(typename Decomposition::RealScalar matrix_norm, const Decomposition& dec) +{ + typedef typename Decomposition::RealScalar RealScalar; + eigen_assert(dec.rows() == dec.cols()); + if (dec.rows() == 0) return NumTraits::infinity(); + if (matrix_norm == RealScalar(0)) return RealScalar(0); + if (dec.rows() == 1) return RealScalar(1); + const RealScalar inverse_matrix_norm = rcond_invmatrix_L1_norm_estimate(dec); + return (inverse_matrix_norm == RealScalar(0) ? RealScalar(0) + : (RealScalar(1) / inverse_matrix_norm) / matrix_norm); +} + +} // namespace internal + +} // namespace Eigen + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreEvaluators.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreEvaluators.h new file mode 100644 index 0000000000000000000000000000000000000000..910889efa708ac3d74aae2d63c7a150a7d7723e8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreEvaluators.h @@ -0,0 +1,1688 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2011 Benoit Jacob +// Copyright (C) 2011-2014 Gael Guennebaud +// Copyright (C) 2011-2012 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_COREEVALUATORS_H +#define EIGEN_COREEVALUATORS_H + +namespace Eigen { + +namespace internal { + +// This class returns the evaluator kind from the expression storage kind. +// Default assumes index based accessors +template +struct storage_kind_to_evaluator_kind { + typedef IndexBased Kind; +}; + +// This class returns the evaluator shape from the expression storage kind. +// It can be Dense, Sparse, Triangular, Diagonal, SelfAdjoint, Band, etc. +template struct storage_kind_to_shape; + +template<> struct storage_kind_to_shape { typedef DenseShape Shape; }; +template<> struct storage_kind_to_shape { typedef SolverShape Shape; }; +template<> struct storage_kind_to_shape { typedef PermutationShape Shape; }; +template<> struct storage_kind_to_shape { typedef TranspositionsShape Shape; }; + +// Evaluators have to be specialized with respect to various criteria such as: +// - storage/structure/shape +// - scalar type +// - etc. +// Therefore, we need specialization of evaluator providing additional template arguments for each kind of evaluators. +// We currently distinguish the following kind of evaluators: +// - unary_evaluator for expressions taking only one arguments (CwiseUnaryOp, CwiseUnaryView, Transpose, MatrixWrapper, ArrayWrapper, Reverse, Replicate) +// - binary_evaluator for expression taking two arguments (CwiseBinaryOp) +// - ternary_evaluator for expression taking three arguments (CwiseTernaryOp) +// - product_evaluator for linear algebra products (Product); special case of binary_evaluator because it requires additional tags for dispatching. +// - mapbase_evaluator for Map, Block, Ref +// - block_evaluator for Block (special dispatching to a mapbase_evaluator or unary_evaluator) + +template< typename T, + typename Arg1Kind = typename evaluator_traits::Kind, + typename Arg2Kind = typename evaluator_traits::Kind, + typename Arg3Kind = typename evaluator_traits::Kind, + typename Arg1Scalar = typename traits::Scalar, + typename Arg2Scalar = typename traits::Scalar, + typename Arg3Scalar = typename traits::Scalar> struct ternary_evaluator; + +template< typename T, + typename LhsKind = typename evaluator_traits::Kind, + typename RhsKind = typename evaluator_traits::Kind, + typename LhsScalar = typename traits::Scalar, + typename RhsScalar = typename traits::Scalar> struct binary_evaluator; + +template< typename T, + typename Kind = typename evaluator_traits::Kind, + typename Scalar = typename T::Scalar> struct unary_evaluator; + +// evaluator_traits contains traits for evaluator + +template +struct evaluator_traits_base +{ + // by default, get evaluator kind and shape from storage + typedef typename storage_kind_to_evaluator_kind::StorageKind>::Kind Kind; + typedef typename storage_kind_to_shape::StorageKind>::Shape Shape; +}; + +// Default evaluator traits +template +struct evaluator_traits : public evaluator_traits_base +{ +}; + +template::Shape > +struct evaluator_assume_aliasing { + static const bool value = false; +}; + +// By default, we assume a unary expression: +template +struct evaluator : public unary_evaluator +{ + typedef unary_evaluator Base; + EIGEN_DEVICE_FUNC explicit evaluator(const T& xpr) : Base(xpr) {} +}; + + +// TODO: Think about const-correctness +template +struct evaluator + : evaluator +{ + EIGEN_DEVICE_FUNC + explicit evaluator(const T& xpr) : evaluator(xpr) {} +}; + +// ---------- base class for all evaluators ---------- + +template +struct evaluator_base : public noncopyable +{ + // TODO that's not very nice to have to propagate all these traits. They are currently only needed to handle outer,inner indices. + typedef traits ExpressionTraits; + + enum { + Alignment = 0 + }; +}; + +// -------------------- Matrix and Array -------------------- +// +// evaluator is a common base class for the +// Matrix and Array evaluators. +// Here we directly specialize evaluator. This is not really a unary expression, and it is, by definition, dense, +// so no need for more sophisticated dispatching. + +template +struct evaluator > + : evaluator_base +{ + typedef PlainObjectBase PlainObjectType; + typedef typename PlainObjectType::Scalar Scalar; + typedef typename PlainObjectType::CoeffReturnType CoeffReturnType; + + enum { + IsRowMajor = PlainObjectType::IsRowMajor, + IsVectorAtCompileTime = PlainObjectType::IsVectorAtCompileTime, + RowsAtCompileTime = PlainObjectType::RowsAtCompileTime, + ColsAtCompileTime = PlainObjectType::ColsAtCompileTime, + + CoeffReadCost = NumTraits::ReadCost, + Flags = traits::EvaluatorFlags, + Alignment = traits::Alignment + }; + + EIGEN_DEVICE_FUNC evaluator() + : m_data(0), + m_outerStride(IsVectorAtCompileTime ? 0 + : int(IsRowMajor) ? ColsAtCompileTime + : RowsAtCompileTime) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + EIGEN_DEVICE_FUNC explicit evaluator(const PlainObjectType& m) + : m_data(m.data()), m_outerStride(IsVectorAtCompileTime ? 0 : m.outerStride()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + if (IsRowMajor) + return m_data[row * m_outerStride.value() + col]; + else + return m_data[row + col * m_outerStride.value()]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_data[index]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + if (IsRowMajor) + return const_cast(m_data)[row * m_outerStride.value() + col]; + else + return const_cast(m_data)[row + col * m_outerStride.value()]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return const_cast(m_data)[index]; + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + if (IsRowMajor) + return ploadt(m_data + row * m_outerStride.value() + col); + else + return ploadt(m_data + row + col * m_outerStride.value()); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return ploadt(m_data + index); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + if (IsRowMajor) + return pstoret + (const_cast(m_data) + row * m_outerStride.value() + col, x); + else + return pstoret + (const_cast(m_data) + row + col * m_outerStride.value(), x); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + return pstoret(const_cast(m_data) + index, x); + } + +protected: + const Scalar *m_data; + + // We do not need to know the outer stride for vectors + variable_if_dynamic m_outerStride; +}; + +template +struct evaluator > + : evaluator > > +{ + typedef Matrix XprType; + + EIGEN_DEVICE_FUNC evaluator() {} + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& m) + : evaluator >(m) + { } +}; + +template +struct evaluator > + : evaluator > > +{ + typedef Array XprType; + + EIGEN_DEVICE_FUNC evaluator() {} + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& m) + : evaluator >(m) + { } +}; + +// -------------------- Transpose -------------------- + +template +struct unary_evaluator, IndexBased> + : evaluator_base > +{ + typedef Transpose XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost, + Flags = evaluator::Flags ^ RowMajorBit, + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& t) : m_argImpl(t.nestedExpression()) {} + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_argImpl.coeff(col, row); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_argImpl.coeff(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_argImpl.coeffRef(col, row); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename XprType::Scalar& coeffRef(Index index) + { + return m_argImpl.coeffRef(index); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_argImpl.template packet(col, row); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return m_argImpl.template packet(index); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + m_argImpl.template writePacket(col, row, x); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + m_argImpl.template writePacket(index, x); + } + +protected: + evaluator m_argImpl; +}; + +// -------------------- CwiseNullaryOp -------------------- +// Like Matrix and Array, this is not really a unary expression, so we directly specialize evaluator. +// Likewise, there is not need to more sophisticated dispatching here. + +template::value, + bool has_unary = has_unary_operator::value, + bool has_binary = has_binary_operator::value> +struct nullary_wrapper +{ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { return op(i,j); } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { return op(i); } + + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { return op.template packetOp(i,j); } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { return op.template packetOp(i); } +}; + +template +struct nullary_wrapper +{ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType=0, IndexType=0) const { return op(); } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType=0, IndexType=0) const { return op.template packetOp(); } +}; + +template +struct nullary_wrapper +{ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j=0) const { return op(i,j); } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j=0) const { return op.template packetOp(i,j); } +}; + +// We need the following specialization for vector-only functors assigned to a runtime vector, +// for instance, using linspace and assigning a RowVectorXd to a MatrixXd or even a row of a MatrixXd. +// In this case, i==0 and j is used for the actual iteration. +template +struct nullary_wrapper +{ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { + eigen_assert(i==0 || j==0); + return op(i+j); + } + template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { + eigen_assert(i==0 || j==0); + return op.template packetOp(i+j); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { return op(i); } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { return op.template packetOp(i); } +}; + +template +struct nullary_wrapper {}; + +#if 0 && EIGEN_COMP_MSVC>0 +// Disable this ugly workaround. This is now handled in traits::match, +// but this piece of code might still become handly if some other weird compilation +// erros pop up again. + +// MSVC exhibits a weird compilation error when +// compiling: +// Eigen::MatrixXf A = MatrixXf::Random(3,3); +// Ref R = 2.f*A; +// and that has_*ary_operator> have not been instantiated yet. +// The "problem" is that evaluator<2.f*A> is instantiated by traits::match<2.f*A> +// and at that time has_*ary_operator returns true regardless of T. +// Then nullary_wrapper is badly instantiated as nullary_wrapper<.,.,true,true,true>. +// The trick is thus to defer the proper instantiation of nullary_wrapper when coeff(), +// and packet() are really instantiated as implemented below: + +// This is a simple wrapper around Index to enforce the re-instantiation of +// has_*ary_operator when needed. +template struct nullary_wrapper_workaround_msvc { + nullary_wrapper_workaround_msvc(const T&); + operator T()const; +}; + +template +struct nullary_wrapper +{ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i, IndexType j) const { + return nullary_wrapper >::value, + has_unary_operator >::value, + has_binary_operator >::value>().operator()(op,i,j); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar operator()(const NullaryOp& op, IndexType i) const { + return nullary_wrapper >::value, + has_unary_operator >::value, + has_binary_operator >::value>().operator()(op,i); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i, IndexType j) const { + return nullary_wrapper >::value, + has_unary_operator >::value, + has_binary_operator >::value>().template packetOp(op,i,j); + } + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE T packetOp(const NullaryOp& op, IndexType i) const { + return nullary_wrapper >::value, + has_unary_operator >::value, + has_binary_operator >::value>().template packetOp(op,i); + } +}; +#endif // MSVC workaround + +template +struct evaluator > + : evaluator_base > +{ + typedef CwiseNullaryOp XprType; + typedef typename internal::remove_all::type PlainObjectTypeCleaned; + + enum { + CoeffReadCost = internal::functor_traits::Cost, + + Flags = (evaluator::Flags + & ( HereditaryBits + | (functor_has_linear_access::ret ? LinearAccessBit : 0) + | (functor_traits::PacketAccess ? PacketAccessBit : 0))) + | (functor_traits::IsRepeatable ? 0 : EvalBeforeNestingBit), + Alignment = AlignedMax + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& n) + : m_functor(n.functor()), m_wrapper() + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(IndexType row, IndexType col) const + { + return m_wrapper(m_functor, row, col); + } + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(IndexType index) const + { + return m_wrapper(m_functor,index); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(IndexType row, IndexType col) const + { + return m_wrapper.template packetOp(m_functor, row, col); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(IndexType index) const + { + return m_wrapper.template packetOp(m_functor, index); + } + +protected: + const NullaryOp m_functor; + const internal::nullary_wrapper m_wrapper; +}; + +// -------------------- CwiseUnaryOp -------------------- + +template +struct unary_evaluator, IndexBased > + : evaluator_base > +{ + typedef CwiseUnaryOp XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost + functor_traits::Cost, + + Flags = evaluator::Flags + & (HereditaryBits | LinearAccessBit | (functor_traits::PacketAccess ? PacketAccessBit : 0)), + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + explicit unary_evaluator(const XprType& op) + : m_functor(op.functor()), + m_argImpl(op.nestedExpression()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_functor(m_argImpl.coeff(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_functor(m_argImpl.coeff(index)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_functor.packetOp(m_argImpl.template packet(row, col)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return m_functor.packetOp(m_argImpl.template packet(index)); + } + +protected: + const UnaryOp m_functor; + evaluator m_argImpl; +}; + +// -------------------- CwiseTernaryOp -------------------- + +// this is a ternary expression +template +struct evaluator > + : public ternary_evaluator > +{ + typedef CwiseTernaryOp XprType; + typedef ternary_evaluator > Base; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr) {} +}; + +template +struct ternary_evaluator, IndexBased, IndexBased> + : evaluator_base > +{ + typedef CwiseTernaryOp XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost + evaluator::CoeffReadCost + evaluator::CoeffReadCost + functor_traits::Cost, + + Arg1Flags = evaluator::Flags, + Arg2Flags = evaluator::Flags, + Arg3Flags = evaluator::Flags, + SameType = is_same::value && is_same::value, + StorageOrdersAgree = (int(Arg1Flags)&RowMajorBit)==(int(Arg2Flags)&RowMajorBit) && (int(Arg1Flags)&RowMajorBit)==(int(Arg3Flags)&RowMajorBit), + Flags0 = (int(Arg1Flags) | int(Arg2Flags) | int(Arg3Flags)) & ( + HereditaryBits + | (int(Arg1Flags) & int(Arg2Flags) & int(Arg3Flags) & + ( (StorageOrdersAgree ? LinearAccessBit : 0) + | (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0) + ) + ) + ), + Flags = (Flags0 & ~RowMajorBit) | (Arg1Flags & RowMajorBit), + Alignment = EIGEN_PLAIN_ENUM_MIN( + EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, evaluator::Alignment), + evaluator::Alignment) + }; + + EIGEN_DEVICE_FUNC explicit ternary_evaluator(const XprType& xpr) + : m_functor(xpr.functor()), + m_arg1Impl(xpr.arg1()), + m_arg2Impl(xpr.arg2()), + m_arg3Impl(xpr.arg3()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_functor(m_arg1Impl.coeff(row, col), m_arg2Impl.coeff(row, col), m_arg3Impl.coeff(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_functor(m_arg1Impl.coeff(index), m_arg2Impl.coeff(index), m_arg3Impl.coeff(index)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_functor.packetOp(m_arg1Impl.template packet(row, col), + m_arg2Impl.template packet(row, col), + m_arg3Impl.template packet(row, col)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return m_functor.packetOp(m_arg1Impl.template packet(index), + m_arg2Impl.template packet(index), + m_arg3Impl.template packet(index)); + } + +protected: + const TernaryOp m_functor; + evaluator m_arg1Impl; + evaluator m_arg2Impl; + evaluator m_arg3Impl; +}; + +// -------------------- CwiseBinaryOp -------------------- + +// this is a binary expression +template +struct evaluator > + : public binary_evaluator > +{ + typedef CwiseBinaryOp XprType; + typedef binary_evaluator > Base; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) : Base(xpr) {} +}; + +template +struct binary_evaluator, IndexBased, IndexBased> + : evaluator_base > +{ + typedef CwiseBinaryOp XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost + evaluator::CoeffReadCost + functor_traits::Cost, + + LhsFlags = evaluator::Flags, + RhsFlags = evaluator::Flags, + SameType = is_same::value, + StorageOrdersAgree = (int(LhsFlags)&RowMajorBit)==(int(RhsFlags)&RowMajorBit), + Flags0 = (int(LhsFlags) | int(RhsFlags)) & ( + HereditaryBits + | (int(LhsFlags) & int(RhsFlags) & + ( (StorageOrdersAgree ? LinearAccessBit : 0) + | (functor_traits::PacketAccess && StorageOrdersAgree && SameType ? PacketAccessBit : 0) + ) + ) + ), + Flags = (Flags0 & ~RowMajorBit) | (LhsFlags & RowMajorBit), + Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment,evaluator::Alignment) + }; + + EIGEN_DEVICE_FUNC explicit binary_evaluator(const XprType& xpr) + : m_functor(xpr.functor()), + m_lhsImpl(xpr.lhs()), + m_rhsImpl(xpr.rhs()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_functor(m_lhsImpl.coeff(row, col), m_rhsImpl.coeff(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_functor(m_lhsImpl.coeff(index), m_rhsImpl.coeff(index)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_functor.packetOp(m_lhsImpl.template packet(row, col), + m_rhsImpl.template packet(row, col)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return m_functor.packetOp(m_lhsImpl.template packet(index), + m_rhsImpl.template packet(index)); + } + +protected: + const BinaryOp m_functor; + evaluator m_lhsImpl; + evaluator m_rhsImpl; +}; + +// -------------------- CwiseUnaryView -------------------- + +template +struct unary_evaluator, IndexBased> + : evaluator_base > +{ + typedef CwiseUnaryView XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost + functor_traits::Cost, + + Flags = (evaluator::Flags & (HereditaryBits | LinearAccessBit | DirectAccessBit)), + + Alignment = 0 // FIXME it is not very clear why alignment is necessarily lost... + }; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& op) + : m_unaryOp(op.functor()), + m_argImpl(op.nestedExpression()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(functor_traits::Cost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_unaryOp(m_argImpl.coeff(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_unaryOp(m_argImpl.coeff(index)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_unaryOp(m_argImpl.coeffRef(row, col)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return m_unaryOp(m_argImpl.coeffRef(index)); + } + +protected: + const UnaryOp m_unaryOp; + evaluator m_argImpl; +}; + +// -------------------- Map -------------------- + +// FIXME perhaps the PlainObjectType could be provided by Derived::PlainObject ? +// but that might complicate template specialization +template +struct mapbase_evaluator; + +template +struct mapbase_evaluator : evaluator_base +{ + typedef Derived XprType; + typedef typename XprType::PointerType PointerType; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + enum { + IsRowMajor = XprType::RowsAtCompileTime, + ColsAtCompileTime = XprType::ColsAtCompileTime, + CoeffReadCost = NumTraits::ReadCost + }; + + EIGEN_DEVICE_FUNC explicit mapbase_evaluator(const XprType& map) + : m_data(const_cast(map.data())), + m_innerStride(map.innerStride()), + m_outerStride(map.outerStride()) + { + EIGEN_STATIC_ASSERT(EIGEN_IMPLIES(evaluator::Flags&PacketAccessBit, internal::inner_stride_at_compile_time::ret==1), + PACKET_ACCESS_REQUIRES_TO_HAVE_INNER_STRIDE_FIXED_TO_1); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_data[col * colStride() + row * rowStride()]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_data[index * m_innerStride.value()]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_data[col * colStride() + row * rowStride()]; + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return m_data[index * m_innerStride.value()]; + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + PointerType ptr = m_data + row * rowStride() + col * colStride(); + return internal::ploadt(ptr); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return internal::ploadt(m_data + index * m_innerStride.value()); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + PointerType ptr = m_data + row * rowStride() + col * colStride(); + return internal::pstoret(ptr, x); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + internal::pstoret(m_data + index * m_innerStride.value(), x); + } +protected: + EIGEN_DEVICE_FUNC + inline Index rowStride() const { return XprType::IsRowMajor ? m_outerStride.value() : m_innerStride.value(); } + EIGEN_DEVICE_FUNC + inline Index colStride() const { return XprType::IsRowMajor ? m_innerStride.value() : m_outerStride.value(); } + + PointerType m_data; + const internal::variable_if_dynamic m_innerStride; + const internal::variable_if_dynamic m_outerStride; +}; + +template +struct evaluator > + : public mapbase_evaluator, PlainObjectType> +{ + typedef Map XprType; + typedef typename XprType::Scalar Scalar; + // TODO: should check for smaller packet types once we can handle multi-sized packet types + typedef typename packet_traits::type PacketScalar; + + enum { + InnerStrideAtCompileTime = StrideType::InnerStrideAtCompileTime == 0 + ? int(PlainObjectType::InnerStrideAtCompileTime) + : int(StrideType::InnerStrideAtCompileTime), + OuterStrideAtCompileTime = StrideType::OuterStrideAtCompileTime == 0 + ? int(PlainObjectType::OuterStrideAtCompileTime) + : int(StrideType::OuterStrideAtCompileTime), + HasNoInnerStride = InnerStrideAtCompileTime == 1, + HasNoOuterStride = StrideType::OuterStrideAtCompileTime == 0, + HasNoStride = HasNoInnerStride && HasNoOuterStride, + IsDynamicSize = PlainObjectType::SizeAtCompileTime==Dynamic, + + PacketAccessMask = bool(HasNoInnerStride) ? ~int(0) : ~int(PacketAccessBit), + LinearAccessMask = bool(HasNoStride) || bool(PlainObjectType::IsVectorAtCompileTime) ? ~int(0) : ~int(LinearAccessBit), + Flags = int( evaluator::Flags) & (LinearAccessMask&PacketAccessMask), + + Alignment = int(MapOptions)&int(AlignedMask) + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& map) + : mapbase_evaluator(map) + { } +}; + +// -------------------- Ref -------------------- + +template +struct evaluator > + : public mapbase_evaluator, PlainObjectType> +{ + typedef Ref XprType; + + enum { + Flags = evaluator >::Flags, + Alignment = evaluator >::Alignment + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& ref) + : mapbase_evaluator(ref) + { } +}; + +// -------------------- Block -------------------- + +template::ret> struct block_evaluator; + +template +struct evaluator > + : block_evaluator +{ + typedef Block XprType; + typedef typename XprType::Scalar Scalar; + // TODO: should check for smaller packet types once we can handle multi-sized packet types + typedef typename packet_traits::type PacketScalar; + + enum { + CoeffReadCost = evaluator::CoeffReadCost, + + RowsAtCompileTime = traits::RowsAtCompileTime, + ColsAtCompileTime = traits::ColsAtCompileTime, + MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = traits::MaxColsAtCompileTime, + + ArgTypeIsRowMajor = (int(evaluator::Flags)&RowMajorBit) != 0, + IsRowMajor = (MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1) ? 1 + : (MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1) ? 0 + : ArgTypeIsRowMajor, + HasSameStorageOrderAsArgType = (IsRowMajor == ArgTypeIsRowMajor), + InnerSize = IsRowMajor ? int(ColsAtCompileTime) : int(RowsAtCompileTime), + InnerStrideAtCompileTime = HasSameStorageOrderAsArgType + ? int(inner_stride_at_compile_time::ret) + : int(outer_stride_at_compile_time::ret), + OuterStrideAtCompileTime = HasSameStorageOrderAsArgType + ? int(outer_stride_at_compile_time::ret) + : int(inner_stride_at_compile_time::ret), + MaskPacketAccessBit = (InnerStrideAtCompileTime == 1 || HasSameStorageOrderAsArgType) ? PacketAccessBit : 0, + + FlagsLinearAccessBit = (RowsAtCompileTime == 1 || ColsAtCompileTime == 1 || (InnerPanel && (evaluator::Flags&LinearAccessBit))) ? LinearAccessBit : 0, + FlagsRowMajorBit = XprType::Flags&RowMajorBit, + Flags0 = evaluator::Flags & ( (HereditaryBits & ~RowMajorBit) | + DirectAccessBit | + MaskPacketAccessBit), + Flags = Flags0 | FlagsLinearAccessBit | FlagsRowMajorBit, + + PacketAlignment = unpacket_traits::alignment, + Alignment0 = (InnerPanel && (OuterStrideAtCompileTime!=Dynamic) + && (OuterStrideAtCompileTime!=0) + && (((OuterStrideAtCompileTime * int(sizeof(Scalar))) % int(PacketAlignment)) == 0)) ? int(PacketAlignment) : 0, + Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, Alignment0) + }; + typedef block_evaluator block_evaluator_type; + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& block) : block_evaluator_type(block) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } +}; + +// no direct-access => dispatch to a unary evaluator +template +struct block_evaluator + : unary_evaluator > +{ + typedef Block XprType; + + EIGEN_DEVICE_FUNC explicit block_evaluator(const XprType& block) + : unary_evaluator(block) + {} +}; + +template +struct unary_evaluator, IndexBased> + : evaluator_base > +{ + typedef Block XprType; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& block) + : m_argImpl(block.nestedExpression()), + m_startRow(block.startRow()), + m_startCol(block.startCol()), + m_linear_offset(InnerPanel?(XprType::IsRowMajor ? block.startRow()*block.cols() : block.startCol()*block.rows()):0) + { } + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + enum { + RowsAtCompileTime = XprType::RowsAtCompileTime, + ForwardLinearAccess = InnerPanel && bool(evaluator::Flags&LinearAccessBit) + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_argImpl.coeff(m_startRow.value() + row, m_startCol.value() + col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + if (ForwardLinearAccess) + return m_argImpl.coeff(m_linear_offset.value() + index); + else + return coeff(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_argImpl.coeffRef(m_startRow.value() + row, m_startCol.value() + col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + if (ForwardLinearAccess) + return m_argImpl.coeffRef(m_linear_offset.value() + index); + else + return coeffRef(RowsAtCompileTime == 1 ? 0 : index, RowsAtCompileTime == 1 ? index : 0); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_argImpl.template packet(m_startRow.value() + row, m_startCol.value() + col); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + if (ForwardLinearAccess) + return m_argImpl.template packet(m_linear_offset.value() + index); + else + return packet(RowsAtCompileTime == 1 ? 0 : index, + RowsAtCompileTime == 1 ? index : 0); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + return m_argImpl.template writePacket(m_startRow.value() + row, m_startCol.value() + col, x); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + if (ForwardLinearAccess) + return m_argImpl.template writePacket(m_linear_offset.value() + index, x); + else + return writePacket(RowsAtCompileTime == 1 ? 0 : index, + RowsAtCompileTime == 1 ? index : 0, + x); + } + +protected: + evaluator m_argImpl; + const variable_if_dynamic m_startRow; + const variable_if_dynamic m_startCol; + const variable_if_dynamic m_linear_offset; +}; + +// TODO: This evaluator does not actually use the child evaluator; +// all action is via the data() as returned by the Block expression. + +template +struct block_evaluator + : mapbase_evaluator, + typename Block::PlainObject> +{ + typedef Block XprType; + typedef typename XprType::Scalar Scalar; + + EIGEN_DEVICE_FUNC explicit block_evaluator(const XprType& block) + : mapbase_evaluator(block) + { + // TODO: for the 3.3 release, this should be turned to an internal assertion, but let's keep it as is for the beta lifetime + eigen_assert(((internal::UIntPtr(block.data()) % EIGEN_PLAIN_ENUM_MAX(1,evaluator::Alignment)) == 0) && "data is not aligned"); + } +}; + + +// -------------------- Select -------------------- +// NOTE shall we introduce a ternary_evaluator? + +// TODO enable vectorization for Select +template +struct evaluator > + : evaluator_base > +{ + typedef Select XprType; + enum { + CoeffReadCost = evaluator::CoeffReadCost + + EIGEN_PLAIN_ENUM_MAX(evaluator::CoeffReadCost, + evaluator::CoeffReadCost), + + Flags = (unsigned int)evaluator::Flags & evaluator::Flags & HereditaryBits, + + Alignment = EIGEN_PLAIN_ENUM_MIN(evaluator::Alignment, evaluator::Alignment) + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& select) + : m_conditionImpl(select.conditionMatrix()), + m_thenImpl(select.thenMatrix()), + m_elseImpl(select.elseMatrix()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + if (m_conditionImpl.coeff(row, col)) + return m_thenImpl.coeff(row, col); + else + return m_elseImpl.coeff(row, col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + if (m_conditionImpl.coeff(index)) + return m_thenImpl.coeff(index); + else + return m_elseImpl.coeff(index); + } + +protected: + evaluator m_conditionImpl; + evaluator m_thenImpl; + evaluator m_elseImpl; +}; + + +// -------------------- Replicate -------------------- + +template +struct unary_evaluator > + : evaluator_base > +{ + typedef Replicate XprType; + typedef typename XprType::CoeffReturnType CoeffReturnType; + enum { + Factor = (RowFactor==Dynamic || ColFactor==Dynamic) ? Dynamic : RowFactor*ColFactor + }; + typedef typename internal::nested_eval::type ArgTypeNested; + typedef typename internal::remove_all::type ArgTypeNestedCleaned; + + enum { + CoeffReadCost = evaluator::CoeffReadCost, + LinearAccessMask = XprType::IsVectorAtCompileTime ? LinearAccessBit : 0, + Flags = (evaluator::Flags & (HereditaryBits|LinearAccessMask) & ~RowMajorBit) | (traits::Flags & RowMajorBit), + + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& replicate) + : m_arg(replicate.nestedExpression()), + m_argImpl(m_arg), + m_rows(replicate.nestedExpression().rows()), + m_cols(replicate.nestedExpression().cols()) + {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + // try to avoid using modulo; this is a pure optimization strategy + const Index actual_row = internal::traits::RowsAtCompileTime==1 ? 0 + : RowFactor==1 ? row + : row % m_rows.value(); + const Index actual_col = internal::traits::ColsAtCompileTime==1 ? 0 + : ColFactor==1 ? col + : col % m_cols.value(); + + return m_argImpl.coeff(actual_row, actual_col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + // try to avoid using modulo; this is a pure optimization strategy + const Index actual_index = internal::traits::RowsAtCompileTime==1 + ? (ColFactor==1 ? index : index%m_cols.value()) + : (RowFactor==1 ? index : index%m_rows.value()); + + return m_argImpl.coeff(actual_index); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + const Index actual_row = internal::traits::RowsAtCompileTime==1 ? 0 + : RowFactor==1 ? row + : row % m_rows.value(); + const Index actual_col = internal::traits::ColsAtCompileTime==1 ? 0 + : ColFactor==1 ? col + : col % m_cols.value(); + + return m_argImpl.template packet(actual_row, actual_col); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + const Index actual_index = internal::traits::RowsAtCompileTime==1 + ? (ColFactor==1 ? index : index%m_cols.value()) + : (RowFactor==1 ? index : index%m_rows.value()); + + return m_argImpl.template packet(actual_index); + } + +protected: + const ArgTypeNested m_arg; + evaluator m_argImpl; + const variable_if_dynamic m_rows; + const variable_if_dynamic m_cols; +}; + + +// -------------------- PartialReduxExpr -------------------- + +template< typename ArgType, typename MemberOp, int Direction> +struct evaluator > + : evaluator_base > +{ + typedef PartialReduxExpr XprType; + typedef typename internal::nested_eval::type ArgTypeNested; + typedef typename internal::remove_all::type ArgTypeNestedCleaned; + typedef typename ArgType::Scalar InputScalar; + typedef typename XprType::Scalar Scalar; + enum { + TraversalSize = Direction==int(Vertical) ? int(ArgType::RowsAtCompileTime) : int(ArgType::ColsAtCompileTime) + }; + typedef typename MemberOp::template Cost CostOpType; + enum { + CoeffReadCost = TraversalSize==Dynamic ? HugeCost + : TraversalSize * evaluator::CoeffReadCost + int(CostOpType::value), + + Flags = (traits::Flags&RowMajorBit) | (evaluator::Flags&(HereditaryBits&(~RowMajorBit))) | LinearAccessBit, + + Alignment = 0 // FIXME this will need to be improved once PartialReduxExpr is vectorized + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType xpr) + : m_arg(xpr.nestedExpression()), m_functor(xpr.functor()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(TraversalSize==Dynamic ? HugeCost : int(CostOpType::value)); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Scalar coeff(Index i, Index j) const + { + if (Direction==Vertical) + return m_functor(m_arg.col(j)); + else + return m_functor(m_arg.row(i)); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const Scalar coeff(Index index) const + { + if (Direction==Vertical) + return m_functor(m_arg.col(index)); + else + return m_functor(m_arg.row(index)); + } + +protected: + typename internal::add_const_on_value_type::type m_arg; + const MemberOp m_functor; +}; + + +// -------------------- MatrixWrapper and ArrayWrapper -------------------- +// +// evaluator_wrapper_base is a common base class for the +// MatrixWrapper and ArrayWrapper evaluators. + +template +struct evaluator_wrapper_base + : evaluator_base +{ + typedef typename remove_all::type ArgType; + enum { + CoeffReadCost = evaluator::CoeffReadCost, + Flags = evaluator::Flags, + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC explicit evaluator_wrapper_base(const ArgType& arg) : m_argImpl(arg) {} + + typedef typename ArgType::Scalar Scalar; + typedef typename ArgType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_argImpl.coeff(row, col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_argImpl.coeff(index); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_argImpl.coeffRef(row, col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return m_argImpl.coeffRef(index); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + return m_argImpl.template packet(row, col); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + return m_argImpl.template packet(index); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + m_argImpl.template writePacket(row, col, x); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + m_argImpl.template writePacket(index, x); + } + +protected: + evaluator m_argImpl; +}; + +template +struct unary_evaluator > + : evaluator_wrapper_base > +{ + typedef MatrixWrapper XprType; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& wrapper) + : evaluator_wrapper_base >(wrapper.nestedExpression()) + { } +}; + +template +struct unary_evaluator > + : evaluator_wrapper_base > +{ + typedef ArrayWrapper XprType; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& wrapper) + : evaluator_wrapper_base >(wrapper.nestedExpression()) + { } +}; + + +// -------------------- Reverse -------------------- + +// defined in Reverse.h: +template struct reverse_packet_cond; + +template +struct unary_evaluator > + : evaluator_base > +{ + typedef Reverse XprType; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + enum { + IsRowMajor = XprType::IsRowMajor, + IsColMajor = !IsRowMajor, + ReverseRow = (Direction == Vertical) || (Direction == BothDirections), + ReverseCol = (Direction == Horizontal) || (Direction == BothDirections), + ReversePacket = (Direction == BothDirections) + || ((Direction == Vertical) && IsColMajor) + || ((Direction == Horizontal) && IsRowMajor), + + CoeffReadCost = evaluator::CoeffReadCost, + + // let's enable LinearAccess only with vectorization because of the product overhead + // FIXME enable DirectAccess with negative strides? + Flags0 = evaluator::Flags, + LinearAccess = ( (Direction==BothDirections) && (int(Flags0)&PacketAccessBit) ) + || ((ReverseRow && XprType::ColsAtCompileTime==1) || (ReverseCol && XprType::RowsAtCompileTime==1)) + ? LinearAccessBit : 0, + + Flags = int(Flags0) & (HereditaryBits | PacketAccessBit | LinearAccess), + + Alignment = 0 // FIXME in some rare cases, Alignment could be preserved, like a Vector4f. + }; + + EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& reverse) + : m_argImpl(reverse.nestedExpression()), + m_rows(ReverseRow ? reverse.nestedExpression().rows() : 1), + m_cols(ReverseCol ? reverse.nestedExpression().cols() : 1) + { } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index col) const + { + return m_argImpl.coeff(ReverseRow ? m_rows.value() - row - 1 : row, + ReverseCol ? m_cols.value() - col - 1 : col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_argImpl.coeff(m_rows.value() * m_cols.value() - index - 1); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index col) + { + return m_argImpl.coeffRef(ReverseRow ? m_rows.value() - row - 1 : row, + ReverseCol ? m_cols.value() - col - 1 : col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return m_argImpl.coeffRef(m_rows.value() * m_cols.value() - index - 1); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index row, Index col) const + { + enum { + PacketSize = unpacket_traits::size, + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 + }; + typedef internal::reverse_packet_cond reverse_packet; + return reverse_packet::run(m_argImpl.template packet( + ReverseRow ? m_rows.value() - row - OffsetRow : row, + ReverseCol ? m_cols.value() - col - OffsetCol : col)); + } + + template + EIGEN_STRONG_INLINE + PacketType packet(Index index) const + { + enum { PacketSize = unpacket_traits::size }; + return preverse(m_argImpl.template packet(m_rows.value() * m_cols.value() - index - PacketSize)); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index row, Index col, const PacketType& x) + { + // FIXME we could factorize some code with packet(i,j) + enum { + PacketSize = unpacket_traits::size, + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1 + }; + typedef internal::reverse_packet_cond reverse_packet; + m_argImpl.template writePacket( + ReverseRow ? m_rows.value() - row - OffsetRow : row, + ReverseCol ? m_cols.value() - col - OffsetCol : col, + reverse_packet::run(x)); + } + + template + EIGEN_STRONG_INLINE + void writePacket(Index index, const PacketType& x) + { + enum { PacketSize = unpacket_traits::size }; + m_argImpl.template writePacket + (m_rows.value() * m_cols.value() - index - PacketSize, preverse(x)); + } + +protected: + evaluator m_argImpl; + + // If we do not reverse rows, then we do not need to know the number of rows; same for columns + // Nonetheless, in this case it is important to set to 1 such that the coeff(index) method works fine for vectors. + const variable_if_dynamic m_rows; + const variable_if_dynamic m_cols; +}; + + +// -------------------- Diagonal -------------------- + +template +struct evaluator > + : evaluator_base > +{ + typedef Diagonal XprType; + + enum { + CoeffReadCost = evaluator::CoeffReadCost, + + Flags = (unsigned int)(evaluator::Flags & (HereditaryBits | DirectAccessBit) & ~RowMajorBit) | LinearAccessBit, + + Alignment = 0 + }; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& diagonal) + : m_argImpl(diagonal.nestedExpression()), + m_index(diagonal.index()) + { } + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index row, Index) const + { + return m_argImpl.coeff(row + rowOffset(), row + colOffset()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + CoeffReturnType coeff(Index index) const + { + return m_argImpl.coeff(index + rowOffset(), index + colOffset()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index row, Index) + { + return m_argImpl.coeffRef(row + rowOffset(), row + colOffset()); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Scalar& coeffRef(Index index) + { + return m_argImpl.coeffRef(index + rowOffset(), index + colOffset()); + } + +protected: + evaluator m_argImpl; + const internal::variable_if_dynamicindex m_index; + +private: + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rowOffset() const { return m_index.value() > 0 ? 0 : -m_index.value(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index colOffset() const { return m_index.value() > 0 ? m_index.value() : 0; } +}; + + +//---------------------------------------------------------------------- +// deprecated code +//---------------------------------------------------------------------- + +// -------------------- EvalToTemp -------------------- + +// expression class for evaluating nested expression to a temporary + +template class EvalToTemp; + +template +struct traits > + : public traits +{ }; + +template +class EvalToTemp + : public dense_xpr_base >::type +{ + public: + + typedef typename dense_xpr_base::type Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(EvalToTemp) + + explicit EvalToTemp(const ArgType& arg) + : m_arg(arg) + { } + + const ArgType& arg() const + { + return m_arg; + } + + Index rows() const + { + return m_arg.rows(); + } + + Index cols() const + { + return m_arg.cols(); + } + + private: + const ArgType& m_arg; +}; + +template +struct evaluator > + : public evaluator +{ + typedef EvalToTemp XprType; + typedef typename ArgType::PlainObject PlainObject; + typedef evaluator Base; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) + : m_result(xpr.arg()) + { + ::new (static_cast(this)) Base(m_result); + } + + // This constructor is used when nesting an EvalTo evaluator in another evaluator + EIGEN_DEVICE_FUNC evaluator(const ArgType& arg) + : m_result(arg) + { + ::new (static_cast(this)) Base(m_result); + } + +protected: + PlainObject m_result; +}; + +} // namespace internal + +} // end namespace Eigen + +#endif // EIGEN_COREEVALUATORS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreIterators.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreIterators.h new file mode 100644 index 0000000000000000000000000000000000000000..4eb42b93af18d06efd093dfd918297a00274ee31 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CoreIterators.h @@ -0,0 +1,127 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_COREITERATORS_H +#define EIGEN_COREITERATORS_H + +namespace Eigen { + +/* This file contains the respective InnerIterator definition of the expressions defined in Eigen/Core + */ + +namespace internal { + +template +class inner_iterator_selector; + +} + +/** \class InnerIterator + * \brief An InnerIterator allows to loop over the element of any matrix expression. + * + * \warning To be used with care because an evaluator is constructed every time an InnerIterator iterator is constructed. + * + * TODO: add a usage example + */ +template +class InnerIterator +{ +protected: + typedef internal::inner_iterator_selector::Kind> IteratorType; + typedef internal::evaluator EvaluatorType; + typedef typename internal::traits::Scalar Scalar; +public: + /** Construct an iterator over the \a outerId -th row or column of \a xpr */ + InnerIterator(const XprType &xpr, const Index &outerId) + : m_eval(xpr), m_iter(m_eval, outerId, xpr.innerSize()) + {} + + /// \returns the value of the current coefficient. + EIGEN_STRONG_INLINE Scalar value() const { return m_iter.value(); } + /** Increment the iterator \c *this to the next non-zero coefficient. + * Explicit zeros are not skipped over. To skip explicit zeros, see class SparseView + */ + EIGEN_STRONG_INLINE InnerIterator& operator++() { m_iter.operator++(); return *this; } + /// \returns the column or row index of the current coefficient. + EIGEN_STRONG_INLINE Index index() const { return m_iter.index(); } + /// \returns the row index of the current coefficient. + EIGEN_STRONG_INLINE Index row() const { return m_iter.row(); } + /// \returns the column index of the current coefficient. + EIGEN_STRONG_INLINE Index col() const { return m_iter.col(); } + /// \returns \c true if the iterator \c *this still references a valid coefficient. + EIGEN_STRONG_INLINE operator bool() const { return m_iter; } + +protected: + EvaluatorType m_eval; + IteratorType m_iter; +private: + // If you get here, then you're not using the right InnerIterator type, e.g.: + // SparseMatrix A; + // SparseMatrix::InnerIterator it(A,0); + template InnerIterator(const EigenBase&,Index outer); +}; + +namespace internal { + +// Generic inner iterator implementation for dense objects +template +class inner_iterator_selector +{ +protected: + typedef evaluator EvaluatorType; + typedef typename traits::Scalar Scalar; + enum { IsRowMajor = (XprType::Flags&RowMajorBit)==RowMajorBit }; + +public: + EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &innerSize) + : m_eval(eval), m_inner(0), m_outer(outerId), m_end(innerSize) + {} + + EIGEN_STRONG_INLINE Scalar value() const + { + return (IsRowMajor) ? m_eval.coeff(m_outer, m_inner) + : m_eval.coeff(m_inner, m_outer); + } + + EIGEN_STRONG_INLINE inner_iterator_selector& operator++() { m_inner++; return *this; } + + EIGEN_STRONG_INLINE Index index() const { return m_inner; } + inline Index row() const { return IsRowMajor ? m_outer : index(); } + inline Index col() const { return IsRowMajor ? index() : m_outer; } + + EIGEN_STRONG_INLINE operator bool() const { return m_inner < m_end && m_inner>=0; } + +protected: + const EvaluatorType& m_eval; + Index m_inner; + const Index m_outer; + const Index m_end; +}; + +// For iterator-based evaluator, inner-iterator is already implemented as +// evaluator<>::InnerIterator +template +class inner_iterator_selector + : public evaluator::InnerIterator +{ +protected: + typedef typename evaluator::InnerIterator Base; + typedef evaluator EvaluatorType; + +public: + EIGEN_STRONG_INLINE inner_iterator_selector(const EvaluatorType &eval, const Index &outerId, const Index &/*innerSize*/) + : Base(eval, outerId) + {} +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_COREITERATORS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h new file mode 100644 index 0000000000000000000000000000000000000000..a36765e396bd439ef85d096a0fd6d3a126a9fbfe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseBinaryOp.h @@ -0,0 +1,184 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CWISE_BINARY_OP_H +#define EIGEN_CWISE_BINARY_OP_H + +namespace Eigen { + +namespace internal { +template +struct traits > +{ + // we must not inherit from traits since it has + // the potential to cause problems with MSVC + typedef typename remove_all::type Ancestor; + typedef typename traits::XprKind XprKind; + enum { + RowsAtCompileTime = traits::RowsAtCompileTime, + ColsAtCompileTime = traits::ColsAtCompileTime, + MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = traits::MaxColsAtCompileTime + }; + + // even though we require Lhs and Rhs to have the same scalar type (see CwiseBinaryOp constructor), + // we still want to handle the case when the result type is different. + typedef typename result_of< + BinaryOp( + const typename Lhs::Scalar&, + const typename Rhs::Scalar& + ) + >::type Scalar; + typedef typename cwise_promote_storage_type::StorageKind, + typename traits::StorageKind, + BinaryOp>::ret StorageKind; + typedef typename promote_index_type::StorageIndex, + typename traits::StorageIndex>::type StorageIndex; + typedef typename Lhs::Nested LhsNested; + typedef typename Rhs::Nested RhsNested; + typedef typename remove_reference::type _LhsNested; + typedef typename remove_reference::type _RhsNested; + enum { + Flags = cwise_promote_storage_order::StorageKind,typename traits::StorageKind,_LhsNested::Flags & RowMajorBit,_RhsNested::Flags & RowMajorBit>::value + }; +}; +} // end namespace internal + +template +class CwiseBinaryOpImpl; + +/** \class CwiseBinaryOp + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise binary operator is applied to two expressions + * + * \tparam BinaryOp template functor implementing the operator + * \tparam LhsType the type of the left-hand side + * \tparam RhsType the type of the right-hand side + * + * This class represents an expression where a coefficient-wise binary operator is applied to two expressions. + * It is the return type of binary operators, by which we mean only those binary operators where + * both the left-hand side and the right-hand side are Eigen expressions. + * For example, the return type of matrix1+matrix2 is a CwiseBinaryOp. + * + * Most of the time, this is the only way that it is used, so you typically don't have to name + * CwiseBinaryOp types explicitly. + * + * \sa MatrixBase::binaryExpr(const MatrixBase &,const CustomBinaryOp &) const, class CwiseUnaryOp, class CwiseNullaryOp + */ +template +class CwiseBinaryOp : + public CwiseBinaryOpImpl< + BinaryOp, LhsType, RhsType, + typename internal::cwise_promote_storage_type::StorageKind, + typename internal::traits::StorageKind, + BinaryOp>::ret>, + internal::no_assignment_operator +{ + public: + + typedef typename internal::remove_all::type Functor; + typedef typename internal::remove_all::type Lhs; + typedef typename internal::remove_all::type Rhs; + + typedef typename CwiseBinaryOpImpl< + BinaryOp, LhsType, RhsType, + typename internal::cwise_promote_storage_type::StorageKind, + typename internal::traits::StorageKind, + BinaryOp>::ret>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseBinaryOp) + + typedef typename internal::ref_selector::type LhsNested; + typedef typename internal::ref_selector::type RhsNested; + typedef typename internal::remove_reference::type _LhsNested; + typedef typename internal::remove_reference::type _RhsNested; + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CwiseBinaryOp(const Lhs& aLhs, const Rhs& aRhs, const BinaryOp& func = BinaryOp()) + : m_lhs(aLhs), m_rhs(aRhs), m_functor(func) + { + EIGEN_CHECK_BINARY_COMPATIBILIY(BinaryOp,typename Lhs::Scalar,typename Rhs::Scalar); + // require the sizes to match + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Lhs, Rhs) + eigen_assert(aLhs.rows() == aRhs.rows() && aLhs.cols() == aRhs.cols()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rows() const { + // return the fixed size type if available to enable compile time optimizations + if (internal::traits::type>::RowsAtCompileTime==Dynamic) + return m_rhs.rows(); + else + return m_lhs.rows(); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index cols() const { + // return the fixed size type if available to enable compile time optimizations + if (internal::traits::type>::ColsAtCompileTime==Dynamic) + return m_rhs.cols(); + else + return m_lhs.cols(); + } + + /** \returns the left hand side nested expression */ + EIGEN_DEVICE_FUNC + const _LhsNested& lhs() const { return m_lhs; } + /** \returns the right hand side nested expression */ + EIGEN_DEVICE_FUNC + const _RhsNested& rhs() const { return m_rhs; } + /** \returns the functor representing the binary operation */ + EIGEN_DEVICE_FUNC + const BinaryOp& functor() const { return m_functor; } + + protected: + LhsNested m_lhs; + RhsNested m_rhs; + const BinaryOp m_functor; +}; + +// Generic API dispatcher +template +class CwiseBinaryOpImpl + : public internal::generic_xpr_base >::type +{ +public: + typedef typename internal::generic_xpr_base >::type Base; +}; + +/** replaces \c *this by \c *this - \a other. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_STRONG_INLINE Derived & +MatrixBase::operator-=(const MatrixBase &other) +{ + call_assignment(derived(), other.derived(), internal::sub_assign_op()); + return derived(); +} + +/** replaces \c *this by \c *this + \a other. + * + * \returns a reference to \c *this + */ +template +template +EIGEN_STRONG_INLINE Derived & +MatrixBase::operator+=(const MatrixBase& other) +{ + call_assignment(derived(), other.derived(), internal::add_assign_op()); + return derived(); +} + +} // end namespace Eigen + +#endif // EIGEN_CWISE_BINARY_OP_H + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseNullaryOp.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseNullaryOp.h new file mode 100644 index 0000000000000000000000000000000000000000..ddd607e3832110602ff54acb97c67b94ecabbe18 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseNullaryOp.h @@ -0,0 +1,866 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CWISE_NULLARY_OP_H +#define EIGEN_CWISE_NULLARY_OP_H + +namespace Eigen { + +namespace internal { +template +struct traits > : traits +{ + enum { + Flags = traits::Flags & RowMajorBit + }; +}; + +} // namespace internal + +/** \class CwiseNullaryOp + * \ingroup Core_Module + * + * \brief Generic expression of a matrix where all coefficients are defined by a functor + * + * \tparam NullaryOp template functor implementing the operator + * \tparam PlainObjectType the underlying plain matrix/array type + * + * This class represents an expression of a generic nullary operator. + * It is the return type of the Ones(), Zero(), Constant(), Identity() and Random() methods, + * and most of the time this is the only way it is used. + * + * However, if you want to write a function returning such an expression, you + * will need to use this class. + * + * The functor NullaryOp must expose one of the following method: + + + + +
\c operator()() if the procedural generation does not depend on the coefficient entries (e.g., random numbers)
\c operator()(Index i)if the procedural generation makes sense for vectors only and that it depends on the coefficient index \c i (e.g., linspace)
\c operator()(Index i,Index j)if the procedural generation depends on the matrix coordinates \c i, \c j (e.g., to generate a checkerboard with 0 and 1)
+ * It is also possible to expose the last two operators if the generation makes sense for matrices but can be optimized for vectors. + * + * See DenseBase::NullaryExpr(Index,const CustomNullaryOp&) for an example binding + * C++11 random number generators. + * + * A nullary expression can also be used to implement custom sophisticated matrix manipulations + * that cannot be covered by the existing set of natively supported matrix manipulations. + * See this \ref TopicCustomizing_NullaryExpr "page" for some examples and additional explanations + * on the behavior of CwiseNullaryOp. + * + * \sa class CwiseUnaryOp, class CwiseBinaryOp, DenseBase::NullaryExpr + */ +template +class CwiseNullaryOp : public internal::dense_xpr_base< CwiseNullaryOp >::type, internal::no_assignment_operator +{ + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(CwiseNullaryOp) + + EIGEN_DEVICE_FUNC + CwiseNullaryOp(Index rows, Index cols, const NullaryOp& func = NullaryOp()) + : m_rows(rows), m_cols(cols), m_functor(func) + { + eigen_assert(rows >= 0 + && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) + && cols >= 0 + && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols)); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rows() const { return m_rows.value(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index cols() const { return m_cols.value(); } + + /** \returns the functor representing the nullary operation */ + EIGEN_DEVICE_FUNC + const NullaryOp& functor() const { return m_functor; } + + protected: + const internal::variable_if_dynamic m_rows; + const internal::variable_if_dynamic m_cols; + const NullaryOp m_functor; +}; + + +/** \returns an expression of a matrix defined by a custom functor \a func + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CwiseNullaryOp::PlainObject> +DenseBase::NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func) +{ + return CwiseNullaryOp(rows, cols, func); +} + +/** \returns an expression of a matrix defined by a custom functor \a func + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * Here is an example with C++11 random generators: \include random_cpp11.cpp + * Output: \verbinclude random_cpp11.out + * + * \sa class CwiseNullaryOp + */ +template +template +EIGEN_STRONG_INLINE const CwiseNullaryOp::PlainObject> +DenseBase::NullaryExpr(Index size, const CustomNullaryOp& func) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + if(RowsAtCompileTime == 1) return CwiseNullaryOp(1, size, func); + else return CwiseNullaryOp(size, 1, func); +} + +/** \returns an expression of a matrix defined by a custom functor \a func + * + * This variant is only for fixed-size DenseBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CwiseNullaryOp::PlainObject> +DenseBase::NullaryExpr(const CustomNullaryOp& func) +{ + return CwiseNullaryOp(RowsAtCompileTime, ColsAtCompileTime, func); +} + +/** \returns an expression of a constant matrix of value \a value + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this DenseBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Constant(Index rows, Index cols, const Scalar& value) +{ + return DenseBase::NullaryExpr(rows, cols, internal::scalar_constant_op(value)); +} + +/** \returns an expression of a constant matrix of value \a value + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this DenseBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Constant(Index size, const Scalar& value) +{ + return DenseBase::NullaryExpr(size, internal::scalar_constant_op(value)); +} + +/** \returns an expression of a constant matrix of value \a value + * + * This variant is only for fixed-size DenseBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * The template parameter \a CustomNullaryOp is the type of the functor. + * + * \sa class CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Constant(const Scalar& value) +{ + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + return DenseBase::NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_constant_op(value)); +} + +/** \deprecated because of accuracy loss. In Eigen 3.3, it is an alias for LinSpaced(Index,const Scalar&,const Scalar&) + * + * \sa LinSpaced(Index,Scalar,Scalar), setLinSpaced(Index,const Scalar&,const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return DenseBase::NullaryExpr(size, internal::linspaced_op(low,high,size)); +} + +/** \deprecated because of accuracy loss. In Eigen 3.3, it is an alias for LinSpaced(const Scalar&,const Scalar&) + * + * \sa LinSpaced(Scalar,Scalar) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(Sequential_t, const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, internal::linspaced_op(low,high,Derived::SizeAtCompileTime)); +} + +/** + * \brief Sets a linearly spaced vector. + * + * The function generates 'size' equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * Example: \include DenseBase_LinSpaced.cpp + * Output: \verbinclude DenseBase_LinSpaced.out + * + * For integer scalar types, an even spacing is possible if and only if the length of the range, + * i.e., \c high-low is a scalar multiple of \c size-1, or if \c size is a scalar multiple of the + * number of values \c high-low+1 (meaning each value can be repeated the same number of time). + * If one of these two considions is not satisfied, then \c high is lowered to the largest value + * satisfying one of this constraint. + * Here are some examples: + * + * Example: \include DenseBase_LinSpacedInt.cpp + * Output: \verbinclude DenseBase_LinSpacedInt.out + * + * \sa setLinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(Index size, const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return DenseBase::NullaryExpr(size, internal::linspaced_op(low,high,size)); +} + +/** + * \copydoc DenseBase::LinSpaced(Index, const Scalar&, const Scalar&) + * Special version for fixed size types which does not require the size parameter. + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::RandomAccessLinSpacedReturnType +DenseBase::LinSpaced(const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + return DenseBase::NullaryExpr(Derived::SizeAtCompileTime, internal::linspaced_op(low,high,Derived::SizeAtCompileTime)); +} + +/** \returns true if all coefficients in this matrix are approximately equal to \a val, to within precision \a prec */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isApproxToConstant +(const Scalar& val, const RealScalar& prec) const +{ + typename internal::nested_eval::type self(derived()); + for(Index j = 0; j < cols(); ++j) + for(Index i = 0; i < rows(); ++i) + if(!internal::isApprox(self.coeff(i, j), val, prec)) + return false; + return true; +} + +/** This is just an alias for isApproxToConstant(). + * + * \returns true if all coefficients in this matrix are approximately equal to \a value, to within precision \a prec */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isConstant +(const Scalar& val, const RealScalar& prec) const +{ + return isApproxToConstant(val, prec); +} + +/** Alias for setConstant(): sets all coefficients in this expression to \a val. + * + * \sa setConstant(), Constant(), class CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void DenseBase::fill(const Scalar& val) +{ + setConstant(val); +} + +/** Sets all coefficients in this expression to value \a val. + * + * \sa fill(), setConstant(Index,const Scalar&), setConstant(Index,Index,const Scalar&), setZero(), setOnes(), Constant(), class CwiseNullaryOp, setZero(), setOnes() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setConstant(const Scalar& val) +{ + return derived() = Constant(rows(), cols(), val); +} + +/** Resizes to the given \a size, and sets all coefficients in this expression to the given value \a val. + * + * \only_for_vectors + * + * Example: \include Matrix_setConstant_int.cpp + * Output: \verbinclude Matrix_setConstant_int.out + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setConstant(Index size, const Scalar& val) +{ + resize(size); + return setConstant(val); +} + +/** Resizes to the given size, and sets all coefficients in this expression to the given value \a val. + * + * \param rows the new number of rows + * \param cols the new number of columns + * \param val the value to which all coefficients are set + * + * Example: \include Matrix_setConstant_int_int.cpp + * Output: \verbinclude Matrix_setConstant_int_int.out + * + * \sa MatrixBase::setConstant(const Scalar&), setConstant(Index,const Scalar&), class CwiseNullaryOp, MatrixBase::Constant(const Scalar&) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setConstant(Index rows, Index cols, const Scalar& val) +{ + resize(rows, cols); + return setConstant(val); +} + +/** + * \brief Sets a linearly spaced vector. + * + * The function generates 'size' equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * Example: \include DenseBase_setLinSpaced.cpp + * Output: \verbinclude DenseBase_setLinSpaced.out + * + * For integer scalar types, do not miss the explanations on the definition + * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. + * + * \sa LinSpaced(Index,const Scalar&,const Scalar&), CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(Index newSize, const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return derived() = Derived::NullaryExpr(newSize, internal::linspaced_op(low,high,newSize)); +} + +/** + * \brief Sets a linearly spaced vector. + * + * The function fills \c *this with equally spaced values in the closed interval [low,high]. + * When size is set to 1, a vector of length 1 containing 'high' is returned. + * + * \only_for_vectors + * + * For integer scalar types, do not miss the explanations on the definition + * of \link LinSpaced(Index,const Scalar&,const Scalar&) even spacing \endlink. + * + * \sa LinSpaced(Index,const Scalar&,const Scalar&), setLinSpaced(Index, const Scalar&, const Scalar&), CwiseNullaryOp + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setLinSpaced(const Scalar& low, const Scalar& high) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return setLinSpaced(size(), low, high); +} + +// zero: + +/** \returns an expression of a zero matrix. + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Zero() should be used + * instead. + * + * Example: \include MatrixBase_zero_int_int.cpp + * Output: \verbinclude MatrixBase_zero_int_int.out + * + * \sa Zero(), Zero(Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Zero(Index rows, Index cols) +{ + return Constant(rows, cols, Scalar(0)); +} + +/** \returns an expression of a zero vector. + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Zero() should be used + * instead. + * + * Example: \include MatrixBase_zero_int.cpp + * Output: \verbinclude MatrixBase_zero_int.out + * + * \sa Zero(), Zero(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Zero(Index size) +{ + return Constant(size, Scalar(0)); +} + +/** \returns an expression of a fixed-size zero matrix or vector. + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_zero.cpp + * Output: \verbinclude MatrixBase_zero.out + * + * \sa Zero(Index), Zero(Index,Index) + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Zero() +{ + return Constant(Scalar(0)); +} + +/** \returns true if *this is approximately equal to the zero matrix, + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isZero.cpp + * Output: \verbinclude MatrixBase_isZero.out + * + * \sa class CwiseNullaryOp, Zero() + */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isZero(const RealScalar& prec) const +{ + typename internal::nested_eval::type self(derived()); + for(Index j = 0; j < cols(); ++j) + for(Index i = 0; i < rows(); ++i) + if(!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) + return false; + return true; +} + +/** Sets all coefficients in this expression to zero. + * + * Example: \include MatrixBase_setZero.cpp + * Output: \verbinclude MatrixBase_setZero.out + * + * \sa class CwiseNullaryOp, Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setZero() +{ + return setConstant(Scalar(0)); +} + +/** Resizes to the given \a size, and sets all coefficients in this expression to zero. + * + * \only_for_vectors + * + * Example: \include Matrix_setZero_int.cpp + * Output: \verbinclude Matrix_setZero_int.out + * + * \sa DenseBase::setZero(), setZero(Index,Index), class CwiseNullaryOp, DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setZero(Index newSize) +{ + resize(newSize); + return setConstant(Scalar(0)); +} + +/** Resizes to the given size, and sets all coefficients in this expression to zero. + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setZero_int_int.cpp + * Output: \verbinclude Matrix_setZero_int_int.out + * + * \sa DenseBase::setZero(), setZero(Index), class CwiseNullaryOp, DenseBase::Zero() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setZero(Index rows, Index cols) +{ + resize(rows, cols); + return setConstant(Scalar(0)); +} + +// ones: + +/** \returns an expression of a matrix where all coefficients equal one. + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Ones() should be used + * instead. + * + * Example: \include MatrixBase_ones_int_int.cpp + * Output: \verbinclude MatrixBase_ones_int_int.out + * + * \sa Ones(), Ones(Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Ones(Index rows, Index cols) +{ + return Constant(rows, cols, Scalar(1)); +} + +/** \returns an expression of a vector where all coefficients equal one. + * + * The parameter \a newSize is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Ones() should be used + * instead. + * + * Example: \include MatrixBase_ones_int.cpp + * Output: \verbinclude MatrixBase_ones_int.out + * + * \sa Ones(), Ones(Index,Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Ones(Index newSize) +{ + return Constant(newSize, Scalar(1)); +} + +/** \returns an expression of a fixed-size matrix or vector where all coefficients equal one. + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_ones.cpp + * Output: \verbinclude MatrixBase_ones.out + * + * \sa Ones(Index), Ones(Index,Index), isOnes(), class Ones + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename DenseBase::ConstantReturnType +DenseBase::Ones() +{ + return Constant(Scalar(1)); +} + +/** \returns true if *this is approximately equal to the matrix where all coefficients + * are equal to 1, within the precision given by \a prec. + * + * Example: \include MatrixBase_isOnes.cpp + * Output: \verbinclude MatrixBase_isOnes.out + * + * \sa class CwiseNullaryOp, Ones() + */ +template +EIGEN_DEVICE_FUNC bool DenseBase::isOnes +(const RealScalar& prec) const +{ + return isApproxToConstant(Scalar(1), prec); +} + +/** Sets all coefficients in this expression to one. + * + * Example: \include MatrixBase_setOnes.cpp + * Output: \verbinclude MatrixBase_setOnes.out + * + * \sa class CwiseNullaryOp, Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& DenseBase::setOnes() +{ + return setConstant(Scalar(1)); +} + +/** Resizes to the given \a newSize, and sets all coefficients in this expression to one. + * + * \only_for_vectors + * + * Example: \include Matrix_setOnes_int.cpp + * Output: \verbinclude Matrix_setOnes_int.out + * + * \sa MatrixBase::setOnes(), setOnes(Index,Index), class CwiseNullaryOp, MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setOnes(Index newSize) +{ + resize(newSize); + return setConstant(Scalar(1)); +} + +/** Resizes to the given size, and sets all coefficients in this expression to one. + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setOnes_int_int.cpp + * Output: \verbinclude Matrix_setOnes_int_int.out + * + * \sa MatrixBase::setOnes(), setOnes(Index), class CwiseNullaryOp, MatrixBase::Ones() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setOnes(Index rows, Index cols) +{ + resize(rows, cols); + return setConstant(Scalar(1)); +} + +// Identity: + +/** \returns an expression of the identity matrix (not necessarily square). + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Identity() should be used + * instead. + * + * Example: \include MatrixBase_identity_int_int.cpp + * Output: \verbinclude MatrixBase_identity_int_int.out + * + * \sa Identity(), setIdentity(), isIdentity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::IdentityReturnType +MatrixBase::Identity(Index rows, Index cols) +{ + return DenseBase::NullaryExpr(rows, cols, internal::scalar_identity_op()); +} + +/** \returns an expression of the identity matrix (not necessarily square). + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variant taking size arguments. + * + * Example: \include MatrixBase_identity.cpp + * Output: \verbinclude MatrixBase_identity.out + * + * \sa Identity(Index,Index), setIdentity(), isIdentity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::IdentityReturnType +MatrixBase::Identity() +{ + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + return MatrixBase::NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_identity_op()); +} + +/** \returns true if *this is approximately equal to the identity matrix + * (not necessarily square), + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isIdentity.cpp + * Output: \verbinclude MatrixBase_isIdentity.out + * + * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), setIdentity() + */ +template +bool MatrixBase::isIdentity +(const RealScalar& prec) const +{ + typename internal::nested_eval::type self(derived()); + for(Index j = 0; j < cols(); ++j) + { + for(Index i = 0; i < rows(); ++i) + { + if(i == j) + { + if(!internal::isApprox(self.coeff(i, j), static_cast(1), prec)) + return false; + } + else + { + if(!internal::isMuchSmallerThan(self.coeff(i, j), static_cast(1), prec)) + return false; + } + } + } + return true; +} + +namespace internal { + +template=16)> +struct setIdentity_impl +{ + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Derived& run(Derived& m) + { + return m = Derived::Identity(m.rows(), m.cols()); + } +}; + +template +struct setIdentity_impl +{ + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Derived& run(Derived& m) + { + m.setZero(); + const Index size = numext::mini(m.rows(), m.cols()); + for(Index i = 0; i < size; ++i) m.coeffRef(i,i) = typename Derived::Scalar(1); + return m; + } +}; + +} // end namespace internal + +/** Writes the identity expression (not necessarily square) into *this. + * + * Example: \include MatrixBase_setIdentity.cpp + * Output: \verbinclude MatrixBase_setIdentity.out + * + * \sa class CwiseNullaryOp, Identity(), Identity(Index,Index), isIdentity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity() +{ + return internal::setIdentity_impl::run(derived()); +} + +/** \brief Resizes to the given size, and writes the identity expression (not necessarily square) into *this. + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setIdentity_int_int.cpp + * Output: \verbinclude Matrix_setIdentity_int_int.out + * + * \sa MatrixBase::setIdentity(), class CwiseNullaryOp, MatrixBase::Identity() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Derived& MatrixBase::setIdentity(Index rows, Index cols) +{ + derived().resize(rows, cols); + return setIdentity(); +} + +/** \returns an expression of the i-th unit (basis) vector. + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit(Index newSize, Index i) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return BasisReturnType(SquareMatrixType::Identity(newSize,newSize), i); +} + +/** \returns an expression of the i-th unit (basis) vector. + * + * \only_for_vectors + * + * This variant is for fixed-size vector only. + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::UnitX(), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::Unit(Index i) +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + return BasisReturnType(SquareMatrixType::Identity(),i); +} + +/** \returns an expression of the X axis unit vector (1{,0}^*) + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitX() +{ return Derived::Unit(0); } + +/** \returns an expression of the Y axis unit vector (0,1{,0}^*) + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitY() +{ return Derived::Unit(1); } + +/** \returns an expression of the Z axis unit vector (0,0,1{,0}^*) + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitZ() +{ return Derived::Unit(2); } + +/** \returns an expression of the W axis unit vector (0,0,0,1) + * + * \only_for_vectors + * + * \sa MatrixBase::Unit(Index,Index), MatrixBase::Unit(Index), MatrixBase::UnitY(), MatrixBase::UnitZ(), MatrixBase::UnitW() + */ +template +EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const typename MatrixBase::BasisReturnType MatrixBase::UnitW() +{ return Derived::Unit(3); } + +} // end namespace Eigen + +#endif // EIGEN_CWISE_NULLARY_OP_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseTernaryOp.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseTernaryOp.h new file mode 100644 index 0000000000000000000000000000000000000000..9f3576fecefb90fc91cd37e9eb3328fcdcf8cf17 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseTernaryOp.h @@ -0,0 +1,197 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2016 Eugene Brevdo +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CWISE_TERNARY_OP_H +#define EIGEN_CWISE_TERNARY_OP_H + +namespace Eigen { + +namespace internal { +template +struct traits > { + // we must not inherit from traits since it has + // the potential to cause problems with MSVC + typedef typename remove_all::type Ancestor; + typedef typename traits::XprKind XprKind; + enum { + RowsAtCompileTime = traits::RowsAtCompileTime, + ColsAtCompileTime = traits::ColsAtCompileTime, + MaxRowsAtCompileTime = traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = traits::MaxColsAtCompileTime + }; + + // even though we require Arg1, Arg2, and Arg3 to have the same scalar type + // (see CwiseTernaryOp constructor), + // we still want to handle the case when the result type is different. + typedef typename result_of::type Scalar; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + + typedef typename Arg1::Nested Arg1Nested; + typedef typename Arg2::Nested Arg2Nested; + typedef typename Arg3::Nested Arg3Nested; + typedef typename remove_reference::type _Arg1Nested; + typedef typename remove_reference::type _Arg2Nested; + typedef typename remove_reference::type _Arg3Nested; + enum { Flags = _Arg1Nested::Flags & RowMajorBit }; +}; +} // end namespace internal + +template +class CwiseTernaryOpImpl; + +/** \class CwiseTernaryOp + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise ternary operator is + * applied to two expressions + * + * \tparam TernaryOp template functor implementing the operator + * \tparam Arg1Type the type of the first argument + * \tparam Arg2Type the type of the second argument + * \tparam Arg3Type the type of the third argument + * + * This class represents an expression where a coefficient-wise ternary + * operator is applied to three expressions. + * It is the return type of ternary operators, by which we mean only those + * ternary operators where + * all three arguments are Eigen expressions. + * For example, the return type of betainc(matrix1, matrix2, matrix3) is a + * CwiseTernaryOp. + * + * Most of the time, this is the only way that it is used, so you typically + * don't have to name + * CwiseTernaryOp types explicitly. + * + * \sa MatrixBase::ternaryExpr(const MatrixBase &, const + * MatrixBase &, const CustomTernaryOp &) const, class CwiseBinaryOp, + * class CwiseUnaryOp, class CwiseNullaryOp + */ +template +class CwiseTernaryOp : public CwiseTernaryOpImpl< + TernaryOp, Arg1Type, Arg2Type, Arg3Type, + typename internal::traits::StorageKind>, + internal::no_assignment_operator +{ + public: + typedef typename internal::remove_all::type Arg1; + typedef typename internal::remove_all::type Arg2; + typedef typename internal::remove_all::type Arg3; + + typedef typename CwiseTernaryOpImpl< + TernaryOp, Arg1Type, Arg2Type, Arg3Type, + typename internal::traits::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseTernaryOp) + + typedef typename internal::ref_selector::type Arg1Nested; + typedef typename internal::ref_selector::type Arg2Nested; + typedef typename internal::ref_selector::type Arg3Nested; + typedef typename internal::remove_reference::type _Arg1Nested; + typedef typename internal::remove_reference::type _Arg2Nested; + typedef typename internal::remove_reference::type _Arg3Nested; + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CwiseTernaryOp(const Arg1& a1, const Arg2& a2, + const Arg3& a3, + const TernaryOp& func = TernaryOp()) + : m_arg1(a1), m_arg2(a2), m_arg3(a3), m_functor(func) { + // require the sizes to match + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg2) + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(Arg1, Arg3) + + // The index types should match + EIGEN_STATIC_ASSERT((internal::is_same< + typename internal::traits::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + EIGEN_STATIC_ASSERT((internal::is_same< + typename internal::traits::StorageKind, + typename internal::traits::StorageKind>::value), + STORAGE_KIND_MUST_MATCH) + + eigen_assert(a1.rows() == a2.rows() && a1.cols() == a2.cols() && + a1.rows() == a3.rows() && a1.cols() == a3.cols()); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rows() const { + // return the fixed size type if available to enable compile time + // optimizations + if (internal::traits::type>:: + RowsAtCompileTime == Dynamic && + internal::traits::type>:: + RowsAtCompileTime == Dynamic) + return m_arg3.rows(); + else if (internal::traits::type>:: + RowsAtCompileTime == Dynamic && + internal::traits::type>:: + RowsAtCompileTime == Dynamic) + return m_arg2.rows(); + else + return m_arg1.rows(); + } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index cols() const { + // return the fixed size type if available to enable compile time + // optimizations + if (internal::traits::type>:: + ColsAtCompileTime == Dynamic && + internal::traits::type>:: + ColsAtCompileTime == Dynamic) + return m_arg3.cols(); + else if (internal::traits::type>:: + ColsAtCompileTime == Dynamic && + internal::traits::type>:: + ColsAtCompileTime == Dynamic) + return m_arg2.cols(); + else + return m_arg1.cols(); + } + + /** \returns the first argument nested expression */ + EIGEN_DEVICE_FUNC + const _Arg1Nested& arg1() const { return m_arg1; } + /** \returns the first argument nested expression */ + EIGEN_DEVICE_FUNC + const _Arg2Nested& arg2() const { return m_arg2; } + /** \returns the third argument nested expression */ + EIGEN_DEVICE_FUNC + const _Arg3Nested& arg3() const { return m_arg3; } + /** \returns the functor representing the ternary operation */ + EIGEN_DEVICE_FUNC + const TernaryOp& functor() const { return m_functor; } + + protected: + Arg1Nested m_arg1; + Arg2Nested m_arg2; + Arg3Nested m_arg3; + const TernaryOp m_functor; +}; + +// Generic API dispatcher +template +class CwiseTernaryOpImpl + : public internal::generic_xpr_base< + CwiseTernaryOp >::type { + public: + typedef typename internal::generic_xpr_base< + CwiseTernaryOp >::type Base; +}; + +} // end namespace Eigen + +#endif // EIGEN_CWISE_TERNARY_OP_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryOp.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryOp.h new file mode 100644 index 0000000000000000000000000000000000000000..1d2dd19f2b1158332c514e36111464e2e6f9c73b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryOp.h @@ -0,0 +1,103 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2014 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CWISE_UNARY_OP_H +#define EIGEN_CWISE_UNARY_OP_H + +namespace Eigen { + +namespace internal { +template +struct traits > + : traits +{ + typedef typename result_of< + UnaryOp(const typename XprType::Scalar&) + >::type Scalar; + typedef typename XprType::Nested XprTypeNested; + typedef typename remove_reference::type _XprTypeNested; + enum { + Flags = _XprTypeNested::Flags & RowMajorBit + }; +}; +} + +template +class CwiseUnaryOpImpl; + +/** \class CwiseUnaryOp + * \ingroup Core_Module + * + * \brief Generic expression where a coefficient-wise unary operator is applied to an expression + * + * \tparam UnaryOp template functor implementing the operator + * \tparam XprType the type of the expression to which we are applying the unary operator + * + * This class represents an expression where a unary operator is applied to an expression. + * It is the return type of all operations taking exactly 1 input expression, regardless of the + * presence of other inputs such as scalars. For example, the operator* in the expression 3*matrix + * is considered unary, because only the right-hand side is an expression, and its + * return type is a specialization of CwiseUnaryOp. + * + * Most of the time, this is the only way that it is used, so you typically don't have to name + * CwiseUnaryOp types explicitly. + * + * \sa MatrixBase::unaryExpr(const CustomUnaryOp &) const, class CwiseBinaryOp, class CwiseNullaryOp + */ +template +class CwiseUnaryOp : public CwiseUnaryOpImpl::StorageKind>, internal::no_assignment_operator +{ + public: + + typedef typename CwiseUnaryOpImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryOp) + typedef typename internal::ref_selector::type XprTypeNested; + typedef typename internal::remove_all::type NestedExpression; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + explicit CwiseUnaryOp(const XprType& xpr, const UnaryOp& func = UnaryOp()) + : m_xpr(xpr), m_functor(func) {} + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index rows() const { return m_xpr.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Index cols() const { return m_xpr.cols(); } + + /** \returns the functor representing the unary operation */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const UnaryOp& functor() const { return m_functor; } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + const typename internal::remove_all::type& + nestedExpression() const { return m_xpr; } + + /** \returns the nested expression */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + typename internal::remove_all::type& + nestedExpression() { return m_xpr; } + + protected: + XprTypeNested m_xpr; + const UnaryOp m_functor; +}; + +// Generic API dispatcher +template +class CwiseUnaryOpImpl + : public internal::generic_xpr_base >::type +{ +public: + typedef typename internal::generic_xpr_base >::type Base; +}; + +} // end namespace Eigen + +#endif // EIGEN_CWISE_UNARY_OP_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryView.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryView.h new file mode 100644 index 0000000000000000000000000000000000000000..27103305629474cfb84f889e8860cc3e08d097ce --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/CwiseUnaryView.h @@ -0,0 +1,128 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_CWISE_UNARY_VIEW_H +#define EIGEN_CWISE_UNARY_VIEW_H + +namespace Eigen { + +namespace internal { +template +struct traits > + : traits +{ + typedef typename result_of< + ViewOp(const typename traits::Scalar&) + >::type Scalar; + typedef typename MatrixType::Nested MatrixTypeNested; + typedef typename remove_all::type _MatrixTypeNested; + enum { + FlagsLvalueBit = is_lvalue::value ? LvalueBit : 0, + Flags = traits<_MatrixTypeNested>::Flags & (RowMajorBit | FlagsLvalueBit | DirectAccessBit), // FIXME DirectAccessBit should not be handled by expressions + MatrixTypeInnerStride = inner_stride_at_compile_time::ret, + // need to cast the sizeof's from size_t to int explicitly, otherwise: + // "error: no integral type can represent all of the enumerator values + InnerStrideAtCompileTime = MatrixTypeInnerStride == Dynamic + ? int(Dynamic) + : int(MatrixTypeInnerStride) * int(sizeof(typename traits::Scalar) / sizeof(Scalar)), + OuterStrideAtCompileTime = outer_stride_at_compile_time::ret == Dynamic + ? int(Dynamic) + : outer_stride_at_compile_time::ret * int(sizeof(typename traits::Scalar) / sizeof(Scalar)) + }; +}; +} + +template +class CwiseUnaryViewImpl; + +/** \class CwiseUnaryView + * \ingroup Core_Module + * + * \brief Generic lvalue expression of a coefficient-wise unary operator of a matrix or a vector + * + * \tparam ViewOp template functor implementing the view + * \tparam MatrixType the type of the matrix we are applying the unary operator + * + * This class represents a lvalue expression of a generic unary view operator of a matrix or a vector. + * It is the return type of real() and imag(), and most of the time this is the only way it is used. + * + * \sa MatrixBase::unaryViewExpr(const CustomUnaryOp &) const, class CwiseUnaryOp + */ +template +class CwiseUnaryView : public CwiseUnaryViewImpl::StorageKind> +{ + public: + + typedef typename CwiseUnaryViewImpl::StorageKind>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(CwiseUnaryView) + typedef typename internal::ref_selector::non_const_type MatrixTypeNested; + typedef typename internal::remove_all::type NestedExpression; + + explicit inline CwiseUnaryView(MatrixType& mat, const ViewOp& func = ViewOp()) + : m_matrix(mat), m_functor(func) {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryView) + + EIGEN_STRONG_INLINE Index rows() const { return m_matrix.rows(); } + EIGEN_STRONG_INLINE Index cols() const { return m_matrix.cols(); } + + /** \returns the functor representing unary operation */ + const ViewOp& functor() const { return m_functor; } + + /** \returns the nested expression */ + const typename internal::remove_all::type& + nestedExpression() const { return m_matrix; } + + /** \returns the nested expression */ + typename internal::remove_reference::type& + nestedExpression() { return m_matrix.const_cast_derived(); } + + protected: + MatrixTypeNested m_matrix; + ViewOp m_functor; +}; + +// Generic API dispatcher +template +class CwiseUnaryViewImpl + : public internal::generic_xpr_base >::type +{ +public: + typedef typename internal::generic_xpr_base >::type Base; +}; + +template +class CwiseUnaryViewImpl + : public internal::dense_xpr_base< CwiseUnaryView >::type +{ + public: + + typedef CwiseUnaryView Derived; + typedef typename internal::dense_xpr_base< CwiseUnaryView >::type Base; + + EIGEN_DENSE_PUBLIC_INTERFACE(Derived) + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CwiseUnaryViewImpl) + + EIGEN_DEVICE_FUNC inline Scalar* data() { return &(this->coeffRef(0)); } + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return &(this->coeff(0)); } + + EIGEN_DEVICE_FUNC inline Index innerStride() const + { + return derived().nestedExpression().innerStride() * sizeof(typename internal::traits::Scalar) / sizeof(Scalar); + } + + EIGEN_DEVICE_FUNC inline Index outerStride() const + { + return derived().nestedExpression().outerStride() * sizeof(typename internal::traits::Scalar) / sizeof(Scalar); + } +}; + +} // end namespace Eigen + +#endif // EIGEN_CWISE_UNARY_VIEW_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseBase.h new file mode 100644 index 0000000000000000000000000000000000000000..90066ae73fdba1cd745721d25750744d0d914752 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseBase.h @@ -0,0 +1,611 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2007-2010 Benoit Jacob +// Copyright (C) 2008-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DENSEBASE_H +#define EIGEN_DENSEBASE_H + +namespace Eigen { + +namespace internal { + +// The index type defined by EIGEN_DEFAULT_DENSE_INDEX_TYPE must be a signed type. +// This dummy function simply aims at checking that at compile time. +static inline void check_DenseIndex_is_signed() { + EIGEN_STATIC_ASSERT(NumTraits::IsSigned,THE_INDEX_TYPE_MUST_BE_A_SIGNED_TYPE); +} + +} // end namespace internal + +/** \class DenseBase + * \ingroup Core_Module + * + * \brief Base class for all dense matrices, vectors, and arrays + * + * This class is the base that is inherited by all dense objects (matrix, vector, arrays, + * and related expression types). The common Eigen API for dense objects is contained in this class. + * + * \tparam Derived is the derived type, e.g., a matrix type or an expression. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_DENSEBASE_PLUGIN. + * + * \sa \blank \ref TopicClassHierarchy + */ +template class DenseBase +#ifndef EIGEN_PARSED_BY_DOXYGEN + : public DenseCoeffsBase +#else + : public DenseCoeffsBase +#endif // not EIGEN_PARSED_BY_DOXYGEN +{ + public: + + /** Inner iterator type to iterate over the coefficients of a row or column. + * \sa class InnerIterator + */ + typedef Eigen::InnerIterator InnerIterator; + + typedef typename internal::traits::StorageKind StorageKind; + + /** + * \brief The type used to store indices + * \details This typedef is relevant for types that store multiple indices such as + * PermutationMatrix or Transpositions, otherwise it defaults to Eigen::Index + * \sa \blank \ref TopicPreprocessorDirectives, Eigen::Index, SparseMatrixBase. + */ + typedef typename internal::traits::StorageIndex StorageIndex; + + /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. */ + typedef typename internal::traits::Scalar Scalar; + + /** The numeric type of the expression' coefficients, e.g. float, double, int or std::complex, etc. + * + * It is an alias for the Scalar type */ + typedef Scalar value_type; + + typedef typename NumTraits::Real RealScalar; + typedef DenseCoeffsBase Base; + + using Base::derived; + using Base::const_cast_derived; + using Base::rows; + using Base::cols; + using Base::size; + using Base::rowIndexByOuterInner; + using Base::colIndexByOuterInner; + using Base::coeff; + using Base::coeffByOuterInner; + using Base::operator(); + using Base::operator[]; + using Base::x; + using Base::y; + using Base::z; + using Base::w; + using Base::stride; + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + using Base::colStride; + typedef typename Base::CoeffReturnType CoeffReturnType; + + enum { + + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + /**< The number of rows at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), ColsAtCompileTime, SizeAtCompileTime */ + + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + /**< The number of columns at compile-time. This is just a copy of the value provided + * by the \a Derived type. If a value is not known at compile-time, + * it is set to the \a Dynamic constant. + * \sa MatrixBase::rows(), MatrixBase::cols(), RowsAtCompileTime, SizeAtCompileTime */ + + + SizeAtCompileTime = (internal::size_at_compile_time::RowsAtCompileTime, + internal::traits::ColsAtCompileTime>::ret), + /**< This is equal to the number of coefficients, i.e. the number of + * rows times the number of columns, or to \a Dynamic if this is not + * known at compile-time. \sa RowsAtCompileTime, ColsAtCompileTime */ + + MaxRowsAtCompileTime = internal::traits::MaxRowsAtCompileTime, + /**< This value is equal to the maximum possible number of rows that this expression + * might have. If this expression might have an arbitrarily high number of rows, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa RowsAtCompileTime, MaxColsAtCompileTime, MaxSizeAtCompileTime + */ + + MaxColsAtCompileTime = internal::traits::MaxColsAtCompileTime, + /**< This value is equal to the maximum possible number of columns that this expression + * might have. If this expression might have an arbitrarily high number of columns, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa ColsAtCompileTime, MaxRowsAtCompileTime, MaxSizeAtCompileTime + */ + + MaxSizeAtCompileTime = (internal::size_at_compile_time::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime>::ret), + /**< This value is equal to the maximum possible number of coefficients that this expression + * might have. If this expression might have an arbitrarily high number of coefficients, + * this value is set to \a Dynamic. + * + * This value is useful to know when evaluating an expression, in order to determine + * whether it is possible to avoid doing a dynamic memory allocation. + * + * \sa SizeAtCompileTime, MaxRowsAtCompileTime, MaxColsAtCompileTime + */ + + IsVectorAtCompileTime = internal::traits::MaxRowsAtCompileTime == 1 + || internal::traits::MaxColsAtCompileTime == 1, + /**< This is set to true if either the number of rows or the number of + * columns is known at compile-time to be equal to 1. Indeed, in that case, + * we are dealing with a column-vector (if there is only one column) or with + * a row-vector (if there is only one row). */ + + Flags = internal::traits::Flags, + /**< This stores expression \ref flags flags which may or may not be inherited by new expressions + * constructed from this one. See the \ref flags "list of flags". + */ + + IsRowMajor = int(Flags) & RowMajorBit, /**< True if this expression has row-major storage order. */ + + InnerSizeAtCompileTime = int(IsVectorAtCompileTime) ? int(SizeAtCompileTime) + : int(IsRowMajor) ? int(ColsAtCompileTime) : int(RowsAtCompileTime), + + InnerStrideAtCompileTime = internal::inner_stride_at_compile_time::ret, + OuterStrideAtCompileTime = internal::outer_stride_at_compile_time::ret + }; + + typedef typename internal::find_best_packet::type PacketScalar; + + enum { IsPlainObjectBase = 0 }; + + /** The plain matrix type corresponding to this expression. + * \sa PlainObject */ + typedef Matrix::Scalar, + internal::traits::RowsAtCompileTime, + internal::traits::ColsAtCompileTime, + AutoAlign | (internal::traits::Flags&RowMajorBit ? RowMajor : ColMajor), + internal::traits::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime + > PlainMatrix; + + /** The plain array type corresponding to this expression. + * \sa PlainObject */ + typedef Array::Scalar, + internal::traits::RowsAtCompileTime, + internal::traits::ColsAtCompileTime, + AutoAlign | (internal::traits::Flags&RowMajorBit ? RowMajor : ColMajor), + internal::traits::MaxRowsAtCompileTime, + internal::traits::MaxColsAtCompileTime + > PlainArray; + + /** \brief The plain matrix or array type corresponding to this expression. + * + * This is not necessarily exactly the return type of eval(). In the case of plain matrices, + * the return type of eval() is a const reference to a matrix, not a matrix! It is however guaranteed + * that the return type of eval() is either PlainObject or const PlainObject&. + */ + typedef typename internal::conditional::XprKind,MatrixXpr >::value, + PlainMatrix, PlainArray>::type PlainObject; + + /** \returns the number of nonzero coefficients which is in practice the number + * of stored coefficients. */ + EIGEN_DEVICE_FUNC + inline Index nonZeros() const { return size(); } + + /** \returns the outer size. + * + * \note For a vector, this returns just 1. For a matrix (non-vector), this is the major dimension + * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of columns for a + * column-major matrix, and the number of rows for a row-major matrix. */ + EIGEN_DEVICE_FUNC + Index outerSize() const + { + return IsVectorAtCompileTime ? 1 + : int(IsRowMajor) ? this->rows() : this->cols(); + } + + /** \returns the inner size. + * + * \note For a vector, this is just the size. For a matrix (non-vector), this is the minor dimension + * with respect to the \ref TopicStorageOrders "storage order", i.e., the number of rows for a + * column-major matrix, and the number of columns for a row-major matrix. */ + EIGEN_DEVICE_FUNC + Index innerSize() const + { + return IsVectorAtCompileTime ? this->size() + : int(IsRowMajor) ? this->cols() : this->rows(); + } + + /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are + * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does + * nothing else. + */ + EIGEN_DEVICE_FUNC + void resize(Index newSize) + { + EIGEN_ONLY_USED_FOR_DEBUG(newSize); + eigen_assert(newSize == this->size() + && "DenseBase::resize() does not actually allow to resize."); + } + /** Only plain matrices/arrays, not expressions, may be resized; therefore the only useful resize methods are + * Matrix::resize() and Array::resize(). The present method only asserts that the new size equals the old size, and does + * nothing else. + */ + EIGEN_DEVICE_FUNC + void resize(Index rows, Index cols) + { + EIGEN_ONLY_USED_FOR_DEBUG(rows); + EIGEN_ONLY_USED_FOR_DEBUG(cols); + eigen_assert(rows == this->rows() && cols == this->cols() + && "DenseBase::resize() does not actually allow to resize."); + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp,PlainObject> ConstantReturnType; + /** \internal \deprecated Represents a vector with linearly spaced coefficients that allows sequential access only. */ + typedef CwiseNullaryOp,PlainObject> SequentialLinSpacedReturnType; + /** \internal Represents a vector with linearly spaced coefficients that allows random access. */ + typedef CwiseNullaryOp,PlainObject> RandomAccessLinSpacedReturnType; + /** \internal the return type of MatrixBase::eigenvalues() */ + typedef Matrix::Scalar>::Real, internal::traits::ColsAtCompileTime, 1> EigenvaluesReturnType; + +#endif // not EIGEN_PARSED_BY_DOXYGEN + + /** Copies \a other into *this. \returns a reference to *this. */ + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const DenseBase& other); + + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const DenseBase& other); + + template + EIGEN_DEVICE_FUNC + Derived& operator=(const EigenBase &other); + + template + EIGEN_DEVICE_FUNC + Derived& operator+=(const EigenBase &other); + + template + EIGEN_DEVICE_FUNC + Derived& operator-=(const EigenBase &other); + + template + EIGEN_DEVICE_FUNC + Derived& operator=(const ReturnByValue& func); + + /** \internal + * Copies \a other into *this without evaluating other. \returns a reference to *this. + * \deprecated */ + template + EIGEN_DEVICE_FUNC + Derived& lazyAssign(const DenseBase& other); + + EIGEN_DEVICE_FUNC + CommaInitializer operator<< (const Scalar& s); + + /** \deprecated it now returns \c *this */ + template + EIGEN_DEPRECATED + const Derived& flagged() const + { return derived(); } + + template + EIGEN_DEVICE_FUNC + CommaInitializer operator<< (const DenseBase& other); + + typedef Transpose TransposeReturnType; + EIGEN_DEVICE_FUNC + TransposeReturnType transpose(); + typedef typename internal::add_const >::type ConstTransposeReturnType; + EIGEN_DEVICE_FUNC + ConstTransposeReturnType transpose() const; + EIGEN_DEVICE_FUNC + void transposeInPlace(); + + EIGEN_DEVICE_FUNC static const ConstantReturnType + Constant(Index rows, Index cols, const Scalar& value); + EIGEN_DEVICE_FUNC static const ConstantReturnType + Constant(Index size, const Scalar& value); + EIGEN_DEVICE_FUNC static const ConstantReturnType + Constant(const Scalar& value); + + EIGEN_DEVICE_FUNC static const SequentialLinSpacedReturnType + LinSpaced(Sequential_t, Index size, const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType + LinSpaced(Index size, const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC static const SequentialLinSpacedReturnType + LinSpaced(Sequential_t, const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC static const RandomAccessLinSpacedReturnType + LinSpaced(const Scalar& low, const Scalar& high); + + template EIGEN_DEVICE_FUNC + static const CwiseNullaryOp + NullaryExpr(Index rows, Index cols, const CustomNullaryOp& func); + template EIGEN_DEVICE_FUNC + static const CwiseNullaryOp + NullaryExpr(Index size, const CustomNullaryOp& func); + template EIGEN_DEVICE_FUNC + static const CwiseNullaryOp + NullaryExpr(const CustomNullaryOp& func); + + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(Index size); + EIGEN_DEVICE_FUNC static const ConstantReturnType Zero(); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(Index size); + EIGEN_DEVICE_FUNC static const ConstantReturnType Ones(); + + EIGEN_DEVICE_FUNC void fill(const Scalar& value); + EIGEN_DEVICE_FUNC Derived& setConstant(const Scalar& value); + EIGEN_DEVICE_FUNC Derived& setLinSpaced(Index size, const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC Derived& setLinSpaced(const Scalar& low, const Scalar& high); + EIGEN_DEVICE_FUNC Derived& setZero(); + EIGEN_DEVICE_FUNC Derived& setOnes(); + EIGEN_DEVICE_FUNC Derived& setRandom(); + + template EIGEN_DEVICE_FUNC + bool isApprox(const DenseBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC + bool isMuchSmallerThan(const RealScalar& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + template EIGEN_DEVICE_FUNC + bool isMuchSmallerThan(const DenseBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + + EIGEN_DEVICE_FUNC bool isApproxToConstant(const Scalar& value, const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isConstant(const Scalar& value, const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isZero(const RealScalar& prec = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC bool isOnes(const RealScalar& prec = NumTraits::dummy_precision()) const; + + inline bool hasNaN() const; + inline bool allFinite() const; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator*=(const Scalar& other); + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator/=(const Scalar& other); + + typedef typename internal::add_const_on_value_type::type>::type EvalReturnType; + /** \returns the matrix or vector obtained by evaluating this expression. + * + * Notice that in the case of a plain matrix or vector (not an expression) this function just returns + * a const reference, in order to avoid a useless copy. + * + * \warning Be carefull with eval() and the auto C++ keyword, as detailed in this \link TopicPitfalls_auto_keyword page \endlink. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE EvalReturnType eval() const + { + // Even though MSVC does not honor strong inlining when the return type + // is a dynamic matrix, we desperately need strong inlining for fixed + // size types on MSVC. + return typename internal::eval::type(derived()); + } + + /** swaps *this with the expression \a other. + * + */ + template + EIGEN_DEVICE_FUNC + void swap(const DenseBase& other) + { + EIGEN_STATIC_ASSERT(!OtherDerived::IsPlainObjectBase,THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + eigen_assert(rows()==other.rows() && cols()==other.cols()); + call_assignment(derived(), other.const_cast_derived(), internal::swap_assign_op()); + } + + /** swaps *this with the matrix or array \a other. + * + */ + template + EIGEN_DEVICE_FUNC + void swap(PlainObjectBase& other) + { + eigen_assert(rows()==other.rows() && cols()==other.cols()); + call_assignment(derived(), other.derived(), internal::swap_assign_op()); + } + + EIGEN_DEVICE_FUNC inline const NestByValue nestByValue() const; + EIGEN_DEVICE_FUNC inline const ForceAlignedAccess forceAlignedAccess() const; + EIGEN_DEVICE_FUNC inline ForceAlignedAccess forceAlignedAccess(); + template EIGEN_DEVICE_FUNC + inline const typename internal::conditional,Derived&>::type forceAlignedAccessIf() const; + template EIGEN_DEVICE_FUNC + inline typename internal::conditional,Derived&>::type forceAlignedAccessIf(); + + EIGEN_DEVICE_FUNC Scalar sum() const; + EIGEN_DEVICE_FUNC Scalar mean() const; + EIGEN_DEVICE_FUNC Scalar trace() const; + + EIGEN_DEVICE_FUNC Scalar prod() const; + + EIGEN_DEVICE_FUNC typename internal::traits::Scalar minCoeff() const; + EIGEN_DEVICE_FUNC typename internal::traits::Scalar maxCoeff() const; + + template EIGEN_DEVICE_FUNC + typename internal::traits::Scalar minCoeff(IndexType* row, IndexType* col) const; + template EIGEN_DEVICE_FUNC + typename internal::traits::Scalar maxCoeff(IndexType* row, IndexType* col) const; + template EIGEN_DEVICE_FUNC + typename internal::traits::Scalar minCoeff(IndexType* index) const; + template EIGEN_DEVICE_FUNC + typename internal::traits::Scalar maxCoeff(IndexType* index) const; + + template + EIGEN_DEVICE_FUNC + Scalar redux(const BinaryOp& func) const; + + template + EIGEN_DEVICE_FUNC + void visit(Visitor& func) const; + + /** \returns a WithFormat proxy object allowing to print a matrix the with given + * format \a fmt. + * + * See class IOFormat for some examples. + * + * \sa class IOFormat, class WithFormat + */ + inline const WithFormat format(const IOFormat& fmt) const + { + return WithFormat(derived(), fmt); + } + + /** \returns the unique coefficient of a 1x1 expression */ + EIGEN_DEVICE_FUNC + CoeffReturnType value() const + { + EIGEN_STATIC_ASSERT_SIZE_1x1(Derived) + eigen_assert(this->rows() == 1 && this->cols() == 1); + return derived().coeff(0,0); + } + + EIGEN_DEVICE_FUNC bool all() const; + EIGEN_DEVICE_FUNC bool any() const; + EIGEN_DEVICE_FUNC Index count() const; + + typedef VectorwiseOp RowwiseReturnType; + typedef const VectorwiseOp ConstRowwiseReturnType; + typedef VectorwiseOp ColwiseReturnType; + typedef const VectorwiseOp ConstColwiseReturnType; + + /** \returns a VectorwiseOp wrapper of *this providing additional partial reduction operations + * + * Example: \include MatrixBase_rowwise.cpp + * Output: \verbinclude MatrixBase_rowwise.out + * + * \sa colwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting + */ + //Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC inline ConstRowwiseReturnType rowwise() const { + return ConstRowwiseReturnType(derived()); + } + EIGEN_DEVICE_FUNC RowwiseReturnType rowwise(); + + /** \returns a VectorwiseOp wrapper of *this providing additional partial reduction operations + * + * Example: \include MatrixBase_colwise.cpp + * Output: \verbinclude MatrixBase_colwise.out + * + * \sa rowwise(), class VectorwiseOp, \ref TutorialReductionsVisitorsBroadcasting + */ + EIGEN_DEVICE_FUNC inline ConstColwiseReturnType colwise() const { + return ConstColwiseReturnType(derived()); + } + EIGEN_DEVICE_FUNC ColwiseReturnType colwise(); + + typedef CwiseNullaryOp,PlainObject> RandomReturnType; + static const RandomReturnType Random(Index rows, Index cols); + static const RandomReturnType Random(Index size); + static const RandomReturnType Random(); + + template + const Select + select(const DenseBase& thenMatrix, + const DenseBase& elseMatrix) const; + + template + inline const Select + select(const DenseBase& thenMatrix, const typename ThenDerived::Scalar& elseScalar) const; + + template + inline const Select + select(const typename ElseDerived::Scalar& thenScalar, const DenseBase& elseMatrix) const; + + template RealScalar lpNorm() const; + + template + EIGEN_DEVICE_FUNC + const Replicate replicate() const; + /** + * \return an expression of the replication of \c *this + * + * Example: \include MatrixBase_replicate_int_int.cpp + * Output: \verbinclude MatrixBase_replicate_int_int.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate + */ + //Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC + const Replicate replicate(Index rowFactor, Index colFactor) const + { + return Replicate(derived(), rowFactor, colFactor); + } + + typedef Reverse ReverseReturnType; + typedef const Reverse ConstReverseReturnType; + EIGEN_DEVICE_FUNC ReverseReturnType reverse(); + /** This is the const version of reverse(). */ + //Code moved here due to a CUDA compiler bug + EIGEN_DEVICE_FUNC ConstReverseReturnType reverse() const + { + return ConstReverseReturnType(derived()); + } + EIGEN_DEVICE_FUNC void reverseInPlace(); + +#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::DenseBase +#define EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +#define EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF(COND) +# include "../plugins/BlockMethods.h" +# ifdef EIGEN_DENSEBASE_PLUGIN +# include EIGEN_DENSEBASE_PLUGIN +# endif +#undef EIGEN_CURRENT_STORAGE_BASE_CLASS +#undef EIGEN_DOC_BLOCK_ADDONS_NOT_INNER_PANEL +#undef EIGEN_DOC_BLOCK_ADDONS_INNER_PANEL_IF + + // disable the use of evalTo for dense objects with a nice compilation error + template + EIGEN_DEVICE_FUNC + inline void evalTo(Dest& ) const + { + EIGEN_STATIC_ASSERT((internal::is_same::value),THE_EVAL_EVALTO_FUNCTION_SHOULD_NEVER_BE_CALLED_FOR_DENSE_OBJECTS); + } + + protected: + /** Default constructor. Do nothing. */ + EIGEN_DEVICE_FUNC DenseBase() + { + /* Just checks for self-consistency of the flags. + * Only do it when debugging Eigen, as this borders on paranoiac and could slow compilation down + */ +#ifdef EIGEN_INTERNAL_DEBUGGING + EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, int(IsRowMajor)) + && EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, int(!IsRowMajor))), + INVALID_STORAGE_ORDER_FOR_THIS_VECTOR_EXPRESSION) +#endif + } + + private: + EIGEN_DEVICE_FUNC explicit DenseBase(int); + EIGEN_DEVICE_FUNC DenseBase(int,int); + template EIGEN_DEVICE_FUNC explicit DenseBase(const DenseBase&); +}; + +} // end namespace Eigen + +#endif // EIGEN_DENSEBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h new file mode 100644 index 0000000000000000000000000000000000000000..c4af48ab699f438e82ae488b8bb1382f3693c7b3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseCoeffsBase.h @@ -0,0 +1,681 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DENSECOEFFSBASE_H +#define EIGEN_DENSECOEFFSBASE_H + +namespace Eigen { + +namespace internal { +template struct add_const_on_value_type_if_arithmetic +{ + typedef typename conditional::value, T, typename add_const_on_value_type::type>::type type; +}; +} + +/** \brief Base class providing read-only coefficient access to matrices and arrays. + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * \tparam #ReadOnlyAccessors Constant indicating read-only access + * + * This class defines the \c operator() \c const function and friends, which can be used to read specific + * entries of a matrix or array. + * + * \sa DenseCoeffsBase, DenseCoeffsBase, + * \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public EigenBase +{ + public: + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + + // Explanation for this CoeffReturnType typedef. + // - This is the return type of the coeff() method. + // - The LvalueBit means exactly that we can offer a coeffRef() method, which means exactly that we can get references + // to coeffs, which means exactly that we can have coeff() return a const reference (as opposed to returning a value). + // - The is_artihmetic check is required since "const int", "const double", etc. will cause warnings on some systems + // while the declaration of "const T", where T is a non arithmetic type does not. Always returning "const Scalar&" is + // not possible, since the underlying expressions might not offer a valid address the reference could be referring to. + typedef typename internal::conditional::Flags&LvalueBit), + const Scalar&, + typename internal::conditional::value, Scalar, const Scalar>::type + >::type CoeffReturnType; + + typedef typename internal::add_const_on_value_type_if_arithmetic< + typename internal::packet_traits::type + >::type PacketReturnType; + + typedef EigenBase Base; + using Base::rows; + using Base::cols; + using Base::size; + using Base::derived; + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) const + { + return int(Derived::RowsAtCompileTime) == 1 ? 0 + : int(Derived::ColsAtCompileTime) == 1 ? inner + : int(Derived::Flags)&RowMajorBit ? outer + : inner; + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) const + { + return int(Derived::ColsAtCompileTime) == 1 ? 0 + : int(Derived::RowsAtCompileTime) == 1 ? inner + : int(Derived::Flags)&RowMajorBit ? inner + : outer; + } + + /** Short version: don't use this function, use + * \link operator()(Index,Index) const \endlink instead. + * + * Long version: this function is similar to + * \link operator()(Index,Index) const \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator()(Index,Index) const \endlink. + * + * \sa operator()(Index,Index) const, coeffRef(Index,Index), coeff(Index) const + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const + { + eigen_internal_assert(row >= 0 && row < rows() + && col >= 0 && col < cols()); + return internal::evaluator(derived()).coeff(row,col); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType coeffByOuterInner(Index outer, Index inner) const + { + return coeff(rowIndexByOuterInner(outer, inner), + colIndexByOuterInner(outer, inner)); + } + + /** \returns the coefficient at given the given row and column. + * + * \sa operator()(Index,Index), operator[](Index) + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const + { + eigen_assert(row >= 0 && row < rows() + && col >= 0 && col < cols()); + return coeff(row, col); + } + + /** Short version: don't use this function, use + * \link operator[](Index) const \endlink instead. + * + * Long version: this function is similar to + * \link operator[](Index) const \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameter \a index is in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator[](Index) const \endlink. + * + * \sa operator[](Index) const, coeffRef(Index), coeff(Index,Index) const + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + coeff(Index index) const + { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).coeff(index); + } + + + /** \returns the coefficient at given index. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, + * z() const, w() const + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + operator[](Index index) const + { + EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, + THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) + eigen_assert(index >= 0 && index < size()); + return coeff(index); + } + + /** \returns the coefficient at given index. + * + * This is synonymous to operator[](Index) const. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index), operator()(Index,Index) const, x() const, y() const, + * z() const, w() const + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + operator()(Index index) const + { + eigen_assert(index >= 0 && index < size()); + return coeff(index); + } + + /** equivalent to operator[](0). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + x() const { return (*this)[0]; } + + /** equivalent to operator[](1). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + y() const + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=2, OUT_OF_RANGE_ACCESS); + return (*this)[1]; + } + + /** equivalent to operator[](2). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + z() const + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=3, OUT_OF_RANGE_ACCESS); + return (*this)[2]; + } + + /** equivalent to operator[](3). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE CoeffReturnType + w() const + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=4, OUT_OF_RANGE_ACCESS); + return (*this)[3]; + } + + /** \internal + * \returns the packet of coefficients starting at the given row and column. It is your responsibility + * to ensure that a packet really starts there. This method is only available on expressions having the + * PacketAccessBit. + * + * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select + * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets + * starting at an address which is a multiple of the packet size. + */ + + template + EIGEN_STRONG_INLINE PacketReturnType packet(Index row, Index col) const + { + typedef typename internal::packet_traits::type DefaultPacketType; + eigen_internal_assert(row >= 0 && row < rows() && col >= 0 && col < cols()); + return internal::evaluator(derived()).template packet(row,col); + } + + + /** \internal */ + template + EIGEN_STRONG_INLINE PacketReturnType packetByOuterInner(Index outer, Index inner) const + { + return packet(rowIndexByOuterInner(outer, inner), + colIndexByOuterInner(outer, inner)); + } + + /** \internal + * \returns the packet of coefficients starting at the given index. It is your responsibility + * to ensure that a packet really starts there. This method is only available on expressions having the + * PacketAccessBit and the LinearAccessBit. + * + * The \a LoadMode parameter may have the value \a #Aligned or \a #Unaligned. Its effect is to select + * the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets + * starting at an address which is a multiple of the packet size. + */ + + template + EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const + { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + typedef typename internal::packet_traits::type DefaultPacketType; + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).template packet(index); + } + + protected: + // explanation: DenseBase is doing "using ..." on the methods from DenseCoeffsBase. + // But some methods are only available in the DirectAccess case. + // So we add dummy methods here with these names, so that "using... " doesn't fail. + // It's not private so that the child class DenseBase can access them, and it's not public + // either since it's an implementation detail, so has to be protected. + void coeffRef(); + void coeffRefByOuterInner(); + void writePacket(); + void writePacketByOuterInner(); + void copyCoeff(); + void copyCoeffByOuterInner(); + void copyPacket(); + void copyPacketByOuterInner(); + void stride(); + void innerStride(); + void outerStride(); + void rowStride(); + void colStride(); +}; + +/** \brief Base class providing read/write coefficient access to matrices and arrays. + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * \tparam #WriteAccessors Constant indicating read/write access + * + * This class defines the non-const \c operator() function and friends, which can be used to write specific + * entries of a matrix or array. This class inherits DenseCoeffsBase which + * defines the const variant for reading specific entries. + * + * \sa DenseCoeffsBase, \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public DenseCoeffsBase +{ + public: + + typedef DenseCoeffsBase Base; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + using Base::coeff; + using Base::rows; + using Base::cols; + using Base::size; + using Base::derived; + using Base::rowIndexByOuterInner; + using Base::colIndexByOuterInner; + using Base::operator[]; + using Base::operator(); + using Base::x; + using Base::y; + using Base::z; + using Base::w; + + /** Short version: don't use this function, use + * \link operator()(Index,Index) \endlink instead. + * + * Long version: this function is similar to + * \link operator()(Index,Index) \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator()(Index,Index) \endlink. + * + * \sa operator()(Index,Index), coeff(Index, Index) const, coeffRef(Index) + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col) + { + eigen_internal_assert(row >= 0 && row < rows() + && col >= 0 && col < cols()); + return internal::evaluator(derived()).coeffRef(row,col); + } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + coeffRefByOuterInner(Index outer, Index inner) + { + return coeffRef(rowIndexByOuterInner(outer, inner), + colIndexByOuterInner(outer, inner)); + } + + /** \returns a reference to the coefficient at given the given row and column. + * + * \sa operator[](Index) + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + operator()(Index row, Index col) + { + eigen_assert(row >= 0 && row < rows() + && col >= 0 && col < cols()); + return coeffRef(row, col); + } + + + /** Short version: don't use this function, use + * \link operator[](Index) \endlink instead. + * + * Long version: this function is similar to + * \link operator[](Index) \endlink, but without the assertion. + * Use this for limiting the performance cost of debugging code when doing + * repeated coefficient access. Only use this when it is guaranteed that the + * parameters \a row and \a col are in range. + * + * If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this + * function equivalent to \link operator[](Index) \endlink. + * + * \sa operator[](Index), coeff(Index) const, coeffRef(Index,Index) + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + coeffRef(Index index) + { + EIGEN_STATIC_ASSERT(internal::evaluator::Flags & LinearAccessBit, + THIS_COEFFICIENT_ACCESSOR_TAKING_ONE_ACCESS_IS_ONLY_FOR_EXPRESSIONS_ALLOWING_LINEAR_ACCESS) + eigen_internal_assert(index >= 0 && index < size()); + return internal::evaluator(derived()).coeffRef(index); + } + + /** \returns a reference to the coefficient at given index. + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + operator[](Index index) + { + EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime, + THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD) + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + /** \returns a reference to the coefficient at given index. + * + * This is synonymous to operator[](Index). + * + * This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit. + * + * \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w() + */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + operator()(Index index) + { + eigen_assert(index >= 0 && index < size()); + return coeffRef(index); + } + + /** equivalent to operator[](0). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + x() { return (*this)[0]; } + + /** equivalent to operator[](1). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + y() + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=2, OUT_OF_RANGE_ACCESS); + return (*this)[1]; + } + + /** equivalent to operator[](2). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + z() + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=3, OUT_OF_RANGE_ACCESS); + return (*this)[2]; + } + + /** equivalent to operator[](3). */ + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& + w() + { + EIGEN_STATIC_ASSERT(Derived::SizeAtCompileTime==-1 || Derived::SizeAtCompileTime>=4, OUT_OF_RANGE_ACCESS); + return (*this)[3]; + } +}; + +/** \brief Base class providing direct read-only coefficient access to matrices and arrays. + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * \tparam #DirectAccessors Constant indicating direct access + * + * This class defines functions to work with strides which can be used to access entries directly. This class + * inherits DenseCoeffsBase which defines functions to access entries read-only using + * \c operator() . + * + * \sa \blank \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase : public DenseCoeffsBase +{ + public: + + typedef DenseCoeffsBase Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + + using Base::rows; + using Base::cols; + using Base::size; + using Base::derived; + + /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. + * + * \sa outerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index innerStride() const + { + return derived().innerStride(); + } + + /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns + * in a column-major matrix). + * + * \sa innerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index outerStride() const + { + return derived().outerStride(); + } + + // FIXME shall we remove it ? + inline Index stride() const + { + return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); + } + + /** \returns the pointer increment between two consecutive rows. + * + * \sa innerStride(), outerStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index rowStride() const + { + return Derived::IsRowMajor ? outerStride() : innerStride(); + } + + /** \returns the pointer increment between two consecutive columns. + * + * \sa innerStride(), outerStride(), rowStride() + */ + EIGEN_DEVICE_FUNC + inline Index colStride() const + { + return Derived::IsRowMajor ? innerStride() : outerStride(); + } +}; + +/** \brief Base class providing direct read/write coefficient access to matrices and arrays. + * \ingroup Core_Module + * \tparam Derived Type of the derived class + * \tparam #DirectWriteAccessors Constant indicating direct access + * + * This class defines functions to work with strides which can be used to access entries directly. This class + * inherits DenseCoeffsBase which defines functions to access entries read/write using + * \c operator(). + * + * \sa \blank \ref TopicClassHierarchy + */ +template +class DenseCoeffsBase + : public DenseCoeffsBase +{ + public: + + typedef DenseCoeffsBase Base; + typedef typename internal::traits::Scalar Scalar; + typedef typename NumTraits::Real RealScalar; + + using Base::rows; + using Base::cols; + using Base::size; + using Base::derived; + + /** \returns the pointer increment between two consecutive elements within a slice in the inner direction. + * + * \sa outerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index innerStride() const + { + return derived().innerStride(); + } + + /** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns + * in a column-major matrix). + * + * \sa innerStride(), rowStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index outerStride() const + { + return derived().outerStride(); + } + + // FIXME shall we remove it ? + inline Index stride() const + { + return Derived::IsVectorAtCompileTime ? innerStride() : outerStride(); + } + + /** \returns the pointer increment between two consecutive rows. + * + * \sa innerStride(), outerStride(), colStride() + */ + EIGEN_DEVICE_FUNC + inline Index rowStride() const + { + return Derived::IsRowMajor ? outerStride() : innerStride(); + } + + /** \returns the pointer increment between two consecutive columns. + * + * \sa innerStride(), outerStride(), rowStride() + */ + EIGEN_DEVICE_FUNC + inline Index colStride() const + { + return Derived::IsRowMajor ? innerStride() : outerStride(); + } +}; + +namespace internal { + +template +struct first_aligned_impl +{ + static inline Index run(const Derived&) + { return 0; } +}; + +template +struct first_aligned_impl +{ + static inline Index run(const Derived& m) + { + return internal::first_aligned(m.data(), m.size()); + } +}; + +/** \internal \returns the index of the first element of the array stored by \a m that is properly aligned with respect to \a Alignment for vectorization. + * + * \tparam Alignment requested alignment in Bytes. + * + * There is also the variant first_aligned(const Scalar*, Integer) defined in Memory.h. See it for more + * documentation. + */ +template +static inline Index first_aligned(const DenseBase& m) +{ + enum { ReturnZero = (int(evaluator::Alignment) >= Alignment) || !(Derived::Flags & DirectAccessBit) }; + return first_aligned_impl::run(m.derived()); +} + +template +static inline Index first_default_aligned(const DenseBase& m) +{ + typedef typename Derived::Scalar Scalar; + typedef typename packet_traits::type DefaultPacketType; + return internal::first_aligned::alignment),Derived>(m); +} + +template::ret> +struct inner_stride_at_compile_time +{ + enum { ret = traits::InnerStrideAtCompileTime }; +}; + +template +struct inner_stride_at_compile_time +{ + enum { ret = 0 }; +}; + +template::ret> +struct outer_stride_at_compile_time +{ + enum { ret = traits::OuterStrideAtCompileTime }; +}; + +template +struct outer_stride_at_compile_time +{ + enum { ret = 0 }; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_DENSECOEFFSBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseStorage.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseStorage.h new file mode 100644 index 0000000000000000000000000000000000000000..7958feeb9c01ed347ceab701244a05758adb4f16 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DenseStorage.h @@ -0,0 +1,570 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2009 Benoit Jacob +// Copyright (C) 2010-2013 Hauke Heibel +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIXSTORAGE_H +#define EIGEN_MATRIXSTORAGE_H + +#ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN + #define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) X; EIGEN_DENSE_STORAGE_CTOR_PLUGIN; +#else + #define EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(X) +#endif + +namespace Eigen { + +namespace internal { + +struct constructor_without_unaligned_array_assert {}; + +template +EIGEN_DEVICE_FUNC +void check_static_allocation_size() +{ + // if EIGEN_STACK_ALLOCATION_LIMIT is defined to 0, then no limit + #if EIGEN_STACK_ALLOCATION_LIMIT + EIGEN_STATIC_ASSERT(Size * sizeof(T) <= EIGEN_STACK_ALLOCATION_LIMIT, OBJECT_ALLOCATED_ON_STACK_IS_TOO_BIG); + #endif +} + +/** \internal + * Static array. If the MatrixOrArrayOptions require auto-alignment, the array will be automatically aligned: + * to 16 bytes boundary if the total size is a multiple of 16 bytes. + */ +template ::value > +struct plain_array +{ + T array[Size]; + + EIGEN_DEVICE_FUNC + plain_array() + { + check_static_allocation_size(); + } + + EIGEN_DEVICE_FUNC + plain_array(constructor_without_unaligned_array_assert) + { + check_static_allocation_size(); + } +}; + +#if defined(EIGEN_DISABLE_UNALIGNED_ARRAY_ASSERT) + #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) +#elif EIGEN_GNUC_AT_LEAST(4,7) + // GCC 4.7 is too aggressive in its optimizations and remove the alignement test based on the fact the array is declared to be aligned. + // See this bug report: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=53900 + // Hiding the origin of the array pointer behind a function argument seems to do the trick even if the function is inlined: + template + EIGEN_ALWAYS_INLINE PtrType eigen_unaligned_array_assert_workaround_gcc47(PtrType array) { return array; } + #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) \ + eigen_assert((internal::UIntPtr(eigen_unaligned_array_assert_workaround_gcc47(array)) & (sizemask)) == 0 \ + && "this assertion is explained here: " \ + "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" \ + " **** READ THIS WEB PAGE !!! ****"); +#else + #define EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(sizemask) \ + eigen_assert((internal::UIntPtr(array) & (sizemask)) == 0 \ + && "this assertion is explained here: " \ + "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" \ + " **** READ THIS WEB PAGE !!! ****"); +#endif + +template +struct plain_array +{ + EIGEN_ALIGN_TO_BOUNDARY(8) T array[Size]; + + EIGEN_DEVICE_FUNC + plain_array() + { + EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(7); + check_static_allocation_size(); + } + + EIGEN_DEVICE_FUNC + plain_array(constructor_without_unaligned_array_assert) + { + check_static_allocation_size(); + } +}; + +template +struct plain_array +{ + EIGEN_ALIGN_TO_BOUNDARY(16) T array[Size]; + + EIGEN_DEVICE_FUNC + plain_array() + { + EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(15); + check_static_allocation_size(); + } + + EIGEN_DEVICE_FUNC + plain_array(constructor_without_unaligned_array_assert) + { + check_static_allocation_size(); + } +}; + +template +struct plain_array +{ + EIGEN_ALIGN_TO_BOUNDARY(32) T array[Size]; + + EIGEN_DEVICE_FUNC + plain_array() + { + EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(31); + check_static_allocation_size(); + } + + EIGEN_DEVICE_FUNC + plain_array(constructor_without_unaligned_array_assert) + { + check_static_allocation_size(); + } +}; + +template +struct plain_array +{ + EIGEN_ALIGN_TO_BOUNDARY(64) T array[Size]; + + EIGEN_DEVICE_FUNC + plain_array() + { + EIGEN_MAKE_UNALIGNED_ARRAY_ASSERT(63); + check_static_allocation_size(); + } + + EIGEN_DEVICE_FUNC + plain_array(constructor_without_unaligned_array_assert) + { + check_static_allocation_size(); + } +}; + +template +struct plain_array +{ + T array[1]; + EIGEN_DEVICE_FUNC plain_array() {} + EIGEN_DEVICE_FUNC plain_array(constructor_without_unaligned_array_assert) {} +}; + +} // end namespace internal + +/** \internal + * + * \class DenseStorage + * \ingroup Core_Module + * + * \brief Stores the data of a matrix + * + * This class stores the data of fixed-size, dynamic-size or mixed matrices + * in a way as compact as possible. + * + * \sa Matrix + */ +template class DenseStorage; + +// purely fixed-size matrix +template class DenseStorage +{ + internal::plain_array m_data; + public: + EIGEN_DEVICE_FUNC DenseStorage() { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = Size) + } + EIGEN_DEVICE_FUNC + explicit DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(internal::constructor_without_unaligned_array_assert()) {} + EIGEN_DEVICE_FUNC + DenseStorage(const DenseStorage& other) : m_data(other.m_data) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = Size) + } + EIGEN_DEVICE_FUNC + DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) m_data = other.m_data; + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size==rows*cols && rows==_Rows && cols==_Cols); + EIGEN_UNUSED_VARIABLE(size); + EIGEN_UNUSED_VARIABLE(rows); + EIGEN_UNUSED_VARIABLE(cols); + } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { std::swap(m_data,other.m_data); } + EIGEN_DEVICE_FUNC static Index rows(void) {return _Rows;} + EIGEN_DEVICE_FUNC static Index cols(void) {return _Cols;} + EIGEN_DEVICE_FUNC void conservativeResize(Index,Index,Index) {} + EIGEN_DEVICE_FUNC void resize(Index,Index,Index) {} + EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } + EIGEN_DEVICE_FUNC T *data() { return m_data.array; } +}; + +// null matrix +template class DenseStorage +{ + public: + EIGEN_DEVICE_FUNC DenseStorage() {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage&) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage&) { return *this; } + EIGEN_DEVICE_FUNC DenseStorage(Index,Index,Index) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& ) {} + EIGEN_DEVICE_FUNC static Index rows(void) {return _Rows;} + EIGEN_DEVICE_FUNC static Index cols(void) {return _Cols;} + EIGEN_DEVICE_FUNC void conservativeResize(Index,Index,Index) {} + EIGEN_DEVICE_FUNC void resize(Index,Index,Index) {} + EIGEN_DEVICE_FUNC const T *data() const { return 0; } + EIGEN_DEVICE_FUNC T *data() { return 0; } +}; + +// more specializations for null matrices; these are necessary to resolve ambiguities +template class DenseStorage +: public DenseStorage { }; + +template class DenseStorage +: public DenseStorage { }; + +template class DenseStorage +: public DenseStorage { }; + +// dynamic-size matrix with fixed-size storage +template class DenseStorage +{ + internal::plain_array m_data; + Index m_rows; + Index m_cols; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_data(other.m_data), m_rows(other.m_rows), m_cols(other.m_cols) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + m_data = other.m_data; + m_rows = other.m_rows; + m_cols = other.m_cols; + } + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index cols) : m_rows(rows), m_cols(cols) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) + { std::swap(m_data,other.m_data); std::swap(m_rows,other.m_rows); std::swap(m_cols,other.m_cols); } + EIGEN_DEVICE_FUNC Index rows() const {return m_rows;} + EIGEN_DEVICE_FUNC Index cols() const {return m_cols;} + EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index cols) { m_rows = rows; m_cols = cols; } + EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index cols) { m_rows = rows; m_cols = cols; } + EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } + EIGEN_DEVICE_FUNC T *data() { return m_data.array; } +}; + +// dynamic-size matrix with fixed-size storage and fixed width +template class DenseStorage +{ + internal::plain_array m_data; + Index m_rows; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_rows(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(internal::constructor_without_unaligned_array_assert()), m_rows(0) {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_data(other.m_data), m_rows(other.m_rows) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + m_data = other.m_data; + m_rows = other.m_rows; + } + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index rows, Index) : m_rows(rows) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_rows,other.m_rows); } + EIGEN_DEVICE_FUNC Index rows(void) const {return m_rows;} + EIGEN_DEVICE_FUNC Index cols(void) const {return _Cols;} + EIGEN_DEVICE_FUNC void conservativeResize(Index, Index rows, Index) { m_rows = rows; } + EIGEN_DEVICE_FUNC void resize(Index, Index rows, Index) { m_rows = rows; } + EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } + EIGEN_DEVICE_FUNC T *data() { return m_data.array; } +}; + +// dynamic-size matrix with fixed-size storage and fixed height +template class DenseStorage +{ + internal::plain_array m_data; + Index m_cols; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_cols(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(internal::constructor_without_unaligned_array_assert()), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) : m_data(other.m_data), m_cols(other.m_cols) {} + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + m_data = other.m_data; + m_cols = other.m_cols; + } + return *this; + } + EIGEN_DEVICE_FUNC DenseStorage(Index, Index, Index cols) : m_cols(cols) {} + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_cols,other.m_cols); } + EIGEN_DEVICE_FUNC Index rows(void) const {return _Rows;} + EIGEN_DEVICE_FUNC Index cols(void) const {return m_cols;} + void conservativeResize(Index, Index, Index cols) { m_cols = cols; } + void resize(Index, Index, Index cols) { m_cols = cols; } + EIGEN_DEVICE_FUNC const T *data() const { return m_data.array; } + EIGEN_DEVICE_FUNC T *data() { return m_data.array; } +}; + +// purely dynamic matrix. +template class DenseStorage +{ + T *m_data; + Index m_rows; + Index m_cols; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC explicit DenseStorage(internal::constructor_without_unaligned_array_assert) + : m_data(0), m_rows(0), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) + : m_data(internal::conditional_aligned_new_auto(size)), m_rows(rows), m_cols(cols) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size==rows*cols && rows>=0 && cols >=0); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(other.m_rows*other.m_cols)) + , m_rows(other.m_rows) + , m_cols(other.m_cols) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows*m_cols) + internal::smart_copy(other.m_data, other.m_data+other.m_rows*other.m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + DenseStorage tmp(other); + this->swap(tmp); + } + return *this; + } +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT + : m_data(std::move(other.m_data)) + , m_rows(std::move(other.m_rows)) + , m_cols(std::move(other.m_cols)) + { + other.m_data = nullptr; + other.m_rows = 0; + other.m_cols = 0; + } + EIGEN_DEVICE_FUNC + DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT + { + using std::swap; + swap(m_data, other.m_data); + swap(m_rows, other.m_rows); + swap(m_cols, other.m_cols); + return *this; + } +#endif + EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols); } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) + { std::swap(m_data,other.m_data); std::swap(m_rows,other.m_rows); std::swap(m_cols,other.m_cols); } + EIGEN_DEVICE_FUNC Index rows(void) const {return m_rows;} + EIGEN_DEVICE_FUNC Index cols(void) const {return m_cols;} + void conservativeResize(Index size, Index rows, Index cols) + { + m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows*m_cols); + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC void resize(Index size, Index rows, Index cols) + { + if(size != m_rows*m_cols) + { + internal::conditional_aligned_delete_auto(m_data, m_rows*m_cols); + if (size) + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + } + m_rows = rows; + m_cols = cols; + } + EIGEN_DEVICE_FUNC const T *data() const { return m_data; } + EIGEN_DEVICE_FUNC T *data() { return m_data; } +}; + +// matrix with dynamic width and fixed height (so that matrix has dynamic size). +template class DenseStorage +{ + T *m_data; + Index m_cols; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_cols(0) {} + explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_cols(0) {} + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) : m_data(internal::conditional_aligned_new_auto(size)), m_cols(cols) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size==rows*cols && rows==_Rows && cols >=0); + EIGEN_UNUSED_VARIABLE(rows); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(_Rows*other.m_cols)) + , m_cols(other.m_cols) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_cols*_Rows) + internal::smart_copy(other.m_data, other.m_data+_Rows*m_cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + DenseStorage tmp(other); + this->swap(tmp); + } + return *this; + } +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT + : m_data(std::move(other.m_data)) + , m_cols(std::move(other.m_cols)) + { + other.m_data = nullptr; + other.m_cols = 0; + } + EIGEN_DEVICE_FUNC + DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT + { + using std::swap; + swap(m_data, other.m_data); + swap(m_cols, other.m_cols); + return *this; + } +#endif + EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, _Rows*m_cols); } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_cols,other.m_cols); } + EIGEN_DEVICE_FUNC static Index rows(void) {return _Rows;} + EIGEN_DEVICE_FUNC Index cols(void) const {return m_cols;} + EIGEN_DEVICE_FUNC void conservativeResize(Index size, Index, Index cols) + { + m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, _Rows*m_cols); + m_cols = cols; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index, Index cols) + { + if(size != _Rows*m_cols) + { + internal::conditional_aligned_delete_auto(m_data, _Rows*m_cols); + if (size) + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + } + m_cols = cols; + } + EIGEN_DEVICE_FUNC const T *data() const { return m_data; } + EIGEN_DEVICE_FUNC T *data() { return m_data; } +}; + +// matrix with dynamic height and fixed width (so that matrix has dynamic size). +template class DenseStorage +{ + T *m_data; + Index m_rows; + public: + EIGEN_DEVICE_FUNC DenseStorage() : m_data(0), m_rows(0) {} + explicit DenseStorage(internal::constructor_without_unaligned_array_assert) : m_data(0), m_rows(0) {} + EIGEN_DEVICE_FUNC DenseStorage(Index size, Index rows, Index cols) : m_data(internal::conditional_aligned_new_auto(size)), m_rows(rows) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + eigen_internal_assert(size==rows*cols && rows>=0 && cols == _Cols); + EIGEN_UNUSED_VARIABLE(cols); + } + EIGEN_DEVICE_FUNC DenseStorage(const DenseStorage& other) + : m_data(internal::conditional_aligned_new_auto(other.m_rows*_Cols)) + , m_rows(other.m_rows) + { + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN(Index size = m_rows*_Cols) + internal::smart_copy(other.m_data, other.m_data+other.m_rows*_Cols, m_data); + } + EIGEN_DEVICE_FUNC DenseStorage& operator=(const DenseStorage& other) + { + if (this != &other) + { + DenseStorage tmp(other); + this->swap(tmp); + } + return *this; + } +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + DenseStorage(DenseStorage&& other) EIGEN_NOEXCEPT + : m_data(std::move(other.m_data)) + , m_rows(std::move(other.m_rows)) + { + other.m_data = nullptr; + other.m_rows = 0; + } + EIGEN_DEVICE_FUNC + DenseStorage& operator=(DenseStorage&& other) EIGEN_NOEXCEPT + { + using std::swap; + swap(m_data, other.m_data); + swap(m_rows, other.m_rows); + return *this; + } +#endif + EIGEN_DEVICE_FUNC ~DenseStorage() { internal::conditional_aligned_delete_auto(m_data, _Cols*m_rows); } + EIGEN_DEVICE_FUNC void swap(DenseStorage& other) { std::swap(m_data,other.m_data); std::swap(m_rows,other.m_rows); } + EIGEN_DEVICE_FUNC Index rows(void) const {return m_rows;} + EIGEN_DEVICE_FUNC static Index cols(void) {return _Cols;} + void conservativeResize(Index size, Index rows, Index) + { + m_data = internal::conditional_aligned_realloc_new_auto(m_data, size, m_rows*_Cols); + m_rows = rows; + } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resize(Index size, Index rows, Index) + { + if(size != m_rows*_Cols) + { + internal::conditional_aligned_delete_auto(m_data, _Cols*m_rows); + if (size) + m_data = internal::conditional_aligned_new_auto(size); + else + m_data = 0; + EIGEN_INTERNAL_DENSE_STORAGE_CTOR_PLUGIN({}) + } + m_rows = rows; + } + EIGEN_DEVICE_FUNC const T *data() const { return m_data; } + EIGEN_DEVICE_FUNC T *data() { return m_data; } +}; + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Diagonal.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Diagonal.h new file mode 100644 index 0000000000000000000000000000000000000000..afcaf3575677ced89e094715fe97c3b8b9864c5d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Diagonal.h @@ -0,0 +1,260 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2007-2009 Benoit Jacob +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DIAGONAL_H +#define EIGEN_DIAGONAL_H + +namespace Eigen { + +/** \class Diagonal + * \ingroup Core_Module + * + * \brief Expression of a diagonal/subdiagonal/superdiagonal in a matrix + * + * \param MatrixType the type of the object in which we are taking a sub/main/super diagonal + * \param DiagIndex the index of the sub/super diagonal. The default is 0 and it means the main diagonal. + * A positive value means a superdiagonal, a negative value means a subdiagonal. + * You can also use DynamicIndex so the index can be set at runtime. + * + * The matrix is not required to be square. + * + * This class represents an expression of the main diagonal, or any sub/super diagonal + * of a square matrix. It is the return type of MatrixBase::diagonal() and MatrixBase::diagonal(Index) and most of the + * time this is the only way it is used. + * + * \sa MatrixBase::diagonal(), MatrixBase::diagonal(Index) + */ + +namespace internal { +template +struct traits > + : traits +{ + typedef typename ref_selector::type MatrixTypeNested; + typedef typename remove_reference::type _MatrixTypeNested; + typedef typename MatrixType::StorageKind StorageKind; + enum { + RowsAtCompileTime = (int(DiagIndex) == DynamicIndex || int(MatrixType::SizeAtCompileTime) == Dynamic) ? Dynamic + : (EIGEN_PLAIN_ENUM_MIN(MatrixType::RowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0), + MatrixType::ColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))), + ColsAtCompileTime = 1, + MaxRowsAtCompileTime = int(MatrixType::MaxSizeAtCompileTime) == Dynamic ? Dynamic + : DiagIndex == DynamicIndex ? EIGEN_SIZE_MIN_PREFER_FIXED(MatrixType::MaxRowsAtCompileTime, + MatrixType::MaxColsAtCompileTime) + : (EIGEN_PLAIN_ENUM_MIN(MatrixType::MaxRowsAtCompileTime - EIGEN_PLAIN_ENUM_MAX(-DiagIndex, 0), + MatrixType::MaxColsAtCompileTime - EIGEN_PLAIN_ENUM_MAX( DiagIndex, 0))), + MaxColsAtCompileTime = 1, + MaskLvalueBit = is_lvalue::value ? LvalueBit : 0, + Flags = (unsigned int)_MatrixTypeNested::Flags & (RowMajorBit | MaskLvalueBit | DirectAccessBit) & ~RowMajorBit, // FIXME DirectAccessBit should not be handled by expressions + MatrixTypeOuterStride = outer_stride_at_compile_time::ret, + InnerStrideAtCompileTime = MatrixTypeOuterStride == Dynamic ? Dynamic : MatrixTypeOuterStride+1, + OuterStrideAtCompileTime = 0 + }; +}; +} + +template class Diagonal + : public internal::dense_xpr_base< Diagonal >::type +{ + public: + + enum { DiagIndex = _DiagIndex }; + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Diagonal) + + EIGEN_DEVICE_FUNC + explicit inline Diagonal(MatrixType& matrix, Index a_index = DiagIndex) : m_matrix(matrix), m_index(a_index) + { + eigen_assert( a_index <= m_matrix.cols() && -a_index <= m_matrix.rows() ); + } + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Diagonal) + + EIGEN_DEVICE_FUNC + inline Index rows() const + { + return m_index.value()<0 ? numext::mini(m_matrix.cols(),m_matrix.rows()+m_index.value()) + : numext::mini(m_matrix.rows(),m_matrix.cols()-m_index.value()); + } + + EIGEN_DEVICE_FUNC + inline Index cols() const { return 1; } + + EIGEN_DEVICE_FUNC + inline Index innerStride() const + { + return m_matrix.outerStride() + 1; + } + + EIGEN_DEVICE_FUNC + inline Index outerStride() const + { + return 0; + } + + typedef typename internal::conditional< + internal::is_lvalue::value, + Scalar, + const Scalar + >::type ScalarWithConstIfNotLvalue; + + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue* data() { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } + EIGEN_DEVICE_FUNC + inline const Scalar* data() const { return &(m_matrix.coeffRef(rowOffset(), colOffset())); } + + EIGEN_DEVICE_FUNC + inline Scalar& coeffRef(Index row, Index) + { + EIGEN_STATIC_ASSERT_LVALUE(MatrixType) + return m_matrix.coeffRef(row+rowOffset(), row+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index row, Index) const + { + return m_matrix.coeffRef(row+rowOffset(), row+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline CoeffReturnType coeff(Index row, Index) const + { + return m_matrix.coeff(row+rowOffset(), row+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline Scalar& coeffRef(Index idx) + { + EIGEN_STATIC_ASSERT_LVALUE(MatrixType) + return m_matrix.coeffRef(idx+rowOffset(), idx+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index idx) const + { + return m_matrix.coeffRef(idx+rowOffset(), idx+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline CoeffReturnType coeff(Index idx) const + { + return m_matrix.coeff(idx+rowOffset(), idx+colOffset()); + } + + EIGEN_DEVICE_FUNC + inline const typename internal::remove_all::type& + nestedExpression() const + { + return m_matrix; + } + + EIGEN_DEVICE_FUNC + inline Index index() const + { + return m_index.value(); + } + + protected: + typename internal::ref_selector::non_const_type m_matrix; + const internal::variable_if_dynamicindex m_index; + + private: + // some compilers may fail to optimize std::max etc in case of compile-time constants... + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index absDiagIndex() const { return m_index.value()>0 ? m_index.value() : -m_index.value(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rowOffset() const { return m_index.value()>0 ? 0 : -m_index.value(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index colOffset() const { return m_index.value()>0 ? m_index.value() : 0; } + // trigger a compile-time error if someone try to call packet + template typename MatrixType::PacketReturnType packet(Index) const; + template typename MatrixType::PacketReturnType packet(Index,Index) const; +}; + +/** \returns an expression of the main diagonal of the matrix \c *this + * + * \c *this is not required to be square. + * + * Example: \include MatrixBase_diagonal.cpp + * Output: \verbinclude MatrixBase_diagonal.out + * + * \sa class Diagonal */ +template +inline typename MatrixBase::DiagonalReturnType +MatrixBase::diagonal() +{ + return DiagonalReturnType(derived()); +} + +/** This is the const version of diagonal(). */ +template +inline typename MatrixBase::ConstDiagonalReturnType +MatrixBase::diagonal() const +{ + return ConstDiagonalReturnType(derived()); +} + +/** \returns an expression of the \a DiagIndex-th sub or super diagonal of the matrix \c *this + * + * \c *this is not required to be square. + * + * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 + * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. + * + * Example: \include MatrixBase_diagonal_int.cpp + * Output: \verbinclude MatrixBase_diagonal_int.out + * + * \sa MatrixBase::diagonal(), class Diagonal */ +template +inline typename MatrixBase::DiagonalDynamicIndexReturnType +MatrixBase::diagonal(Index index) +{ + return DiagonalDynamicIndexReturnType(derived(), index); +} + +/** This is the const version of diagonal(Index). */ +template +inline typename MatrixBase::ConstDiagonalDynamicIndexReturnType +MatrixBase::diagonal(Index index) const +{ + return ConstDiagonalDynamicIndexReturnType(derived(), index); +} + +/** \returns an expression of the \a DiagIndex-th sub or super diagonal of the matrix \c *this + * + * \c *this is not required to be square. + * + * The template parameter \a DiagIndex represent a super diagonal if \a DiagIndex > 0 + * and a sub diagonal otherwise. \a DiagIndex == 0 is equivalent to the main diagonal. + * + * Example: \include MatrixBase_diagonal_template_int.cpp + * Output: \verbinclude MatrixBase_diagonal_template_int.out + * + * \sa MatrixBase::diagonal(), class Diagonal */ +template +template +inline typename MatrixBase::template DiagonalIndexReturnType::Type +MatrixBase::diagonal() +{ + return typename DiagonalIndexReturnType::Type(derived()); +} + +/** This is the const version of diagonal(). */ +template +template +inline typename MatrixBase::template ConstDiagonalIndexReturnType::Type +MatrixBase::diagonal() const +{ + return typename ConstDiagonalIndexReturnType::Type(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_DIAGONAL_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalMatrix.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..ecfdce8efa1c9be1a2d6bcc7f36d3ab16fc2622a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalMatrix.h @@ -0,0 +1,343 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// Copyright (C) 2007-2009 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DIAGONALMATRIX_H +#define EIGEN_DIAGONALMATRIX_H + +namespace Eigen { + +#ifndef EIGEN_PARSED_BY_DOXYGEN +template +class DiagonalBase : public EigenBase +{ + public: + typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; + typedef typename DiagonalVectorType::Scalar Scalar; + typedef typename DiagonalVectorType::RealScalar RealScalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + + enum { + RowsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + ColsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + MaxRowsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + IsVectorAtCompileTime = 0, + Flags = NoPreferredStorageOrderBit + }; + + typedef Matrix DenseMatrixType; + typedef DenseMatrixType DenseType; + typedef DiagonalMatrix PlainObject; + + EIGEN_DEVICE_FUNC + inline const Derived& derived() const { return *static_cast(this); } + EIGEN_DEVICE_FUNC + inline Derived& derived() { return *static_cast(this); } + + EIGEN_DEVICE_FUNC + DenseMatrixType toDenseMatrix() const { return derived(); } + + EIGEN_DEVICE_FUNC + inline const DiagonalVectorType& diagonal() const { return derived().diagonal(); } + EIGEN_DEVICE_FUNC + inline DiagonalVectorType& diagonal() { return derived().diagonal(); } + + EIGEN_DEVICE_FUNC + inline Index rows() const { return diagonal().size(); } + EIGEN_DEVICE_FUNC + inline Index cols() const { return diagonal().size(); } + + template + EIGEN_DEVICE_FUNC + const Product + operator*(const MatrixBase &matrix) const + { + return Product(derived(),matrix.derived()); + } + + typedef DiagonalWrapper, const DiagonalVectorType> > InverseReturnType; + EIGEN_DEVICE_FUNC + inline const InverseReturnType + inverse() const + { + return InverseReturnType(diagonal().cwiseInverse()); + } + + EIGEN_DEVICE_FUNC + inline const DiagonalWrapper + operator*(const Scalar& scalar) const + { + return DiagonalWrapper(diagonal() * scalar); + } + EIGEN_DEVICE_FUNC + friend inline const DiagonalWrapper + operator*(const Scalar& scalar, const DiagonalBase& other) + { + return DiagonalWrapper(scalar * other.diagonal()); + } +}; + +#endif + +/** \class DiagonalMatrix + * \ingroup Core_Module + * + * \brief Represents a diagonal matrix with its storage + * + * \param _Scalar the type of coefficients + * \param SizeAtCompileTime the dimension of the matrix, or Dynamic + * \param MaxSizeAtCompileTime the dimension of the matrix, or Dynamic. This parameter is optional and defaults + * to SizeAtCompileTime. Most of the time, you do not need to specify it. + * + * \sa class DiagonalWrapper + */ + +namespace internal { +template +struct traits > + : traits > +{ + typedef Matrix<_Scalar,SizeAtCompileTime,1,0,MaxSizeAtCompileTime,1> DiagonalVectorType; + typedef DiagonalShape StorageKind; + enum { + Flags = LvalueBit | NoPreferredStorageOrderBit + }; +}; +} +template +class DiagonalMatrix + : public DiagonalBase > +{ + public: + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename internal::traits::DiagonalVectorType DiagonalVectorType; + typedef const DiagonalMatrix& Nested; + typedef _Scalar Scalar; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + #endif + + protected: + + DiagonalVectorType m_diagonal; + + public: + + /** const version of diagonal(). */ + EIGEN_DEVICE_FUNC + inline const DiagonalVectorType& diagonal() const { return m_diagonal; } + /** \returns a reference to the stored vector of diagonal coefficients. */ + EIGEN_DEVICE_FUNC + inline DiagonalVectorType& diagonal() { return m_diagonal; } + + /** Default constructor without initialization */ + EIGEN_DEVICE_FUNC + inline DiagonalMatrix() {} + + /** Constructs a diagonal matrix with given dimension */ + EIGEN_DEVICE_FUNC + explicit inline DiagonalMatrix(Index dim) : m_diagonal(dim) {} + + /** 2D constructor. */ + EIGEN_DEVICE_FUNC + inline DiagonalMatrix(const Scalar& x, const Scalar& y) : m_diagonal(x,y) {} + + /** 3D constructor. */ + EIGEN_DEVICE_FUNC + inline DiagonalMatrix(const Scalar& x, const Scalar& y, const Scalar& z) : m_diagonal(x,y,z) {} + + /** Copy constructor. */ + template + EIGEN_DEVICE_FUNC + inline DiagonalMatrix(const DiagonalBase& other) : m_diagonal(other.diagonal()) {} + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** copy constructor. prevent a default copy constructor from hiding the other templated constructor */ + inline DiagonalMatrix(const DiagonalMatrix& other) : m_diagonal(other.diagonal()) {} + #endif + + /** generic constructor from expression of the diagonal coefficients */ + template + EIGEN_DEVICE_FUNC + explicit inline DiagonalMatrix(const MatrixBase& other) : m_diagonal(other) + {} + + /** Copy operator. */ + template + EIGEN_DEVICE_FUNC + DiagonalMatrix& operator=(const DiagonalBase& other) + { + m_diagonal = other.diagonal(); + return *this; + } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC + DiagonalMatrix& operator=(const DiagonalMatrix& other) + { + m_diagonal = other.diagonal(); + return *this; + } + #endif + + /** Resizes to given size. */ + EIGEN_DEVICE_FUNC + inline void resize(Index size) { m_diagonal.resize(size); } + /** Sets all coefficients to zero. */ + EIGEN_DEVICE_FUNC + inline void setZero() { m_diagonal.setZero(); } + /** Resizes and sets all coefficients to zero. */ + EIGEN_DEVICE_FUNC + inline void setZero(Index size) { m_diagonal.setZero(size); } + /** Sets this matrix to be the identity matrix of the current size. */ + EIGEN_DEVICE_FUNC + inline void setIdentity() { m_diagonal.setOnes(); } + /** Sets this matrix to be the identity matrix of the given size. */ + EIGEN_DEVICE_FUNC + inline void setIdentity(Index size) { m_diagonal.setOnes(size); } +}; + +/** \class DiagonalWrapper + * \ingroup Core_Module + * + * \brief Expression of a diagonal matrix + * + * \param _DiagonalVectorType the type of the vector of diagonal coefficients + * + * This class is an expression of a diagonal matrix, but not storing its own vector of diagonal coefficients, + * instead wrapping an existing vector expression. It is the return type of MatrixBase::asDiagonal() + * and most of the time this is the only way that it is used. + * + * \sa class DiagonalMatrix, class DiagonalBase, MatrixBase::asDiagonal() + */ + +namespace internal { +template +struct traits > +{ + typedef _DiagonalVectorType DiagonalVectorType; + typedef typename DiagonalVectorType::Scalar Scalar; + typedef typename DiagonalVectorType::StorageIndex StorageIndex; + typedef DiagonalShape StorageKind; + typedef typename traits::XprKind XprKind; + enum { + RowsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + ColsAtCompileTime = DiagonalVectorType::SizeAtCompileTime, + MaxRowsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = DiagonalVectorType::MaxSizeAtCompileTime, + Flags = (traits::Flags & LvalueBit) | NoPreferredStorageOrderBit + }; +}; +} + +template +class DiagonalWrapper + : public DiagonalBase >, internal::no_assignment_operator +{ + public: + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef _DiagonalVectorType DiagonalVectorType; + typedef DiagonalWrapper Nested; + #endif + + /** Constructor from expression of diagonal coefficients to wrap. */ + EIGEN_DEVICE_FUNC + explicit inline DiagonalWrapper(DiagonalVectorType& a_diagonal) : m_diagonal(a_diagonal) {} + + /** \returns a const reference to the wrapped expression of diagonal coefficients. */ + EIGEN_DEVICE_FUNC + const DiagonalVectorType& diagonal() const { return m_diagonal; } + + protected: + typename DiagonalVectorType::Nested m_diagonal; +}; + +/** \returns a pseudo-expression of a diagonal matrix with *this as vector of diagonal coefficients + * + * \only_for_vectors + * + * Example: \include MatrixBase_asDiagonal.cpp + * Output: \verbinclude MatrixBase_asDiagonal.out + * + * \sa class DiagonalWrapper, class DiagonalMatrix, diagonal(), isDiagonal() + **/ +template +inline const DiagonalWrapper +MatrixBase::asDiagonal() const +{ + return DiagonalWrapper(derived()); +} + +/** \returns true if *this is approximately equal to a diagonal matrix, + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isDiagonal.cpp + * Output: \verbinclude MatrixBase_isDiagonal.out + * + * \sa asDiagonal() + */ +template +bool MatrixBase::isDiagonal(const RealScalar& prec) const +{ + if(cols() != rows()) return false; + RealScalar maxAbsOnDiagonal = static_cast(-1); + for(Index j = 0; j < cols(); ++j) + { + RealScalar absOnDiagonal = numext::abs(coeff(j,j)); + if(absOnDiagonal > maxAbsOnDiagonal) maxAbsOnDiagonal = absOnDiagonal; + } + for(Index j = 0; j < cols(); ++j) + for(Index i = 0; i < j; ++i) + { + if(!internal::isMuchSmallerThan(coeff(i, j), maxAbsOnDiagonal, prec)) return false; + if(!internal::isMuchSmallerThan(coeff(j, i), maxAbsOnDiagonal, prec)) return false; + } + return true; +} + +namespace internal { + +template<> struct storage_kind_to_shape { typedef DiagonalShape Shape; }; + +struct Diagonal2Dense {}; + +template<> struct AssignmentKind { typedef Diagonal2Dense Kind; }; + +// Diagonal matrix to Dense assignment +template< typename DstXprType, typename SrcXprType, typename Functor> +struct Assignment +{ + static void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &/*func*/) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + + dst.setZero(); + dst.diagonal() = src.diagonal(); + } + + static void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &/*func*/) + { dst.diagonal() += src.diagonal(); } + + static void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &/*func*/) + { dst.diagonal() -= src.diagonal(); } +}; + +} // namespace internal + +} // end namespace Eigen + +#endif // EIGEN_DIAGONALMATRIX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalProduct.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..d372b938f656c042c0413c88aa5eaf4e5bb977d6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/DiagonalProduct.h @@ -0,0 +1,28 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2007-2009 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DIAGONALPRODUCT_H +#define EIGEN_DIAGONALPRODUCT_H + +namespace Eigen { + +/** \returns the diagonal matrix product of \c *this by the diagonal matrix \a diagonal. + */ +template +template +inline const Product +MatrixBase::operator*(const DiagonalBase &a_diagonal) const +{ + return Product(derived(),a_diagonal.derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_DIAGONALPRODUCT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Dot.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Dot.h new file mode 100644 index 0000000000000000000000000000000000000000..1fe7a84a48dc94c24d287a36607587486c2293cf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Dot.h @@ -0,0 +1,318 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008, 2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DOT_H +#define EIGEN_DOT_H + +namespace Eigen { + +namespace internal { + +// helper function for dot(). The problem is that if we put that in the body of dot(), then upon calling dot +// with mismatched types, the compiler emits errors about failing to instantiate cwiseProduct BEFORE +// looking at the static assertions. Thus this is a trick to get better compile errors. +template +struct dot_nocheck +{ + typedef scalar_conj_product_op::Scalar,typename traits::Scalar> conj_prod; + typedef typename conj_prod::result_type ResScalar; + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE + static ResScalar run(const MatrixBase& a, const MatrixBase& b) + { + return a.template binaryExpr(b).sum(); + } +}; + +template +struct dot_nocheck +{ + typedef scalar_conj_product_op::Scalar,typename traits::Scalar> conj_prod; + typedef typename conj_prod::result_type ResScalar; + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE + static ResScalar run(const MatrixBase& a, const MatrixBase& b) + { + return a.transpose().template binaryExpr(b).sum(); + } +}; + +} // end namespace internal + +/** \fn MatrixBase::dot + * \returns the dot product of *this with other. + * + * \only_for_vectors + * + * \note If the scalar type is complex numbers, then this function returns the hermitian + * (sesquilinear) dot product, conjugate-linear in the first variable and linear in the + * second variable. + * + * \sa squaredNorm(), norm() + */ +template +template +EIGEN_DEVICE_FUNC +EIGEN_STRONG_INLINE +typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType +MatrixBase::dot(const MatrixBase& other) const +{ + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived) + EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived,OtherDerived) +#if !(defined(EIGEN_NO_STATIC_ASSERT) && defined(EIGEN_NO_DEBUG)) + typedef internal::scalar_conj_product_op func; + EIGEN_CHECK_BINARY_COMPATIBILIY(func,Scalar,typename OtherDerived::Scalar); +#endif + + eigen_assert(size() == other.size()); + + return internal::dot_nocheck::run(*this, other); +} + +//---------- implementation of L2 norm and related functions ---------- + +/** \returns, for vectors, the squared \em l2 norm of \c *this, and for matrices the Frobenius norm. + * In both cases, it consists in the sum of the square of all the matrix entries. + * For vectors, this is also equals to the dot product of \c *this with itself. + * + * \sa dot(), norm(), lpNorm() + */ +template +EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real MatrixBase::squaredNorm() const +{ + return numext::real((*this).cwiseAbs2().sum()); +} + +/** \returns, for vectors, the \em l2 norm of \c *this, and for matrices the Frobenius norm. + * In both cases, it consists in the square root of the sum of the square of all the matrix entries. + * For vectors, this is also equals to the square root of the dot product of \c *this with itself. + * + * \sa lpNorm(), dot(), squaredNorm() + */ +template +EIGEN_STRONG_INLINE typename NumTraits::Scalar>::Real MatrixBase::norm() const +{ + return numext::sqrt(squaredNorm()); +} + +/** \returns an expression of the quotient of \c *this by its own norm. + * + * \warning If the input vector is too small (i.e., this->norm()==0), + * then this function returns a copy of the input. + * + * \only_for_vectors + * + * \sa norm(), normalize() + */ +template +EIGEN_STRONG_INLINE const typename MatrixBase::PlainObject +MatrixBase::normalized() const +{ + typedef typename internal::nested_eval::type _Nested; + _Nested n(derived()); + RealScalar z = n.squaredNorm(); + // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU + if(z>RealScalar(0)) + return n / numext::sqrt(z); + else + return n; +} + +/** Normalizes the vector, i.e. divides it by its own norm. + * + * \only_for_vectors + * + * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. + * + * \sa norm(), normalized() + */ +template +EIGEN_STRONG_INLINE void MatrixBase::normalize() +{ + RealScalar z = squaredNorm(); + // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU + if(z>RealScalar(0)) + derived() /= numext::sqrt(z); +} + +/** \returns an expression of the quotient of \c *this by its own norm while avoiding underflow and overflow. + * + * \only_for_vectors + * + * This method is analogue to the normalized() method, but it reduces the risk of + * underflow and overflow when computing the norm. + * + * \warning If the input vector is too small (i.e., this->norm()==0), + * then this function returns a copy of the input. + * + * \sa stableNorm(), stableNormalize(), normalized() + */ +template +EIGEN_STRONG_INLINE const typename MatrixBase::PlainObject +MatrixBase::stableNormalized() const +{ + typedef typename internal::nested_eval::type _Nested; + _Nested n(derived()); + RealScalar w = n.cwiseAbs().maxCoeff(); + RealScalar z = (n/w).squaredNorm(); + if(z>RealScalar(0)) + return n / (numext::sqrt(z)*w); + else + return n; +} + +/** Normalizes the vector while avoid underflow and overflow + * + * \only_for_vectors + * + * This method is analogue to the normalize() method, but it reduces the risk of + * underflow and overflow when computing the norm. + * + * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged. + * + * \sa stableNorm(), stableNormalized(), normalize() + */ +template +EIGEN_STRONG_INLINE void MatrixBase::stableNormalize() +{ + RealScalar w = cwiseAbs().maxCoeff(); + RealScalar z = (derived()/w).squaredNorm(); + if(z>RealScalar(0)) + derived() /= numext::sqrt(z)*w; +} + +//---------- implementation of other norms ---------- + +namespace internal { + +template +struct lpNorm_selector +{ + typedef typename NumTraits::Scalar>::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const MatrixBase& m) + { + EIGEN_USING_STD_MATH(pow) + return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1)/p); + } +}; + +template +struct lpNorm_selector +{ + EIGEN_DEVICE_FUNC + static inline typename NumTraits::Scalar>::Real run(const MatrixBase& m) + { + return m.cwiseAbs().sum(); + } +}; + +template +struct lpNorm_selector +{ + EIGEN_DEVICE_FUNC + static inline typename NumTraits::Scalar>::Real run(const MatrixBase& m) + { + return m.norm(); + } +}; + +template +struct lpNorm_selector +{ + typedef typename NumTraits::Scalar>::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const MatrixBase& m) + { + if(Derived::SizeAtCompileTime==0 || (Derived::SizeAtCompileTime==Dynamic && m.size()==0)) + return RealScalar(0); + return m.cwiseAbs().maxCoeff(); + } +}; + +} // end namespace internal + +/** \returns the \b coefficient-wise \f$ \ell^p \f$ norm of \c *this, that is, returns the p-th root of the sum of the p-th powers of the absolute values + * of the coefficients of \c *this. If \a p is the special value \a Eigen::Infinity, this function returns the \f$ \ell^\infty \f$ + * norm, that is the maximum of the absolute values of the coefficients of \c *this. + * + * In all cases, if \c *this is empty, then the value 0 is returned. + * + * \note For matrices, this function does not compute the operator-norm. That is, if \c *this is a matrix, then its coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm matrix operator norms using \link TutorialReductionsVisitorsBroadcastingReductionsNorm partial reductions \endlink. + * + * \sa norm() + */ +template +template +#ifndef EIGEN_PARSED_BY_DOXYGEN +inline typename NumTraits::Scalar>::Real +#else +MatrixBase::RealScalar +#endif +MatrixBase::lpNorm() const +{ + return internal::lpNorm_selector::run(*this); +} + +//---------- implementation of isOrthogonal / isUnitary ---------- + +/** \returns true if *this is approximately orthogonal to \a other, + * within the precision given by \a prec. + * + * Example: \include MatrixBase_isOrthogonal.cpp + * Output: \verbinclude MatrixBase_isOrthogonal.out + */ +template +template +bool MatrixBase::isOrthogonal +(const MatrixBase& other, const RealScalar& prec) const +{ + typename internal::nested_eval::type nested(derived()); + typename internal::nested_eval::type otherNested(other.derived()); + return numext::abs2(nested.dot(otherNested)) <= prec * prec * nested.squaredNorm() * otherNested.squaredNorm(); +} + +/** \returns true if *this is approximately an unitary matrix, + * within the precision given by \a prec. In the case where the \a Scalar + * type is real numbers, a unitary matrix is an orthogonal matrix, whence the name. + * + * \note This can be used to check whether a family of vectors forms an orthonormal basis. + * Indeed, \c m.isUnitary() returns true if and only if the columns (equivalently, the rows) of m form an + * orthonormal basis. + * + * Example: \include MatrixBase_isUnitary.cpp + * Output: \verbinclude MatrixBase_isUnitary.out + */ +template +bool MatrixBase::isUnitary(const RealScalar& prec) const +{ + typename internal::nested_eval::type self(derived()); + for(Index i = 0; i < cols(); ++i) + { + if(!internal::isApprox(self.col(i).squaredNorm(), static_cast(1), prec)) + return false; + for(Index j = 0; j < i; ++j) + if(!internal::isMuchSmallerThan(self.col(i).dot(self.col(j)), static_cast(1), prec)) + return false; + } + return true; +} + +} // end namespace Eigen + +#endif // EIGEN_DOT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/EigenBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/EigenBase.h new file mode 100644 index 0000000000000000000000000000000000000000..b195506a91e8c6c60fe3da6151878a3100caf390 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/EigenBase.h @@ -0,0 +1,159 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Benoit Jacob +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_EIGENBASE_H +#define EIGEN_EIGENBASE_H + +namespace Eigen { + +/** \class EigenBase + * \ingroup Core_Module + * + * Common base class for all classes T such that MatrixBase has an operator=(T) and a constructor MatrixBase(T). + * + * In other words, an EigenBase object is an object that can be copied into a MatrixBase. + * + * Besides MatrixBase-derived classes, this also includes special matrix classes such as diagonal matrices, etc. + * + * Notice that this class is trivial, it is only used to disambiguate overloaded functions. + * + * \sa \blank \ref TopicClassHierarchy + */ +template struct EigenBase +{ +// typedef typename internal::plain_matrix_type::type PlainObject; + + /** \brief The interface type of indices + * \details To change this, \c \#define the preprocessor symbol \c EIGEN_DEFAULT_DENSE_INDEX_TYPE. + * \deprecated Since Eigen 3.3, its usage is deprecated. Use Eigen::Index instead. + * \sa StorageIndex, \ref TopicPreprocessorDirectives. + */ + typedef Eigen::Index Index; + + // FIXME is it needed? + typedef typename internal::traits::StorageKind StorageKind; + + /** \returns a reference to the derived object */ + EIGEN_DEVICE_FUNC + Derived& derived() { return *static_cast(this); } + /** \returns a const reference to the derived object */ + EIGEN_DEVICE_FUNC + const Derived& derived() const { return *static_cast(this); } + + EIGEN_DEVICE_FUNC + inline Derived& const_cast_derived() const + { return *static_cast(const_cast(this)); } + EIGEN_DEVICE_FUNC + inline const Derived& const_derived() const + { return *static_cast(this); } + + /** \returns the number of rows. \sa cols(), RowsAtCompileTime */ + EIGEN_DEVICE_FUNC + inline Index rows() const { return derived().rows(); } + /** \returns the number of columns. \sa rows(), ColsAtCompileTime*/ + EIGEN_DEVICE_FUNC + inline Index cols() const { return derived().cols(); } + /** \returns the number of coefficients, which is rows()*cols(). + * \sa rows(), cols(), SizeAtCompileTime. */ + EIGEN_DEVICE_FUNC + inline Index size() const { return rows() * cols(); } + + /** \internal Don't use it, but do the equivalent: \code dst = *this; \endcode */ + template + EIGEN_DEVICE_FUNC + inline void evalTo(Dest& dst) const + { derived().evalTo(dst); } + + /** \internal Don't use it, but do the equivalent: \code dst += *this; \endcode */ + template + EIGEN_DEVICE_FUNC + inline void addTo(Dest& dst) const + { + // This is the default implementation, + // derived class can reimplement it in a more optimized way. + typename Dest::PlainObject res(rows(),cols()); + evalTo(res); + dst += res; + } + + /** \internal Don't use it, but do the equivalent: \code dst -= *this; \endcode */ + template + EIGEN_DEVICE_FUNC + inline void subTo(Dest& dst) const + { + // This is the default implementation, + // derived class can reimplement it in a more optimized way. + typename Dest::PlainObject res(rows(),cols()); + evalTo(res); + dst -= res; + } + + /** \internal Don't use it, but do the equivalent: \code dst.applyOnTheRight(*this); \endcode */ + template + EIGEN_DEVICE_FUNC inline void applyThisOnTheRight(Dest& dst) const + { + // This is the default implementation, + // derived class can reimplement it in a more optimized way. + dst = dst * this->derived(); + } + + /** \internal Don't use it, but do the equivalent: \code dst.applyOnTheLeft(*this); \endcode */ + template + EIGEN_DEVICE_FUNC inline void applyThisOnTheLeft(Dest& dst) const + { + // This is the default implementation, + // derived class can reimplement it in a more optimized way. + dst = this->derived() * dst; + } + +}; + +/*************************************************************************** +* Implementation of matrix base methods +***************************************************************************/ + +/** \brief Copies the generic expression \a other into *this. + * + * \details The expression must provide a (templated) evalTo(Derived& dst) const + * function which does the actual job. In practice, this allows any user to write + * its own special matrix without having to modify MatrixBase + * + * \returns a reference to *this. + */ +template +template +EIGEN_DEVICE_FUNC +Derived& DenseBase::operator=(const EigenBase &other) +{ + call_assignment(derived(), other.derived()); + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +Derived& DenseBase::operator+=(const EigenBase &other) +{ + call_assignment(derived(), other.derived(), internal::add_assign_op()); + return derived(); +} + +template +template +EIGEN_DEVICE_FUNC +Derived& DenseBase::operator-=(const EigenBase &other) +{ + call_assignment(derived(), other.derived(), internal::sub_assign_op()); + return derived(); +} + +} // end namespace Eigen + +#endif // EIGEN_EIGENBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ForceAlignedAccess.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ForceAlignedAccess.h new file mode 100644 index 0000000000000000000000000000000000000000..7b08b45e67c8bd72a7b6d574855d86ff67253c71 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ForceAlignedAccess.h @@ -0,0 +1,146 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_FORCEALIGNEDACCESS_H +#define EIGEN_FORCEALIGNEDACCESS_H + +namespace Eigen { + +/** \class ForceAlignedAccess + * \ingroup Core_Module + * + * \brief Enforce aligned packet loads and stores regardless of what is requested + * + * \param ExpressionType the type of the object of which we are forcing aligned packet access + * + * This class is the return type of MatrixBase::forceAlignedAccess() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::forceAlignedAccess() + */ + +namespace internal { +template +struct traits > : public traits +{}; +} + +template class ForceAlignedAccess + : public internal::dense_xpr_base< ForceAlignedAccess >::type +{ + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ForceAlignedAccess) + + EIGEN_DEVICE_FUNC explicit inline ForceAlignedAccess(const ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC inline Index rows() const { return m_expression.rows(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return m_expression.cols(); } + EIGEN_DEVICE_FUNC inline Index outerStride() const { return m_expression.outerStride(); } + EIGEN_DEVICE_FUNC inline Index innerStride() const { return m_expression.innerStride(); } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const + { + return m_expression.coeff(row, col); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) + { + return m_expression.const_cast_derived().coeffRef(row, col); + } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const + { + return m_expression.coeff(index); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) + { + return m_expression.const_cast_derived().coeffRef(index); + } + + template + inline const PacketScalar packet(Index row, Index col) const + { + return m_expression.template packet(row, col); + } + + template + inline void writePacket(Index row, Index col, const PacketScalar& x) + { + m_expression.const_cast_derived().template writePacket(row, col, x); + } + + template + inline const PacketScalar packet(Index index) const + { + return m_expression.template packet(index); + } + + template + inline void writePacket(Index index, const PacketScalar& x) + { + m_expression.const_cast_derived().template writePacket(index, x); + } + + EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } + + protected: + const ExpressionType& m_expression; + + private: + ForceAlignedAccess& operator=(const ForceAlignedAccess&); +}; + +/** \returns an expression of *this with forced aligned access + * \sa forceAlignedAccessIf(),class ForceAlignedAccess + */ +template +inline const ForceAlignedAccess +MatrixBase::forceAlignedAccess() const +{ + return ForceAlignedAccess(derived()); +} + +/** \returns an expression of *this with forced aligned access + * \sa forceAlignedAccessIf(), class ForceAlignedAccess + */ +template +inline ForceAlignedAccess +MatrixBase::forceAlignedAccess() +{ + return ForceAlignedAccess(derived()); +} + +/** \returns an expression of *this with forced aligned access if \a Enable is true. + * \sa forceAlignedAccess(), class ForceAlignedAccess + */ +template +template +inline typename internal::add_const_on_value_type,Derived&>::type>::type +MatrixBase::forceAlignedAccessIf() const +{ + return derived(); // FIXME This should not work but apparently is never used +} + +/** \returns an expression of *this with forced aligned access if \a Enable is true. + * \sa forceAlignedAccess(), class ForceAlignedAccess + */ +template +template +inline typename internal::conditional,Derived&>::type +MatrixBase::forceAlignedAccessIf() +{ + return derived(); // FIXME This should not work but apparently is never used +} + +} // end namespace Eigen + +#endif // EIGEN_FORCEALIGNEDACCESS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Fuzzy.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Fuzzy.h new file mode 100644 index 0000000000000000000000000000000000000000..3e403a09d92fc025661b427e5649c3334c7309c8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Fuzzy.h @@ -0,0 +1,155 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_FUZZY_H +#define EIGEN_FUZZY_H + +namespace Eigen { + +namespace internal +{ + +template::IsInteger> +struct isApprox_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) + { + typename internal::nested_eval::type nested(x); + typename internal::nested_eval::type otherNested(y); + return (nested - otherNested).cwiseAbs2().sum() <= prec * prec * numext::mini(nested.cwiseAbs2().sum(), otherNested.cwiseAbs2().sum()); + } +}; + +template +struct isApprox_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar&) + { + return x.matrix() == y.matrix(); + } +}; + +template::IsInteger> +struct isMuchSmallerThan_object_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const OtherDerived& y, const typename Derived::RealScalar& prec) + { + return x.cwiseAbs2().sum() <= numext::abs2(prec) * y.cwiseAbs2().sum(); + } +}; + +template +struct isMuchSmallerThan_object_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const OtherDerived&, const typename Derived::RealScalar&) + { + return x.matrix() == Derived::Zero(x.rows(), x.cols()).matrix(); + } +}; + +template::IsInteger> +struct isMuchSmallerThan_scalar_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const typename Derived::RealScalar& y, const typename Derived::RealScalar& prec) + { + return x.cwiseAbs2().sum() <= numext::abs2(prec * y); + } +}; + +template +struct isMuchSmallerThan_scalar_selector +{ + EIGEN_DEVICE_FUNC + static bool run(const Derived& x, const typename Derived::RealScalar&, const typename Derived::RealScalar&) + { + return x.matrix() == Derived::Zero(x.rows(), x.cols()).matrix(); + } +}; + +} // end namespace internal + + +/** \returns \c true if \c *this is approximately equal to \a other, within the precision + * determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. Two vectors \f$ v \f$ and \f$ w \f$ + * are considered to be approximately equal within precision \f$ p \f$ if + * \f[ \Vert v - w \Vert \leqslant p\,\min(\Vert v\Vert, \Vert w\Vert). \f] + * For matrices, the comparison is done using the Hilbert-Schmidt norm (aka Frobenius norm + * L2 norm). + * + * \note Because of the multiplicativeness of this comparison, one can't use this function + * to check whether \c *this is approximately equal to the zero matrix or vector. + * Indeed, \c isApprox(zero) returns false unless \c *this itself is exactly the zero matrix + * or vector. If you want to test whether \c *this is zero, use internal::isMuchSmallerThan(const + * RealScalar&, RealScalar) instead. + * + * \sa internal::isMuchSmallerThan(const RealScalar&, RealScalar) const + */ +template +template +bool DenseBase::isApprox( + const DenseBase& other, + const RealScalar& prec +) const +{ + return internal::isApprox_selector::run(derived(), other.derived(), prec); +} + +/** \returns \c true if the norm of \c *this is much smaller than \a other, + * within the precision determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is + * considered to be much smaller than \f$ x \f$ within precision \f$ p \f$ if + * \f[ \Vert v \Vert \leqslant p\,\vert x\vert. \f] + * + * For matrices, the comparison is done using the Hilbert-Schmidt norm. For this reason, + * the value of the reference scalar \a other should come from the Hilbert-Schmidt norm + * of a reference matrix of same dimensions. + * + * \sa isApprox(), isMuchSmallerThan(const DenseBase&, RealScalar) const + */ +template +bool DenseBase::isMuchSmallerThan( + const typename NumTraits::Real& other, + const RealScalar& prec +) const +{ + return internal::isMuchSmallerThan_scalar_selector::run(derived(), other, prec); +} + +/** \returns \c true if the norm of \c *this is much smaller than the norm of \a other, + * within the precision determined by \a prec. + * + * \note The fuzzy compares are done multiplicatively. A vector \f$ v \f$ is + * considered to be much smaller than a vector \f$ w \f$ within precision \f$ p \f$ if + * \f[ \Vert v \Vert \leqslant p\,\Vert w\Vert. \f] + * For matrices, the comparison is done using the Hilbert-Schmidt norm. + * + * \sa isApprox(), isMuchSmallerThan(const RealScalar&, RealScalar) const + */ +template +template +bool DenseBase::isMuchSmallerThan( + const DenseBase& other, + const RealScalar& prec +) const +{ + return internal::isMuchSmallerThan_object_selector::run(derived(), other.derived(), prec); +} + +} // end namespace Eigen + +#endif // EIGEN_FUZZY_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GeneralProduct.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GeneralProduct.h new file mode 100644 index 0000000000000000000000000000000000000000..6f0cc80e940c67db21f7dd56058bae51e5d7b1b9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GeneralProduct.h @@ -0,0 +1,455 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2008-2011 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GENERAL_PRODUCT_H +#define EIGEN_GENERAL_PRODUCT_H + +namespace Eigen { + +enum { + Large = 2, + Small = 3 +}; + +namespace internal { + +template struct product_type_selector; + +template struct product_size_category +{ + enum { + #ifndef EIGEN_CUDA_ARCH + is_large = MaxSize == Dynamic || + Size >= EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD || + (Size==Dynamic && MaxSize>=EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD), + #else + is_large = 0, + #endif + value = is_large ? Large + : Size == 1 ? 1 + : Small + }; +}; + +template struct product_type +{ + typedef typename remove_all::type _Lhs; + typedef typename remove_all::type _Rhs; + enum { + MaxRows = traits<_Lhs>::MaxRowsAtCompileTime, + Rows = traits<_Lhs>::RowsAtCompileTime, + MaxCols = traits<_Rhs>::MaxColsAtCompileTime, + Cols = traits<_Rhs>::ColsAtCompileTime, + MaxDepth = EIGEN_SIZE_MIN_PREFER_FIXED(traits<_Lhs>::MaxColsAtCompileTime, + traits<_Rhs>::MaxRowsAtCompileTime), + Depth = EIGEN_SIZE_MIN_PREFER_FIXED(traits<_Lhs>::ColsAtCompileTime, + traits<_Rhs>::RowsAtCompileTime) + }; + + // the splitting into different lines of code here, introducing the _select enums and the typedef below, + // is to work around an internal compiler error with gcc 4.1 and 4.2. +private: + enum { + rows_select = product_size_category::value, + cols_select = product_size_category::value, + depth_select = product_size_category::value + }; + typedef product_type_selector selector; + +public: + enum { + value = selector::ret, + ret = selector::ret + }; +#ifdef EIGEN_DEBUG_PRODUCT + static void debug() + { + EIGEN_DEBUG_VAR(Rows); + EIGEN_DEBUG_VAR(Cols); + EIGEN_DEBUG_VAR(Depth); + EIGEN_DEBUG_VAR(rows_select); + EIGEN_DEBUG_VAR(cols_select); + EIGEN_DEBUG_VAR(depth_select); + EIGEN_DEBUG_VAR(value); + } +#endif +}; + +/* The following allows to select the kind of product at compile time + * based on the three dimensions of the product. + * This is a compile time mapping from {1,Small,Large}^3 -> {product types} */ +// FIXME I'm not sure the current mapping is the ideal one. +template struct product_type_selector { enum { ret = OuterProduct }; }; +template struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; +template struct product_type_selector<1, N, 1> { enum { ret = LazyCoeffBasedProductMode }; }; +template struct product_type_selector<1, 1, Depth> { enum { ret = InnerProduct }; }; +template<> struct product_type_selector<1, 1, 1> { enum { ret = InnerProduct }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector<1, Small,Small> { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = LazyCoeffBasedProductMode }; }; +template<> struct product_type_selector<1, Large,Small> { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector<1, Large,Large> { enum { ret = GemvProduct }; }; +template<> struct product_type_selector<1, Small,Large> { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = GemvProduct }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = GemmProduct }; }; +template<> struct product_type_selector { enum { ret = GemmProduct }; }; +template<> struct product_type_selector { enum { ret = GemmProduct }; }; +template<> struct product_type_selector { enum { ret = GemmProduct }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = CoeffBasedProductMode }; }; +template<> struct product_type_selector { enum { ret = GemmProduct }; }; + +} // end namespace internal + +/*********************************************************************** +* Implementation of Inner Vector Vector Product +***********************************************************************/ + +// FIXME : maybe the "inner product" could return a Scalar +// instead of a 1x1 matrix ?? +// Pro: more natural for the user +// Cons: this could be a problem if in a meta unrolled algorithm a matrix-matrix +// product ends up to a row-vector times col-vector product... To tackle this use +// case, we could have a specialization for Block with: operator=(Scalar x); + +/*********************************************************************** +* Implementation of Outer Vector Vector Product +***********************************************************************/ + +/*********************************************************************** +* Implementation of General Matrix Vector Product +***********************************************************************/ + +/* According to the shape/flags of the matrix we have to distinghish 3 different cases: + * 1 - the matrix is col-major, BLAS compatible and M is large => call fast BLAS-like colmajor routine + * 2 - the matrix is row-major, BLAS compatible and N is large => call fast BLAS-like rowmajor routine + * 3 - all other cases are handled using a simple loop along the outer-storage direction. + * Therefore we need a lower level meta selector. + * Furthermore, if the matrix is the rhs, then the product has to be transposed. + */ +namespace internal { + +template +struct gemv_dense_selector; + +} // end namespace internal + +namespace internal { + +template struct gemv_static_vector_if; + +template +struct gemv_static_vector_if +{ + EIGEN_STRONG_INLINE Scalar* data() { eigen_internal_assert(false && "should never be called"); return 0; } +}; + +template +struct gemv_static_vector_if +{ + EIGEN_STRONG_INLINE Scalar* data() { return 0; } +}; + +template +struct gemv_static_vector_if +{ + enum { + ForceAlignment = internal::packet_traits::Vectorizable, + PacketSize = internal::packet_traits::size + }; + #if EIGEN_MAX_STATIC_ALIGN_BYTES!=0 + internal::plain_array m_data; + EIGEN_STRONG_INLINE Scalar* data() { return m_data.array; } + #else + // Some architectures cannot align on the stack, + // => let's manually enforce alignment by allocating more data and return the address of the first aligned element. + internal::plain_array m_data; + EIGEN_STRONG_INLINE Scalar* data() { + return ForceAlignment + ? reinterpret_cast((internal::UIntPtr(m_data.array) & ~(std::size_t(EIGEN_MAX_ALIGN_BYTES-1))) + EIGEN_MAX_ALIGN_BYTES) + : m_data.array; + } + #endif +}; + +// The vector is on the left => transposition +template +struct gemv_dense_selector +{ + template + static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) + { + Transpose destT(dest); + enum { OtherStorageOrder = StorageOrder == RowMajor ? ColMajor : RowMajor }; + gemv_dense_selector + ::run(rhs.transpose(), lhs.transpose(), destT, alpha); + } +}; + +template<> struct gemv_dense_selector +{ + template + static inline void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) + { + typedef typename Lhs::Scalar LhsScalar; + typedef typename Rhs::Scalar RhsScalar; + typedef typename Dest::Scalar ResScalar; + typedef typename Dest::RealScalar RealScalar; + + typedef internal::blas_traits LhsBlasTraits; + typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; + typedef internal::blas_traits RhsBlasTraits; + typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; + + typedef Map, EIGEN_PLAIN_ENUM_MIN(AlignedMax,internal::packet_traits::size)> MappedDest; + + ActualLhsType actualLhs = LhsBlasTraits::extract(lhs); + ActualRhsType actualRhs = RhsBlasTraits::extract(rhs); + + ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(lhs) + * RhsBlasTraits::extractScalarFactor(rhs); + + // make sure Dest is a compile-time vector type (bug 1166) + typedef typename conditional::type ActualDest; + + enum { + // FIXME find a way to allow an inner stride on the result if packet_traits::size==1 + // on, the other hand it is good for the cache to pack the vector anyways... + EvalToDestAtCompileTime = (ActualDest::InnerStrideAtCompileTime==1), + ComplexByReal = (NumTraits::IsComplex) && (!NumTraits::IsComplex), + MightCannotUseDest = (!EvalToDestAtCompileTime) || ComplexByReal + }; + + typedef const_blas_data_mapper LhsMapper; + typedef const_blas_data_mapper RhsMapper; + RhsScalar compatibleAlpha = get_factor::run(actualAlpha); + + if(!MightCannotUseDest) + { + // shortcut if we are sure to be able to use dest directly, + // this ease the compiler to generate cleaner and more optimzized code for most common cases + general_matrix_vector_product + ::run( + actualLhs.rows(), actualLhs.cols(), + LhsMapper(actualLhs.data(), actualLhs.outerStride()), + RhsMapper(actualRhs.data(), actualRhs.innerStride()), + dest.data(), 1, + compatibleAlpha); + } + else + { + gemv_static_vector_if static_dest; + + const bool alphaIsCompatible = (!ComplexByReal) || (numext::imag(actualAlpha)==RealScalar(0)); + const bool evalToDest = EvalToDestAtCompileTime && alphaIsCompatible; + + ei_declare_aligned_stack_constructed_variable(ResScalar,actualDestPtr,dest.size(), + evalToDest ? dest.data() : static_dest.data()); + + if(!evalToDest) + { + #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN + Index size = dest.size(); + EIGEN_DENSE_STORAGE_CTOR_PLUGIN + #endif + if(!alphaIsCompatible) + { + MappedDest(actualDestPtr, dest.size()).setZero(); + compatibleAlpha = RhsScalar(1); + } + else + MappedDest(actualDestPtr, dest.size()) = dest; + } + + general_matrix_vector_product + ::run( + actualLhs.rows(), actualLhs.cols(), + LhsMapper(actualLhs.data(), actualLhs.outerStride()), + RhsMapper(actualRhs.data(), actualRhs.innerStride()), + actualDestPtr, 1, + compatibleAlpha); + + if (!evalToDest) + { + if(!alphaIsCompatible) + dest.matrix() += actualAlpha * MappedDest(actualDestPtr, dest.size()); + else + dest = MappedDest(actualDestPtr, dest.size()); + } + } + } +}; + +template<> struct gemv_dense_selector +{ + template + static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) + { + typedef typename Lhs::Scalar LhsScalar; + typedef typename Rhs::Scalar RhsScalar; + typedef typename Dest::Scalar ResScalar; + + typedef internal::blas_traits LhsBlasTraits; + typedef typename LhsBlasTraits::DirectLinearAccessType ActualLhsType; + typedef internal::blas_traits RhsBlasTraits; + typedef typename RhsBlasTraits::DirectLinearAccessType ActualRhsType; + typedef typename internal::remove_all::type ActualRhsTypeCleaned; + + typename add_const::type actualLhs = LhsBlasTraits::extract(lhs); + typename add_const::type actualRhs = RhsBlasTraits::extract(rhs); + + ResScalar actualAlpha = alpha * LhsBlasTraits::extractScalarFactor(lhs) + * RhsBlasTraits::extractScalarFactor(rhs); + + enum { + // FIXME find a way to allow an inner stride on the result if packet_traits::size==1 + // on, the other hand it is good for the cache to pack the vector anyways... + DirectlyUseRhs = ActualRhsTypeCleaned::InnerStrideAtCompileTime==1 + }; + + gemv_static_vector_if static_rhs; + + ei_declare_aligned_stack_constructed_variable(RhsScalar,actualRhsPtr,actualRhs.size(), + DirectlyUseRhs ? const_cast(actualRhs.data()) : static_rhs.data()); + + if(!DirectlyUseRhs) + { + #ifdef EIGEN_DENSE_STORAGE_CTOR_PLUGIN + Index size = actualRhs.size(); + EIGEN_DENSE_STORAGE_CTOR_PLUGIN + #endif + Map(actualRhsPtr, actualRhs.size()) = actualRhs; + } + + typedef const_blas_data_mapper LhsMapper; + typedef const_blas_data_mapper RhsMapper; + general_matrix_vector_product + ::run( + actualLhs.rows(), actualLhs.cols(), + LhsMapper(actualLhs.data(), actualLhs.outerStride()), + RhsMapper(actualRhsPtr, 1), + dest.data(), dest.col(0).innerStride(), //NOTE if dest is not a vector at compile-time, then dest.innerStride() might be wrong. (bug 1166) + actualAlpha); + } +}; + +template<> struct gemv_dense_selector +{ + template + static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) + { + EIGEN_STATIC_ASSERT((!nested_eval::Evaluate),EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); + // TODO if rhs is large enough it might be beneficial to make sure that dest is sequentially stored in memory, otherwise use a temp + typename nested_eval::type actual_rhs(rhs); + const Index size = rhs.rows(); + for(Index k=0; k struct gemv_dense_selector +{ + template + static void run(const Lhs &lhs, const Rhs &rhs, Dest& dest, const typename Dest::Scalar& alpha) + { + EIGEN_STATIC_ASSERT((!nested_eval::Evaluate),EIGEN_INTERNAL_COMPILATION_ERROR_OR_YOU_MADE_A_PROGRAMMING_MISTAKE); + typename nested_eval::type actual_rhs(rhs); + const Index rows = dest.rows(); + for(Index i=0; i +template +inline const Product +MatrixBase::operator*(const MatrixBase &other) const +{ + // A note regarding the function declaration: In MSVC, this function will sometimes + // not be inlined since DenseStorage is an unwindable object for dynamic + // matrices and product types are holding a member to store the result. + // Thus it does not help tagging this function with EIGEN_STRONG_INLINE. + enum { + ProductIsValid = Derived::ColsAtCompileTime==Dynamic + || OtherDerived::RowsAtCompileTime==Dynamic + || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime), + AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime, + SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived) + }; + // note to the lost user: + // * for a dot product use: v1.dot(v2) + // * for a coeff-wise product use: v1.cwiseProduct(v2) + EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes), + INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) + EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors), + INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) + EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT) +#ifdef EIGEN_DEBUG_PRODUCT + internal::product_type::debug(); +#endif + + return Product(derived(), other.derived()); +} + +/** \returns an expression of the matrix product of \c *this and \a other without implicit evaluation. + * + * The returned product will behave like any other expressions: the coefficients of the product will be + * computed once at a time as requested. This might be useful in some extremely rare cases when only + * a small and no coherent fraction of the result's coefficients have to be computed. + * + * \warning This version of the matrix product can be much much slower. So use it only if you know + * what you are doing and that you measured a true speed improvement. + * + * \sa operator*(const MatrixBase&) + */ +template +template +const Product +MatrixBase::lazyProduct(const MatrixBase &other) const +{ + enum { + ProductIsValid = Derived::ColsAtCompileTime==Dynamic + || OtherDerived::RowsAtCompileTime==Dynamic + || int(Derived::ColsAtCompileTime)==int(OtherDerived::RowsAtCompileTime), + AreVectors = Derived::IsVectorAtCompileTime && OtherDerived::IsVectorAtCompileTime, + SameSizes = EIGEN_PREDICATE_SAME_MATRIX_SIZE(Derived,OtherDerived) + }; + // note to the lost user: + // * for a dot product use: v1.dot(v2) + // * for a coeff-wise product use: v1.cwiseProduct(v2) + EIGEN_STATIC_ASSERT(ProductIsValid || !(AreVectors && SameSizes), + INVALID_VECTOR_VECTOR_PRODUCT__IF_YOU_WANTED_A_DOT_OR_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTIONS) + EIGEN_STATIC_ASSERT(ProductIsValid || !(SameSizes && !AreVectors), + INVALID_MATRIX_PRODUCT__IF_YOU_WANTED_A_COEFF_WISE_PRODUCT_YOU_MUST_USE_THE_EXPLICIT_FUNCTION) + EIGEN_STATIC_ASSERT(ProductIsValid || SameSizes, INVALID_MATRIX_PRODUCT) + + return Product(derived(), other.derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_PRODUCT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GenericPacketMath.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GenericPacketMath.h new file mode 100644 index 0000000000000000000000000000000000000000..029f8ac36fb8976d4d2bb6ec753f0fc03b4ab2c6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GenericPacketMath.h @@ -0,0 +1,593 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GENERIC_PACKET_MATH_H +#define EIGEN_GENERIC_PACKET_MATH_H + +namespace Eigen { + +namespace internal { + +/** \internal + * \file GenericPacketMath.h + * + * Default implementation for types not supported by the vectorization. + * In practice these functions are provided to make easier the writing + * of generic vectorized code. + */ + +#ifndef EIGEN_DEBUG_ALIGNED_LOAD +#define EIGEN_DEBUG_ALIGNED_LOAD +#endif + +#ifndef EIGEN_DEBUG_UNALIGNED_LOAD +#define EIGEN_DEBUG_UNALIGNED_LOAD +#endif + +#ifndef EIGEN_DEBUG_ALIGNED_STORE +#define EIGEN_DEBUG_ALIGNED_STORE +#endif + +#ifndef EIGEN_DEBUG_UNALIGNED_STORE +#define EIGEN_DEBUG_UNALIGNED_STORE +#endif + +struct default_packet_traits +{ + enum { + HasHalfPacket = 0, + + HasAdd = 1, + HasSub = 1, + HasMul = 1, + HasNegate = 1, + HasAbs = 1, + HasArg = 0, + HasAbs2 = 1, + HasMin = 1, + HasMax = 1, + HasConj = 1, + HasSetLinear = 1, + HasBlend = 0, + + HasDiv = 0, + HasSqrt = 0, + HasRsqrt = 0, + HasExp = 0, + HasLog = 0, + HasLog1p = 0, + HasLog10 = 0, + HasPow = 0, + + HasSin = 0, + HasCos = 0, + HasTan = 0, + HasASin = 0, + HasACos = 0, + HasATan = 0, + HasSinh = 0, + HasCosh = 0, + HasTanh = 0, + HasLGamma = 0, + HasDiGamma = 0, + HasZeta = 0, + HasPolygamma = 0, + HasErf = 0, + HasErfc = 0, + HasIGamma = 0, + HasIGammac = 0, + HasBetaInc = 0, + + HasRound = 0, + HasFloor = 0, + HasCeil = 0, + + HasSign = 0 + }; +}; + +template struct packet_traits : default_packet_traits +{ + typedef T type; + typedef T half; + enum { + Vectorizable = 0, + size = 1, + AlignedOnScalar = 0, + HasHalfPacket = 0 + }; + enum { + HasAdd = 0, + HasSub = 0, + HasMul = 0, + HasNegate = 0, + HasAbs = 0, + HasAbs2 = 0, + HasMin = 0, + HasMax = 0, + HasConj = 0, + HasSetLinear = 0 + }; +}; + +template struct packet_traits : packet_traits { }; + +template struct type_casting_traits { + enum { + VectorizedCast = 0, + SrcCoeffRatio = 1, + TgtCoeffRatio = 1 + }; +}; + + +/** \internal \returns static_cast(a) (coeff-wise) */ +template +EIGEN_DEVICE_FUNC inline TgtPacket +pcast(const SrcPacket& a) { + return static_cast(a); +} +template +EIGEN_DEVICE_FUNC inline TgtPacket +pcast(const SrcPacket& a, const SrcPacket& /*b*/) { + return static_cast(a); +} + +template +EIGEN_DEVICE_FUNC inline TgtPacket +pcast(const SrcPacket& a, const SrcPacket& /*b*/, const SrcPacket& /*c*/, const SrcPacket& /*d*/) { + return static_cast(a); +} + +/** \internal \returns a + b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +padd(const Packet& a, + const Packet& b) { return a+b; } + +/** \internal \returns a - b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +psub(const Packet& a, + const Packet& b) { return a-b; } + +/** \internal \returns -a (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pnegate(const Packet& a) { return -a; } + +/** \internal \returns conj(a) (coeff-wise) */ + +template EIGEN_DEVICE_FUNC inline Packet +pconj(const Packet& a) { return numext::conj(a); } + +/** \internal \returns a * b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pmul(const Packet& a, + const Packet& b) { return a*b; } + +/** \internal \returns a / b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pdiv(const Packet& a, + const Packet& b) { return a/b; } + +/** \internal \returns the min of \a a and \a b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pmin(const Packet& a, + const Packet& b) { return numext::mini(a, b); } + +/** \internal \returns the max of \a a and \a b (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pmax(const Packet& a, + const Packet& b) { return numext::maxi(a, b); } + +/** \internal \returns the absolute value of \a a */ +template EIGEN_DEVICE_FUNC inline Packet +pabs(const Packet& a) { using std::abs; return abs(a); } + +/** \internal \returns the phase angle of \a a */ +template EIGEN_DEVICE_FUNC inline Packet +parg(const Packet& a) { using numext::arg; return arg(a); } + +/** \internal \returns the bitwise and of \a a and \a b */ +template EIGEN_DEVICE_FUNC inline Packet +pand(const Packet& a, const Packet& b) { return a & b; } + +/** \internal \returns the bitwise or of \a a and \a b */ +template EIGEN_DEVICE_FUNC inline Packet +por(const Packet& a, const Packet& b) { return a | b; } + +/** \internal \returns the bitwise xor of \a a and \a b */ +template EIGEN_DEVICE_FUNC inline Packet +pxor(const Packet& a, const Packet& b) { return a ^ b; } + +/** \internal \returns the bitwise andnot of \a a and \a b */ +template EIGEN_DEVICE_FUNC inline Packet +pandnot(const Packet& a, const Packet& b) { return a & (!b); } + +/** \internal \returns a packet version of \a *from, from must be 16 bytes aligned */ +template EIGEN_DEVICE_FUNC inline Packet +pload(const typename unpacket_traits::type* from) { return *from; } + +/** \internal \returns a packet version of \a *from, (un-aligned load) */ +template EIGEN_DEVICE_FUNC inline Packet +ploadu(const typename unpacket_traits::type* from) { return *from; } + +/** \internal \returns a packet with constant coefficients \a a, e.g.: (a,a,a,a) */ +template EIGEN_DEVICE_FUNC inline Packet +pset1(const typename unpacket_traits::type& a) { return a; } + +/** \internal \returns a packet with constant coefficients \a a[0], e.g.: (a[0],a[0],a[0],a[0]) */ +template EIGEN_DEVICE_FUNC inline Packet +pload1(const typename unpacket_traits::type *a) { return pset1(*a); } + +/** \internal \returns a packet with elements of \a *from duplicated. + * For instance, for a packet of 8 elements, 4 scalars will be read from \a *from and + * duplicated to form: {from[0],from[0],from[1],from[1],from[2],from[2],from[3],from[3]} + * Currently, this function is only used for scalar * complex products. + */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet +ploaddup(const typename unpacket_traits::type* from) { return *from; } + +/** \internal \returns a packet with elements of \a *from quadrupled. + * For instance, for a packet of 8 elements, 2 scalars will be read from \a *from and + * replicated to form: {from[0],from[0],from[0],from[0],from[1],from[1],from[1],from[1]} + * Currently, this function is only used in matrix products. + * For packet-size smaller or equal to 4, this function is equivalent to pload1 + */ +template EIGEN_DEVICE_FUNC inline Packet +ploadquad(const typename unpacket_traits::type* from) +{ return pload1(from); } + +/** \internal equivalent to + * \code + * a0 = pload1(a+0); + * a1 = pload1(a+1); + * a2 = pload1(a+2); + * a3 = pload1(a+3); + * \endcode + * \sa pset1, pload1, ploaddup, pbroadcast2 + */ +template EIGEN_DEVICE_FUNC +inline void pbroadcast4(const typename unpacket_traits::type *a, + Packet& a0, Packet& a1, Packet& a2, Packet& a3) +{ + a0 = pload1(a+0); + a1 = pload1(a+1); + a2 = pload1(a+2); + a3 = pload1(a+3); +} + +/** \internal equivalent to + * \code + * a0 = pload1(a+0); + * a1 = pload1(a+1); + * \endcode + * \sa pset1, pload1, ploaddup, pbroadcast4 + */ +template EIGEN_DEVICE_FUNC +inline void pbroadcast2(const typename unpacket_traits::type *a, + Packet& a0, Packet& a1) +{ + a0 = pload1(a+0); + a1 = pload1(a+1); +} + +/** \internal \brief Returns a packet with coefficients (a,a+1,...,a+packet_size-1). */ +template EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet +plset(const typename unpacket_traits::type& a) { return a; } + +/** \internal copy the packet \a from to \a *to, \a to must be 16 bytes aligned */ +template EIGEN_DEVICE_FUNC inline void pstore(Scalar* to, const Packet& from) +{ (*to) = from; } + +/** \internal copy the packet \a from to \a *to, (un-aligned store) */ +template EIGEN_DEVICE_FUNC inline void pstoreu(Scalar* to, const Packet& from) +{ (*to) = from; } + + template EIGEN_DEVICE_FUNC inline Packet pgather(const Scalar* from, Index /*stride*/) + { return ploadu(from); } + + template EIGEN_DEVICE_FUNC inline void pscatter(Scalar* to, const Packet& from, Index /*stride*/) + { pstore(to, from); } + +/** \internal tries to do cache prefetching of \a addr */ +template EIGEN_DEVICE_FUNC inline void prefetch(const Scalar* addr) +{ +#ifdef __CUDA_ARCH__ +#if defined(__LP64__) + // 64-bit pointer operand constraint for inlined asm + asm(" prefetch.L1 [ %1 ];" : "=l"(addr) : "l"(addr)); +#else + // 32-bit pointer operand constraint for inlined asm + asm(" prefetch.L1 [ %1 ];" : "=r"(addr) : "r"(addr)); +#endif +#elif (!EIGEN_COMP_MSVC) && (EIGEN_COMP_GNUC || EIGEN_COMP_CLANG || EIGEN_COMP_ICC) + __builtin_prefetch(addr); +#endif +} + +/** \internal \returns the first element of a packet */ +template EIGEN_DEVICE_FUNC inline typename unpacket_traits::type pfirst(const Packet& a) +{ return a; } + +/** \internal \returns a packet where the element i contains the sum of the packet of \a vec[i] */ +template EIGEN_DEVICE_FUNC inline Packet +preduxp(const Packet* vecs) { return vecs[0]; } + +/** \internal \returns the sum of the elements of \a a*/ +template EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux(const Packet& a) +{ return a; } + +/** \internal \returns the sum of the elements of \a a by block of 4 elements. + * For a packet {a0, a1, a2, a3, a4, a5, a6, a7}, it returns a half packet {a0+a4, a1+a5, a2+a6, a3+a7} + * For packet-size smaller or equal to 4, this boils down to a noop. + */ +template EIGEN_DEVICE_FUNC inline +typename conditional<(unpacket_traits::size%8)==0,typename unpacket_traits::half,Packet>::type +predux_downto4(const Packet& a) +{ return a; } + +/** \internal \returns the product of the elements of \a a*/ +template EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_mul(const Packet& a) +{ return a; } + +/** \internal \returns the min of the elements of \a a*/ +template EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_min(const Packet& a) +{ return a; } + +/** \internal \returns the max of the elements of \a a*/ +template EIGEN_DEVICE_FUNC inline typename unpacket_traits::type predux_max(const Packet& a) +{ return a; } + +/** \internal \returns the reversed elements of \a a*/ +template EIGEN_DEVICE_FUNC inline Packet preverse(const Packet& a) +{ return a; } + +/** \internal \returns \a a with real and imaginary part flipped (for complex type only) */ +template EIGEN_DEVICE_FUNC inline Packet pcplxflip(const Packet& a) +{ + // FIXME: uncomment the following in case we drop the internal imag and real functions. +// using std::imag; +// using std::real; + return Packet(imag(a),real(a)); +} + +/************************** +* Special math functions +***************************/ + +/** \internal \returns the sine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet psin(const Packet& a) { using std::sin; return sin(a); } + +/** \internal \returns the cosine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pcos(const Packet& a) { using std::cos; return cos(a); } + +/** \internal \returns the tan of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet ptan(const Packet& a) { using std::tan; return tan(a); } + +/** \internal \returns the arc sine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pasin(const Packet& a) { using std::asin; return asin(a); } + +/** \internal \returns the arc cosine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pacos(const Packet& a) { using std::acos; return acos(a); } + +/** \internal \returns the arc tangent of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet patan(const Packet& a) { using std::atan; return atan(a); } + +/** \internal \returns the hyperbolic sine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet psinh(const Packet& a) { using std::sinh; return sinh(a); } + +/** \internal \returns the hyperbolic cosine of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pcosh(const Packet& a) { using std::cosh; return cosh(a); } + +/** \internal \returns the hyperbolic tan of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet ptanh(const Packet& a) { using std::tanh; return tanh(a); } + +/** \internal \returns the exp of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pexp(const Packet& a) { using std::exp; return exp(a); } + +/** \internal \returns the log of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet plog(const Packet& a) { using std::log; return log(a); } + +/** \internal \returns the log1p of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet plog1p(const Packet& a) { return numext::log1p(a); } + +/** \internal \returns the log10 of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet plog10(const Packet& a) { using std::log10; return log10(a); } + +/** \internal \returns the square-root of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet psqrt(const Packet& a) { using std::sqrt; return sqrt(a); } + +/** \internal \returns the reciprocal square-root of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet prsqrt(const Packet& a) { + return pdiv(pset1(1), psqrt(a)); +} + +/** \internal \returns the rounded value of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pround(const Packet& a) { using numext::round; return round(a); } + +/** \internal \returns the floor of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pfloor(const Packet& a) { using numext::floor; return floor(a); } + +/** \internal \returns the ceil of \a a (coeff-wise) */ +template EIGEN_DECLARE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS +Packet pceil(const Packet& a) { using numext::ceil; return ceil(a); } + +/*************************************************************************** +* The following functions might not have to be overwritten for vectorized types +***************************************************************************/ + +/** \internal copy a packet with constant coeficient \a a (e.g., [a,a,a,a]) to \a *to. \a to must be 16 bytes aligned */ +// NOTE: this function must really be templated on the packet type (think about different packet types for the same scalar type) +template +inline void pstore1(typename unpacket_traits::type* to, const typename unpacket_traits::type& a) +{ + pstore(to, pset1(a)); +} + +/** \internal \returns a * b + c (coeff-wise) */ +template EIGEN_DEVICE_FUNC inline Packet +pmadd(const Packet& a, + const Packet& b, + const Packet& c) +{ return padd(pmul(a, b),c); } + +/** \internal \returns a packet version of \a *from. + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt(const typename unpacket_traits::type* from) +{ + if(Alignment >= unpacket_traits::alignment) + return pload(from); + else + return ploadu(from); +} + +/** \internal copy the packet \a from to \a *to. + * The pointer \a from must be aligned on a \a Alignment bytes boundary. */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE void pstoret(Scalar* to, const Packet& from) +{ + if(Alignment >= unpacket_traits::alignment) + pstore(to, from); + else + pstoreu(to, from); +} + +/** \internal \returns a packet version of \a *from. + * Unlike ploadt, ploadt_ro takes advantage of the read-only memory path on the + * hardware if available to speedup the loading of data that won't be modified + * by the current computation. + */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE Packet ploadt_ro(const typename unpacket_traits::type* from) +{ + return ploadt(from); +} + +/** \internal default implementation of palign() allowing partial specialization */ +template +struct palign_impl +{ + // by default data are aligned, so there is nothing to be done :) + static inline void run(PacketType&, const PacketType&) {} +}; + +/** \internal update \a first using the concatenation of the packet_size minus \a Offset last elements + * of \a first and \a Offset first elements of \a second. + * + * This function is currently only used to optimize matrix-vector products on unligned matrices. + * It takes 2 packets that represent a contiguous memory array, and returns a packet starting + * at the position \a Offset. For instance, for packets of 4 elements, we have: + * Input: + * - first = {f0,f1,f2,f3} + * - second = {s0,s1,s2,s3} + * Output: + * - if Offset==0 then {f0,f1,f2,f3} + * - if Offset==1 then {f1,f2,f3,s0} + * - if Offset==2 then {f2,f3,s0,s1} + * - if Offset==3 then {f3,s0,s1,s3} + */ +template +inline void palign(PacketType& first, const PacketType& second) +{ + palign_impl::run(first,second); +} + +/*************************************************************************** +* Fast complex products (GCC generates a function call which is very slow) +***************************************************************************/ + +// Eigen+CUDA does not support complexes. +#ifndef __CUDACC__ + +template<> inline std::complex pmul(const std::complex& a, const std::complex& b) +{ return std::complex(real(a)*real(b) - imag(a)*imag(b), imag(a)*real(b) + real(a)*imag(b)); } + +template<> inline std::complex pmul(const std::complex& a, const std::complex& b) +{ return std::complex(real(a)*real(b) - imag(a)*imag(b), imag(a)*real(b) + real(a)*imag(b)); } + +#endif + + +/*************************************************************************** + * PacketBlock, that is a collection of N packets where the number of words + * in the packet is a multiple of N. +***************************************************************************/ +template ::size> struct PacketBlock { + Packet packet[N]; +}; + +template EIGEN_DEVICE_FUNC inline void +ptranspose(PacketBlock& /*kernel*/) { + // Nothing to do in the scalar case, i.e. a 1x1 matrix. +} + +/*************************************************************************** + * Selector, i.e. vector of N boolean values used to select (i.e. blend) + * words from 2 packets. +***************************************************************************/ +template struct Selector { + bool select[N]; +}; + +template EIGEN_DEVICE_FUNC inline Packet +pblend(const Selector::size>& ifPacket, const Packet& thenPacket, const Packet& elsePacket) { + return ifPacket.select[0] ? thenPacket : elsePacket; +} + +/** \internal \returns \a a with the first coefficient replaced by the scalar b */ +template EIGEN_DEVICE_FUNC inline Packet +pinsertfirst(const Packet& a, typename unpacket_traits::type b) +{ + // Default implementation based on pblend. + // It must be specialized for higher performance. + Selector::size> mask; + mask.select[0] = true; + // This for loop should be optimized away by the compiler. + for(Index i=1; i::size; ++i) + mask.select[i] = false; + return pblend(mask, pset1(b), a); +} + +/** \internal \returns \a a with the last coefficient replaced by the scalar b */ +template EIGEN_DEVICE_FUNC inline Packet +pinsertlast(const Packet& a, typename unpacket_traits::type b) +{ + // Default implementation based on pblend. + // It must be specialized for higher performance. + Selector::size> mask; + // This for loop should be optimized away by the compiler. + for(Index i=0; i::size-1; ++i) + mask.select[i] = false; + mask.select[unpacket_traits::size-1] = true; + return pblend(mask, pset1(b), a); +} + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_GENERIC_PACKET_MATH_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GlobalFunctions.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GlobalFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..769dc255c207c3e8ca3245571d5035167fc0ef0c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/GlobalFunctions.h @@ -0,0 +1,187 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010-2016 Gael Guennebaud +// Copyright (C) 2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_GLOBAL_FUNCTIONS_H +#define EIGEN_GLOBAL_FUNCTIONS_H + +#ifdef EIGEN_PARSED_BY_DOXYGEN + +#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME,FUNCTOR,DOC_OP,DOC_DETAILS) \ + /** \returns an expression of the coefficient-wise DOC_OP of \a x + + DOC_DETAILS + + \sa Math functions, class CwiseUnaryOp + */ \ + template \ + inline const Eigen::CwiseUnaryOp, const Derived> \ + NAME(const Eigen::ArrayBase& x); + +#else + +#define EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(NAME,FUNCTOR,DOC_OP,DOC_DETAILS) \ + template \ + inline const Eigen::CwiseUnaryOp, const Derived> \ + (NAME)(const Eigen::ArrayBase& x) { \ + return Eigen::CwiseUnaryOp, const Derived>(x.derived()); \ + } + +#endif // EIGEN_PARSED_BY_DOXYGEN + +#define EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(NAME,FUNCTOR) \ + \ + template \ + struct NAME##_retval > \ + { \ + typedef const Eigen::CwiseUnaryOp, const Derived> type; \ + }; \ + template \ + struct NAME##_impl > \ + { \ + static inline typename NAME##_retval >::type run(const Eigen::ArrayBase& x) \ + { \ + return typename NAME##_retval >::type(x.derived()); \ + } \ + }; + +namespace Eigen +{ + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(real,scalar_real_op,real part,\sa ArrayBase::real) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(imag,scalar_imag_op,imaginary part,\sa ArrayBase::imag) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(conj,scalar_conjugate_op,complex conjugate,\sa ArrayBase::conjugate) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(inverse,scalar_inverse_op,inverse,\sa ArrayBase::inverse) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sin,scalar_sin_op,sine,\sa ArrayBase::sin) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cos,scalar_cos_op,cosine,\sa ArrayBase::cos) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tan,scalar_tan_op,tangent,\sa ArrayBase::tan) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(atan,scalar_atan_op,arc-tangent,\sa ArrayBase::atan) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(asin,scalar_asin_op,arc-sine,\sa ArrayBase::asin) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(acos,scalar_acos_op,arc-consine,\sa ArrayBase::acos) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sinh,scalar_sinh_op,hyperbolic sine,\sa ArrayBase::sinh) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cosh,scalar_cosh_op,hyperbolic cosine,\sa ArrayBase::cosh) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(tanh,scalar_tanh_op,hyperbolic tangent,\sa ArrayBase::tanh) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(lgamma,scalar_lgamma_op,natural logarithm of the gamma function,\sa ArrayBase::lgamma) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(digamma,scalar_digamma_op,derivative of lgamma,\sa ArrayBase::digamma) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erf,scalar_erf_op,error function,\sa ArrayBase::erf) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(erfc,scalar_erfc_op,complement error function,\sa ArrayBase::erfc) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(exp,scalar_exp_op,exponential,\sa ArrayBase::exp) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log,scalar_log_op,natural logarithm,\sa Eigen::log10 DOXCOMMA ArrayBase::log) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log1p,scalar_log1p_op,natural logarithm of 1 plus the value,\sa ArrayBase::log1p) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(log10,scalar_log10_op,base 10 logarithm,\sa Eigen::log DOXCOMMA ArrayBase::log) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs,scalar_abs_op,absolute value,\sa ArrayBase::abs DOXCOMMA MatrixBase::cwiseAbs) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(abs2,scalar_abs2_op,squared absolute value,\sa ArrayBase::abs2 DOXCOMMA MatrixBase::cwiseAbs2) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(arg,scalar_arg_op,complex argument,\sa ArrayBase::arg) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sqrt,scalar_sqrt_op,square root,\sa ArrayBase::sqrt DOXCOMMA MatrixBase::cwiseSqrt) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(rsqrt,scalar_rsqrt_op,reciprocal square root,\sa ArrayBase::rsqrt) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(square,scalar_square_op,square (power 2),\sa Eigen::abs2 DOXCOMMA Eigen::pow DOXCOMMA ArrayBase::square) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(cube,scalar_cube_op,cube (power 3),\sa Eigen::pow DOXCOMMA ArrayBase::cube) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(round,scalar_round_op,nearest integer,\sa Eigen::floor DOXCOMMA Eigen::ceil DOXCOMMA ArrayBase::round) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(floor,scalar_floor_op,nearest integer not greater than the giben value,\sa Eigen::ceil DOXCOMMA ArrayBase::floor) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(ceil,scalar_ceil_op,nearest integer not less than the giben value,\sa Eigen::floor DOXCOMMA ArrayBase::ceil) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isnan,scalar_isnan_op,not-a-number test,\sa Eigen::isinf DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isnan) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isinf,scalar_isinf_op,infinite value test,\sa Eigen::isnan DOXCOMMA Eigen::isfinite DOXCOMMA ArrayBase::isinf) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(isfinite,scalar_isfinite_op,finite value test,\sa Eigen::isinf DOXCOMMA Eigen::isnan DOXCOMMA ArrayBase::isfinite) + EIGEN_ARRAY_DECLARE_GLOBAL_UNARY(sign,scalar_sign_op,sign (or 0),\sa ArrayBase::sign) + + /** \returns an expression of the coefficient-wise power of \a x to the given constant \a exponent. + * + * \tparam ScalarExponent is the scalar type of \a exponent. It must be compatible with the scalar type of the given expression (\c Derived::Scalar). + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ +#ifdef EIGEN_PARSED_BY_DOXYGEN + template + inline const CwiseBinaryOp,Derived,Constant > + pow(const Eigen::ArrayBase& x, const ScalarExponent& exponent); +#else + template + inline typename internal::enable_if< !(internal::is_same::value) && EIGEN_SCALAR_BINARY_SUPPORTED(pow,typename Derived::Scalar,ScalarExponent), + const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(Derived,ScalarExponent,pow) >::type + pow(const Eigen::ArrayBase& x, const ScalarExponent& exponent) { + return x.derived().pow(exponent); + } + + template + inline const EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(Derived,typename Derived::Scalar,pow) + pow(const Eigen::ArrayBase& x, const typename Derived::Scalar& exponent) { + return x.derived().pow(exponent); + } +#endif + + /** \returns an expression of the coefficient-wise power of \a x to the given array of \a exponents. + * + * This function computes the coefficient-wise power. + * + * Example: \include Cwise_array_power_array.cpp + * Output: \verbinclude Cwise_array_power_array.out + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ + template + inline const Eigen::CwiseBinaryOp, const Derived, const ExponentDerived> + pow(const Eigen::ArrayBase& x, const Eigen::ArrayBase& exponents) + { + return Eigen::CwiseBinaryOp, const Derived, const ExponentDerived>( + x.derived(), + exponents.derived() + ); + } + + /** \returns an expression of the coefficient-wise power of the scalar \a x to the given array of \a exponents. + * + * This function computes the coefficient-wise power between a scalar and an array of exponents. + * + * \tparam Scalar is the scalar type of \a x. It must be compatible with the scalar type of the given array expression (\c Derived::Scalar). + * + * Example: \include Cwise_scalar_power_array.cpp + * Output: \verbinclude Cwise_scalar_power_array.out + * + * \sa ArrayBase::pow() + * + * \relates ArrayBase + */ +#ifdef EIGEN_PARSED_BY_DOXYGEN + template + inline const CwiseBinaryOp,Constant,Derived> + pow(const Scalar& x,const Eigen::ArrayBase& x); +#else + template + inline typename internal::enable_if< !(internal::is_same::value) && EIGEN_SCALAR_BINARY_SUPPORTED(pow,Scalar,typename Derived::Scalar), + const EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(Scalar,Derived,pow) >::type + pow(const Scalar& x, const Eigen::ArrayBase& exponents) + { + return EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(Scalar,Derived,pow)( + typename internal::plain_constant_type::type(exponents.rows(), exponents.cols(), x), exponents.derived() ); + } + + template + inline const EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(typename Derived::Scalar,Derived,pow) + pow(const typename Derived::Scalar& x, const Eigen::ArrayBase& exponents) + { + return EIGEN_SCALAR_BINARYOP_EXPR_RETURN_TYPE(typename Derived::Scalar,Derived,pow)( + typename internal::plain_constant_type::type(exponents.rows(), exponents.cols(), x), exponents.derived() ); + } +#endif + + + namespace internal + { + EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(real,scalar_real_op) + EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(imag,scalar_imag_op) + EIGEN_ARRAY_DECLARE_GLOBAL_EIGEN_UNARY(abs2,scalar_abs2_op) + } +} + +// TODO: cleanly disable those functions that are not supported on Array (numext::real_ref, internal::random, internal::isApprox...) + +#endif // EIGEN_GLOBAL_FUNCTIONS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/IO.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/IO.h new file mode 100644 index 0000000000000000000000000000000000000000..da7fd6cce2e811bd8fe94e8a4a85b814377cbc6c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/IO.h @@ -0,0 +1,225 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_IO_H +#define EIGEN_IO_H + +namespace Eigen { + +enum { DontAlignCols = 1 }; +enum { StreamPrecision = -1, + FullPrecision = -2 }; + +namespace internal { +template +std::ostream & print_matrix(std::ostream & s, const Derived& _m, const IOFormat& fmt); +} + +/** \class IOFormat + * \ingroup Core_Module + * + * \brief Stores a set of parameters controlling the way matrices are printed + * + * List of available parameters: + * - \b precision number of digits for floating point values, or one of the special constants \c StreamPrecision and \c FullPrecision. + * The default is the special value \c StreamPrecision which means to use the + * stream's own precision setting, as set for instance using \c cout.precision(3). The other special value + * \c FullPrecision means that the number of digits will be computed to match the full precision of each floating-point + * type. + * - \b flags an OR-ed combination of flags, the default value is 0, the only currently available flag is \c DontAlignCols which + * allows to disable the alignment of columns, resulting in faster code. + * - \b coeffSeparator string printed between two coefficients of the same row + * - \b rowSeparator string printed between two rows + * - \b rowPrefix string printed at the beginning of each row + * - \b rowSuffix string printed at the end of each row + * - \b matPrefix string printed at the beginning of the matrix + * - \b matSuffix string printed at the end of the matrix + * + * Example: \include IOFormat.cpp + * Output: \verbinclude IOFormat.out + * + * \sa DenseBase::format(), class WithFormat + */ +struct IOFormat +{ + /** Default constructor, see class IOFormat for the meaning of the parameters */ + IOFormat(int _precision = StreamPrecision, int _flags = 0, + const std::string& _coeffSeparator = " ", + const std::string& _rowSeparator = "\n", const std::string& _rowPrefix="", const std::string& _rowSuffix="", + const std::string& _matPrefix="", const std::string& _matSuffix="") + : matPrefix(_matPrefix), matSuffix(_matSuffix), rowPrefix(_rowPrefix), rowSuffix(_rowSuffix), rowSeparator(_rowSeparator), + rowSpacer(""), coeffSeparator(_coeffSeparator), precision(_precision), flags(_flags) + { + // TODO check if rowPrefix, rowSuffix or rowSeparator contains a newline + // don't add rowSpacer if columns are not to be aligned + if((flags & DontAlignCols)) + return; + int i = int(matSuffix.length())-1; + while (i>=0 && matSuffix[i]!='\n') + { + rowSpacer += ' '; + i--; + } + } + std::string matPrefix, matSuffix; + std::string rowPrefix, rowSuffix, rowSeparator, rowSpacer; + std::string coeffSeparator; + int precision; + int flags; +}; + +/** \class WithFormat + * \ingroup Core_Module + * + * \brief Pseudo expression providing matrix output with given format + * + * \tparam ExpressionType the type of the object on which IO stream operations are performed + * + * This class represents an expression with stream operators controlled by a given IOFormat. + * It is the return type of DenseBase::format() + * and most of the time this is the only way it is used. + * + * See class IOFormat for some examples. + * + * \sa DenseBase::format(), class IOFormat + */ +template +class WithFormat +{ + public: + + WithFormat(const ExpressionType& matrix, const IOFormat& format) + : m_matrix(matrix), m_format(format) + {} + + friend std::ostream & operator << (std::ostream & s, const WithFormat& wf) + { + return internal::print_matrix(s, wf.m_matrix.eval(), wf.m_format); + } + + protected: + typename ExpressionType::Nested m_matrix; + IOFormat m_format; +}; + +namespace internal { + +// NOTE: This helper is kept for backward compatibility with previous code specializing +// this internal::significant_decimals_impl structure. In the future we should directly +// call digits10() which has been introduced in July 2016 in 3.3. +template +struct significant_decimals_impl +{ + static inline int run() + { + return NumTraits::digits10(); + } +}; + +/** \internal + * print the matrix \a _m to the output stream \a s using the output format \a fmt */ +template +std::ostream & print_matrix(std::ostream & s, const Derived& _m, const IOFormat& fmt) +{ + if(_m.size() == 0) + { + s << fmt.matPrefix << fmt.matSuffix; + return s; + } + + typename Derived::Nested m = _m; + typedef typename Derived::Scalar Scalar; + + Index width = 0; + + std::streamsize explicit_precision; + if(fmt.precision == StreamPrecision) + { + explicit_precision = 0; + } + else if(fmt.precision == FullPrecision) + { + if (NumTraits::IsInteger) + { + explicit_precision = 0; + } + else + { + explicit_precision = significant_decimals_impl::run(); + } + } + else + { + explicit_precision = fmt.precision; + } + + std::streamsize old_precision = 0; + if(explicit_precision) old_precision = s.precision(explicit_precision); + + bool align_cols = !(fmt.flags & DontAlignCols); + if(align_cols) + { + // compute the largest width + for(Index j = 0; j < m.cols(); ++j) + for(Index i = 0; i < m.rows(); ++i) + { + std::stringstream sstr; + sstr.copyfmt(s); + sstr << m.coeff(i,j); + width = std::max(width, Index(sstr.str().length())); + } + } + s << fmt.matPrefix; + for(Index i = 0; i < m.rows(); ++i) + { + if (i) + s << fmt.rowSpacer; + s << fmt.rowPrefix; + if(width) s.width(width); + s << m.coeff(i, 0); + for(Index j = 1; j < m.cols(); ++j) + { + s << fmt.coeffSeparator; + if (width) s.width(width); + s << m.coeff(i, j); + } + s << fmt.rowSuffix; + if( i < m.rows() - 1) + s << fmt.rowSeparator; + } + s << fmt.matSuffix; + if(explicit_precision) s.precision(old_precision); + return s; +} + +} // end namespace internal + +/** \relates DenseBase + * + * Outputs the matrix, to the given stream. + * + * If you wish to print the matrix with a format different than the default, use DenseBase::format(). + * + * It is also possible to change the default format by defining EIGEN_DEFAULT_IO_FORMAT before including Eigen headers. + * If not defined, this will automatically be defined to Eigen::IOFormat(), that is the Eigen::IOFormat with default parameters. + * + * \sa DenseBase::format() + */ +template +std::ostream & operator << +(std::ostream & s, + const DenseBase & m) +{ + return internal::print_matrix(s, m.eval(), EIGEN_DEFAULT_IO_FORMAT); +} + +} // end namespace Eigen + +#endif // EIGEN_IO_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Inverse.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Inverse.h new file mode 100644 index 0000000000000000000000000000000000000000..b76f0439d80f1ee66c3a14e1e6e582b9f2327b8c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Inverse.h @@ -0,0 +1,118 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_INVERSE_H +#define EIGEN_INVERSE_H + +namespace Eigen { + +template class InverseImpl; + +namespace internal { + +template +struct traits > + : traits +{ + typedef typename XprType::PlainObject PlainObject; + typedef traits BaseTraits; + enum { + Flags = BaseTraits::Flags & RowMajorBit + }; +}; + +} // end namespace internal + +/** \class Inverse + * + * \brief Expression of the inverse of another expression + * + * \tparam XprType the type of the expression we are taking the inverse + * + * This class represents an abstract expression of A.inverse() + * and most of the time this is the only way it is used. + * + */ +template +class Inverse : public InverseImpl::StorageKind> +{ +public: + typedef typename XprType::StorageIndex StorageIndex; + typedef typename XprType::PlainObject PlainObject; + typedef typename XprType::Scalar Scalar; + typedef typename internal::ref_selector::type XprTypeNested; + typedef typename internal::remove_all::type XprTypeNestedCleaned; + typedef typename internal::ref_selector::type Nested; + typedef typename internal::remove_all::type NestedExpression; + + explicit EIGEN_DEVICE_FUNC Inverse(const XprType &xpr) + : m_xpr(xpr) + {} + + EIGEN_DEVICE_FUNC Index rows() const { return m_xpr.rows(); } + EIGEN_DEVICE_FUNC Index cols() const { return m_xpr.cols(); } + + EIGEN_DEVICE_FUNC const XprTypeNestedCleaned& nestedExpression() const { return m_xpr; } + +protected: + XprTypeNested m_xpr; +}; + +// Generic API dispatcher +template +class InverseImpl + : public internal::generic_xpr_base >::type +{ +public: + typedef typename internal::generic_xpr_base >::type Base; + typedef typename XprType::Scalar Scalar; +private: + + Scalar coeff(Index row, Index col) const; + Scalar coeff(Index i) const; +}; + +namespace internal { + +/** \internal + * \brief Default evaluator for Inverse expression. + * + * This default evaluator for Inverse expression simply evaluate the inverse into a temporary + * by a call to internal::call_assignment_no_alias. + * Therefore, inverse implementers only have to specialize Assignment, ...> for + * there own nested expression. + * + * \sa class Inverse + */ +template +struct unary_evaluator > + : public evaluator::PlainObject> +{ + typedef Inverse InverseType; + typedef typename InverseType::PlainObject PlainObject; + typedef evaluator Base; + + enum { Flags = Base::Flags | EvalBeforeNestingBit }; + + unary_evaluator(const InverseType& inv_xpr) + : m_result(inv_xpr.rows(), inv_xpr.cols()) + { + ::new (static_cast(this)) Base(m_result); + internal::call_assignment_no_alias(m_result, inv_xpr); + } + +protected: + PlainObject m_result; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_INVERSE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Map.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Map.h new file mode 100644 index 0000000000000000000000000000000000000000..548bf9a2d558dbad6e83ce2c39618b08f225d766 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Map.h @@ -0,0 +1,171 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2007-2010 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MAP_H +#define EIGEN_MAP_H + +namespace Eigen { + +namespace internal { +template +struct traits > + : public traits +{ + typedef traits TraitsBase; + enum { + PlainObjectTypeInnerSize = ((traits::Flags&RowMajorBit)==RowMajorBit) + ? PlainObjectType::ColsAtCompileTime + : PlainObjectType::RowsAtCompileTime, + + InnerStrideAtCompileTime = StrideType::InnerStrideAtCompileTime == 0 + ? int(PlainObjectType::InnerStrideAtCompileTime) + : int(StrideType::InnerStrideAtCompileTime), + OuterStrideAtCompileTime = StrideType::OuterStrideAtCompileTime == 0 + ? (InnerStrideAtCompileTime==Dynamic || PlainObjectTypeInnerSize==Dynamic + ? Dynamic + : int(InnerStrideAtCompileTime) * int(PlainObjectTypeInnerSize)) + : int(StrideType::OuterStrideAtCompileTime), + Alignment = int(MapOptions)&int(AlignedMask), + Flags0 = TraitsBase::Flags & (~NestByRefBit), + Flags = is_lvalue::value ? int(Flags0) : (int(Flags0) & ~LvalueBit) + }; +private: + enum { Options }; // Expressions don't have Options +}; +} + +/** \class Map + * \ingroup Core_Module + * + * \brief A matrix or vector expression mapping an existing array of data. + * + * \tparam PlainObjectType the equivalent matrix type of the mapped data + * \tparam MapOptions specifies the pointer alignment in bytes. It can be: \c #Aligned128, , \c #Aligned64, \c #Aligned32, \c #Aligned16, \c #Aligned8 or \c #Unaligned. + * The default is \c #Unaligned. + * \tparam StrideType optionally specifies strides. By default, Map assumes the memory layout + * of an ordinary, contiguous array. This can be overridden by specifying strides. + * The type passed here must be a specialization of the Stride template, see examples below. + * + * This class represents a matrix or vector expression mapping an existing array of data. + * It can be used to let Eigen interface without any overhead with non-Eigen data structures, + * such as plain C arrays or structures from other libraries. By default, it assumes that the + * data is laid out contiguously in memory. You can however override this by explicitly specifying + * inner and outer strides. + * + * Here's an example of simply mapping a contiguous array as a \ref TopicStorageOrders "column-major" matrix: + * \include Map_simple.cpp + * Output: \verbinclude Map_simple.out + * + * If you need to map non-contiguous arrays, you can do so by specifying strides: + * + * Here's an example of mapping an array as a vector, specifying an inner stride, that is, the pointer + * increment between two consecutive coefficients. Here, we're specifying the inner stride as a compile-time + * fixed value. + * \include Map_inner_stride.cpp + * Output: \verbinclude Map_inner_stride.out + * + * Here's an example of mapping an array while specifying an outer stride. Here, since we're mapping + * as a column-major matrix, 'outer stride' means the pointer increment between two consecutive columns. + * Here, we're specifying the outer stride as a runtime parameter. Note that here \c OuterStride<> is + * a short version of \c OuterStride because the default template parameter of OuterStride + * is \c Dynamic + * \include Map_outer_stride.cpp + * Output: \verbinclude Map_outer_stride.out + * + * For more details and for an example of specifying both an inner and an outer stride, see class Stride. + * + * \b Tip: to change the array of data mapped by a Map object, you can use the C++ + * placement new syntax: + * + * Example: \include Map_placement_new.cpp + * Output: \verbinclude Map_placement_new.out + * + * This class is the return type of PlainObjectBase::Map() but can also be used directly. + * + * \sa PlainObjectBase::Map(), \ref TopicStorageOrders + */ +template class Map + : public MapBase > +{ + public: + + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Map) + + typedef typename Base::PointerType PointerType; + typedef PointerType PointerArgType; + EIGEN_DEVICE_FUNC + inline PointerType cast_to_pointer_type(PointerArgType ptr) { return ptr; } + + EIGEN_DEVICE_FUNC + inline Index innerStride() const + { + return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; + } + + EIGEN_DEVICE_FUNC + inline Index outerStride() const + { + return int(StrideType::OuterStrideAtCompileTime) != 0 ? m_stride.outer() + : int(internal::traits::OuterStrideAtCompileTime) != Dynamic ? Index(internal::traits::OuterStrideAtCompileTime) + : IsVectorAtCompileTime ? (this->size() * innerStride()) + : (int(Flags)&RowMajorBit) ? (this->cols() * innerStride()) + : (this->rows() * innerStride()); + } + + /** Constructor in the fixed-size case. + * + * \param dataPtr pointer to the array to map + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC + explicit inline Map(PointerArgType dataPtr, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr)), m_stride(stride) + { + PlainObjectType::Base::_check_template_params(); + } + + /** Constructor in the dynamic-size vector case. + * + * \param dataPtr pointer to the array to map + * \param size the size of the vector expression + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC + inline Map(PointerArgType dataPtr, Index size, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr), size), m_stride(stride) + { + PlainObjectType::Base::_check_template_params(); + } + + /** Constructor in the dynamic-size matrix case. + * + * \param dataPtr pointer to the array to map + * \param rows the number of rows of the matrix expression + * \param cols the number of columns of the matrix expression + * \param stride optional Stride object, passing the strides. + */ + EIGEN_DEVICE_FUNC + inline Map(PointerArgType dataPtr, Index rows, Index cols, const StrideType& stride = StrideType()) + : Base(cast_to_pointer_type(dataPtr), rows, cols), m_stride(stride) + { + PlainObjectType::Base::_check_template_params(); + } + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Map) + + protected: + StrideType m_stride; +}; + + +} // end namespace Eigen + +#endif // EIGEN_MAP_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MapBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MapBase.h new file mode 100644 index 0000000000000000000000000000000000000000..668922ffccb063e2de81c09cdf8524b635a36662 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MapBase.h @@ -0,0 +1,303 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2007-2010 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MAPBASE_H +#define EIGEN_MAPBASE_H + +#define EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) \ + EIGEN_STATIC_ASSERT((int(internal::evaluator::Flags) & LinearAccessBit) || Derived::IsVectorAtCompileTime, \ + YOU_ARE_TRYING_TO_USE_AN_INDEX_BASED_ACCESSOR_ON_AN_EXPRESSION_THAT_DOES_NOT_SUPPORT_THAT) + +namespace Eigen { + +/** \ingroup Core_Module + * + * \brief Base class for dense Map and Block expression with direct access + * + * This base class provides the const low-level accessors (e.g. coeff, coeffRef) of dense + * Map and Block objects with direct access. + * Typical users do not have to directly deal with this class. + * + * This class can be extended by through the macro plugin \c EIGEN_MAPBASE_PLUGIN. + * See \link TopicCustomizing_Plugins customizing Eigen \endlink for details. + * + * The \c Derived class has to provide the following two methods describing the memory layout: + * \code Index innerStride() const; \endcode + * \code Index outerStride() const; \endcode + * + * \sa class Map, class Block + */ +template class MapBase + : public internal::dense_xpr_base::type +{ + public: + + typedef typename internal::dense_xpr_base::type Base; + enum { + RowsAtCompileTime = internal::traits::RowsAtCompileTime, + ColsAtCompileTime = internal::traits::ColsAtCompileTime, + InnerStrideAtCompileTime = internal::traits::InnerStrideAtCompileTime, + SizeAtCompileTime = Base::SizeAtCompileTime + }; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + typedef typename internal::conditional< + bool(internal::is_lvalue::value), + Scalar *, + const Scalar *>::type + PointerType; + + using Base::derived; +// using Base::RowsAtCompileTime; +// using Base::ColsAtCompileTime; +// using Base::SizeAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::IsVectorAtCompileTime; + using Base::Flags; + using Base::IsRowMajor; + + using Base::rows; + using Base::cols; + using Base::size; + using Base::coeff; + using Base::coeffRef; + using Base::lazyAssign; + using Base::eval; + + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + using Base::colStride; + + // bug 217 - compile error on ICC 11.1 + using Base::operator=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + + /** \copydoc DenseBase::rows() */ + EIGEN_DEVICE_FUNC inline Index rows() const { return m_rows.value(); } + /** \copydoc DenseBase::cols() */ + EIGEN_DEVICE_FUNC inline Index cols() const { return m_cols.value(); } + + /** Returns a pointer to the first coefficient of the matrix or vector. + * + * \note When addressing this data, make sure to honor the strides returned by innerStride() and outerStride(). + * + * \sa innerStride(), outerStride() + */ + EIGEN_DEVICE_FUNC inline const Scalar* data() const { return m_data; } + + /** \copydoc PlainObjectBase::coeff(Index,Index) const */ + EIGEN_DEVICE_FUNC + inline const Scalar& coeff(Index rowId, Index colId) const + { + return m_data[colId * colStride() + rowId * rowStride()]; + } + + /** \copydoc PlainObjectBase::coeff(Index) const */ + EIGEN_DEVICE_FUNC + inline const Scalar& coeff(Index index) const + { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return m_data[index * innerStride()]; + } + + /** \copydoc PlainObjectBase::coeffRef(Index,Index) const */ + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index rowId, Index colId) const + { + return this->m_data[colId * colStride() + rowId * rowStride()]; + } + + /** \copydoc PlainObjectBase::coeffRef(Index) const */ + EIGEN_DEVICE_FUNC + inline const Scalar& coeffRef(Index index) const + { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return this->m_data[index * innerStride()]; + } + + /** \internal */ + template + inline PacketScalar packet(Index rowId, Index colId) const + { + return internal::ploadt + (m_data + (colId * colStride() + rowId * rowStride())); + } + + /** \internal */ + template + inline PacketScalar packet(Index index) const + { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return internal::ploadt(m_data + index * innerStride()); + } + + /** \internal Constructor for fixed size matrices or vectors */ + EIGEN_DEVICE_FUNC + explicit inline MapBase(PointerType dataPtr) : m_data(dataPtr), m_rows(RowsAtCompileTime), m_cols(ColsAtCompileTime) + { + EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived) + checkSanity(); + } + + /** \internal Constructor for dynamically sized vectors */ + EIGEN_DEVICE_FUNC + inline MapBase(PointerType dataPtr, Index vecSize) + : m_data(dataPtr), + m_rows(RowsAtCompileTime == Dynamic ? vecSize : Index(RowsAtCompileTime)), + m_cols(ColsAtCompileTime == Dynamic ? vecSize : Index(ColsAtCompileTime)) + { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived) + eigen_assert(vecSize >= 0); + eigen_assert(dataPtr == 0 || SizeAtCompileTime == Dynamic || SizeAtCompileTime == vecSize); + checkSanity(); + } + + /** \internal Constructor for dynamically sized matrices */ + EIGEN_DEVICE_FUNC + inline MapBase(PointerType dataPtr, Index rows, Index cols) + : m_data(dataPtr), m_rows(rows), m_cols(cols) + { + eigen_assert( (dataPtr == 0) + || ( rows >= 0 && (RowsAtCompileTime == Dynamic || RowsAtCompileTime == rows) + && cols >= 0 && (ColsAtCompileTime == Dynamic || ColsAtCompileTime == cols))); + checkSanity(); + } + + #ifdef EIGEN_MAPBASE_PLUGIN + #include EIGEN_MAPBASE_PLUGIN + #endif + + protected: + + template + EIGEN_DEVICE_FUNC + void checkSanity(typename internal::enable_if<(internal::traits::Alignment>0),void*>::type = 0) const + { +#if EIGEN_MAX_ALIGN_BYTES>0 + // innerStride() is not set yet when this function is called, so we optimistically assume the lowest plausible value: + const Index minInnerStride = InnerStrideAtCompileTime == Dynamic ? 1 : Index(InnerStrideAtCompileTime); + EIGEN_ONLY_USED_FOR_DEBUG(minInnerStride); + eigen_assert(( ((internal::UIntPtr(m_data) % internal::traits::Alignment) == 0) + || (cols() * rows() * minInnerStride * sizeof(Scalar)) < internal::traits::Alignment ) && "data is not aligned"); +#endif + } + + template + EIGEN_DEVICE_FUNC + void checkSanity(typename internal::enable_if::Alignment==0,void*>::type = 0) const + {} + + PointerType m_data; + const internal::variable_if_dynamic m_rows; + const internal::variable_if_dynamic m_cols; +}; + +/** \ingroup Core_Module + * + * \brief Base class for non-const dense Map and Block expression with direct access + * + * This base class provides the non-const low-level accessors (e.g. coeff and coeffRef) of + * dense Map and Block objects with direct access. + * It inherits MapBase which defines the const variant for reading specific entries. + * + * \sa class Map, class Block + */ +template class MapBase + : public MapBase +{ + typedef MapBase ReadOnlyMapBase; + public: + + typedef MapBase Base; + + typedef typename Base::Scalar Scalar; + typedef typename Base::PacketScalar PacketScalar; + typedef typename Base::StorageIndex StorageIndex; + typedef typename Base::PointerType PointerType; + + using Base::derived; + using Base::rows; + using Base::cols; + using Base::size; + using Base::coeff; + using Base::coeffRef; + + using Base::innerStride; + using Base::outerStride; + using Base::rowStride; + using Base::colStride; + + typedef typename internal::conditional< + internal::is_lvalue::value, + Scalar, + const Scalar + >::type ScalarWithConstIfNotLvalue; + + EIGEN_DEVICE_FUNC + inline const Scalar* data() const { return this->m_data; } + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue* data() { return this->m_data; } // no const-cast here so non-const-correct code will give a compile error + + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue& coeffRef(Index row, Index col) + { + return this->m_data[col * colStride() + row * rowStride()]; + } + + EIGEN_DEVICE_FUNC + inline ScalarWithConstIfNotLvalue& coeffRef(Index index) + { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + return this->m_data[index * innerStride()]; + } + + template + inline void writePacket(Index row, Index col, const PacketScalar& val) + { + internal::pstoret + (this->m_data + (col * colStride() + row * rowStride()), val); + } + + template + inline void writePacket(Index index, const PacketScalar& val) + { + EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS(Derived) + internal::pstoret + (this->m_data + index * innerStride(), val); + } + + EIGEN_DEVICE_FUNC explicit inline MapBase(PointerType dataPtr) : Base(dataPtr) {} + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index vecSize) : Base(dataPtr, vecSize) {} + EIGEN_DEVICE_FUNC inline MapBase(PointerType dataPtr, Index rows, Index cols) : Base(dataPtr, rows, cols) {} + + EIGEN_DEVICE_FUNC + Derived& operator=(const MapBase& other) + { + ReadOnlyMapBase::Base::operator=(other); + return derived(); + } + + // In theory we could simply refer to Base:Base::operator=, but MSVC does not like Base::Base, + // see bugs 821 and 920. + using ReadOnlyMapBase::Base::operator=; +}; + +#undef EIGEN_STATIC_ASSERT_INDEX_BASED_ACCESS + +} // end namespace Eigen + +#endif // EIGEN_MAPBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctions.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctions.h new file mode 100644 index 0000000000000000000000000000000000000000..b249ce0c8b04177ecf2ee3b29529dd44ff3c5ba1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctions.h @@ -0,0 +1,1415 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATHFUNCTIONS_H +#define EIGEN_MATHFUNCTIONS_H + +// source: http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html +// TODO this should better be moved to NumTraits +#define EIGEN_PI 3.141592653589793238462643383279502884197169399375105820974944592307816406L + + +namespace Eigen { + +// On WINCE, std::abs is defined for int only, so let's defined our own overloads: +// This issue has been confirmed with MSVC 2008 only, but the issue might exist for more recent versions too. +#if EIGEN_OS_WINCE && EIGEN_COMP_MSVC && EIGEN_COMP_MSVC<=1500 +long abs(long x) { return (labs(x)); } +double abs(double x) { return (fabs(x)); } +float abs(float x) { return (fabsf(x)); } +long double abs(long double x) { return (fabsl(x)); } +#endif + +namespace internal { + +/** \internal \class global_math_functions_filtering_base + * + * What it does: + * Defines a typedef 'type' as follows: + * - if type T has a member typedef Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl, then + * global_math_functions_filtering_base::type is a typedef for it. + * - otherwise, global_math_functions_filtering_base::type is a typedef for T. + * + * How it's used: + * To allow to defined the global math functions (like sin...) in certain cases, like the Array expressions. + * When you do sin(array1+array2), the object array1+array2 has a complicated expression type, all what you want to know + * is that it inherits ArrayBase. So we implement a partial specialization of sin_impl for ArrayBase. + * So we must make sure to use sin_impl > and not sin_impl, otherwise our partial specialization + * won't be used. How does sin know that? That's exactly what global_math_functions_filtering_base tells it. + * + * How it's implemented: + * SFINAE in the style of enable_if. Highly susceptible of breaking compilers. With GCC, it sure does work, but if you replace + * the typename dummy by an integer template parameter, it doesn't work anymore! + */ + +template +struct global_math_functions_filtering_base +{ + typedef T type; +}; + +template struct always_void { typedef void type; }; + +template +struct global_math_functions_filtering_base + ::type + > +{ + typedef typename T::Eigen_BaseClassForSpecializationOfGlobalMathFuncImpl type; +}; + +#define EIGEN_MATHFUNC_IMPL(func, scalar) Eigen::internal::func##_impl::type> +#define EIGEN_MATHFUNC_RETVAL(func, scalar) typename Eigen::internal::func##_retval::type>::type + +/**************************************************************************** +* Implementation of real * +****************************************************************************/ + +template::IsComplex> +struct real_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + return x; + } +}; + +template +struct real_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + using std::real; + return real(x); + } +}; + +template struct real_impl : real_default_impl {}; + +#ifdef __CUDA_ARCH__ +template +struct real_impl > +{ + typedef T RealScalar; + EIGEN_DEVICE_FUNC + static inline T run(const std::complex& x) + { + return x.real(); + } +}; +#endif + +template +struct real_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of imag * +****************************************************************************/ + +template::IsComplex> +struct imag_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar&) + { + return RealScalar(0); + } +}; + +template +struct imag_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + using std::imag; + return imag(x); + } +}; + +template struct imag_impl : imag_default_impl {}; + +#ifdef __CUDA_ARCH__ +template +struct imag_impl > +{ + typedef T RealScalar; + EIGEN_DEVICE_FUNC + static inline T run(const std::complex& x) + { + return x.imag(); + } +}; +#endif + +template +struct imag_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of real_ref * +****************************************************************************/ + +template +struct real_ref_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar& run(Scalar& x) + { + return reinterpret_cast(&x)[0]; + } + EIGEN_DEVICE_FUNC + static inline const RealScalar& run(const Scalar& x) + { + return reinterpret_cast(&x)[0]; + } +}; + +template +struct real_ref_retval +{ + typedef typename NumTraits::Real & type; +}; + +/**************************************************************************** +* Implementation of imag_ref * +****************************************************************************/ + +template +struct imag_ref_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar& run(Scalar& x) + { + return reinterpret_cast(&x)[1]; + } + EIGEN_DEVICE_FUNC + static inline const RealScalar& run(const Scalar& x) + { + return reinterpret_cast(&x)[1]; + } +}; + +template +struct imag_ref_default_impl +{ + EIGEN_DEVICE_FUNC + static inline Scalar run(Scalar&) + { + return Scalar(0); + } + EIGEN_DEVICE_FUNC + static inline const Scalar run(const Scalar&) + { + return Scalar(0); + } +}; + +template +struct imag_ref_impl : imag_ref_default_impl::IsComplex> {}; + +template +struct imag_ref_retval +{ + typedef typename NumTraits::Real & type; +}; + +/**************************************************************************** +* Implementation of conj * +****************************************************************************/ + +template::IsComplex> +struct conj_impl +{ + EIGEN_DEVICE_FUNC + static inline Scalar run(const Scalar& x) + { + return x; + } +}; + +template +struct conj_impl +{ + EIGEN_DEVICE_FUNC + static inline Scalar run(const Scalar& x) + { + using std::conj; + return conj(x); + } +}; + +template +struct conj_retval +{ + typedef Scalar type; +}; + +/**************************************************************************** +* Implementation of abs2 * +****************************************************************************/ + +template +struct abs2_impl_default +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + return x*x; + } +}; + +template +struct abs2_impl_default // IsComplex +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + return real(x)*real(x) + imag(x)*imag(x); + } +}; + +template +struct abs2_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + return abs2_impl_default::IsComplex>::run(x); + } +}; + +template +struct abs2_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of norm1 * +****************************************************************************/ + +template +struct norm1_default_impl +{ + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + EIGEN_USING_STD_MATH(abs); + return abs(real(x)) + abs(imag(x)); + } +}; + +template +struct norm1_default_impl +{ + EIGEN_DEVICE_FUNC + static inline Scalar run(const Scalar& x) + { + EIGEN_USING_STD_MATH(abs); + return abs(x); + } +}; + +template +struct norm1_impl : norm1_default_impl::IsComplex> {}; + +template +struct norm1_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of hypot * +****************************************************************************/ + +template struct hypot_impl; + +template +struct hypot_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of cast * +****************************************************************************/ + +template +struct cast_impl +{ + EIGEN_DEVICE_FUNC + static inline NewType run(const OldType& x) + { + return static_cast(x); + } +}; + +// here, for once, we're plainly returning NewType: we don't want cast to do weird things. + +template +EIGEN_DEVICE_FUNC +inline NewType cast(const OldType& x) +{ + return cast_impl::run(x); +} + +/**************************************************************************** +* Implementation of round * +****************************************************************************/ + +#if EIGEN_HAS_CXX11_MATH + template + struct round_impl { + static inline Scalar run(const Scalar& x) + { + EIGEN_STATIC_ASSERT((!NumTraits::IsComplex), NUMERIC_TYPE_MUST_BE_REAL) + using std::round; + return round(x); + } + }; +#else + template + struct round_impl + { + static inline Scalar run(const Scalar& x) + { + EIGEN_STATIC_ASSERT((!NumTraits::IsComplex), NUMERIC_TYPE_MUST_BE_REAL) + EIGEN_USING_STD_MATH(floor); + EIGEN_USING_STD_MATH(ceil); + return (x > Scalar(0)) ? floor(x + Scalar(0.5)) : ceil(x - Scalar(0.5)); + } + }; +#endif + +template +struct round_retval +{ + typedef Scalar type; +}; + +/**************************************************************************** +* Implementation of arg * +****************************************************************************/ + +#if EIGEN_HAS_CXX11_MATH + template + struct arg_impl { + static inline Scalar run(const Scalar& x) + { + EIGEN_USING_STD_MATH(arg); + return arg(x); + } + }; +#else + template::IsComplex> + struct arg_default_impl + { + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + return (x < Scalar(0)) ? Scalar(EIGEN_PI) : Scalar(0); } + }; + + template + struct arg_default_impl + { + typedef typename NumTraits::Real RealScalar; + EIGEN_DEVICE_FUNC + static inline RealScalar run(const Scalar& x) + { + EIGEN_USING_STD_MATH(arg); + return arg(x); + } + }; + + template struct arg_impl : arg_default_impl {}; +#endif + +template +struct arg_retval +{ + typedef typename NumTraits::Real type; +}; + +/**************************************************************************** +* Implementation of log1p * +****************************************************************************/ + +namespace std_fallback { + // fallback log1p implementation in case there is no log1p(Scalar) function in namespace of Scalar, + // or that there is no suitable std::log1p function available + template + EIGEN_DEVICE_FUNC inline Scalar log1p(const Scalar& x) { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + typedef typename NumTraits::Real RealScalar; + EIGEN_USING_STD_MATH(log); + Scalar x1p = RealScalar(1) + x; + return numext::equal_strict(x1p, Scalar(1)) ? x : x * ( log(x1p) / (x1p - RealScalar(1)) ); + } +} + +template +struct log1p_impl { + static inline Scalar run(const Scalar& x) + { + EIGEN_STATIC_ASSERT_NON_INTEGER(Scalar) + #if EIGEN_HAS_CXX11_MATH + using std::log1p; + #endif + using std_fallback::log1p; + return log1p(x); + } +}; + + +template +struct log1p_retval +{ + typedef Scalar type; +}; + +/**************************************************************************** +* Implementation of pow * +****************************************************************************/ + +template::IsInteger&&NumTraits::IsInteger> +struct pow_impl +{ + //typedef Scalar retval; + typedef typename ScalarBinaryOpTraits >::ReturnType result_type; + static EIGEN_DEVICE_FUNC inline result_type run(const ScalarX& x, const ScalarY& y) + { + EIGEN_USING_STD_MATH(pow); + return pow(x, y); + } +}; + +template +struct pow_impl +{ + typedef ScalarX result_type; + static EIGEN_DEVICE_FUNC inline ScalarX run(ScalarX x, ScalarY y) + { + ScalarX res(1); + eigen_assert(!NumTraits::IsSigned || y >= 0); + if(y & 1) res *= x; + y >>= 1; + while(y) + { + x *= x; + if(y&1) res *= x; + y >>= 1; + } + return res; + } +}; + +/**************************************************************************** +* Implementation of random * +****************************************************************************/ + +template +struct random_default_impl {}; + +template +struct random_impl : random_default_impl::IsComplex, NumTraits::IsInteger> {}; + +template +struct random_retval +{ + typedef Scalar type; +}; + +template inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y); +template inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(); + +template +struct random_default_impl +{ + static inline Scalar run(const Scalar& x, const Scalar& y) + { + return x + (y-x) * Scalar(std::rand()) / Scalar(RAND_MAX); + } + static inline Scalar run() + { + return run(Scalar(NumTraits::IsSigned ? -1 : 0), Scalar(1)); + } +}; + +enum { + meta_floor_log2_terminate, + meta_floor_log2_move_up, + meta_floor_log2_move_down, + meta_floor_log2_bogus +}; + +template struct meta_floor_log2_selector +{ + enum { middle = (lower + upper) / 2, + value = (upper <= lower + 1) ? int(meta_floor_log2_terminate) + : (n < (1 << middle)) ? int(meta_floor_log2_move_down) + : (n==0) ? int(meta_floor_log2_bogus) + : int(meta_floor_log2_move_up) + }; +}; + +template::value> +struct meta_floor_log2 {}; + +template +struct meta_floor_log2 +{ + enum { value = meta_floor_log2::middle>::value }; +}; + +template +struct meta_floor_log2 +{ + enum { value = meta_floor_log2::middle, upper>::value }; +}; + +template +struct meta_floor_log2 +{ + enum { value = (n >= ((unsigned int)(1) << (lower+1))) ? lower+1 : lower }; +}; + +template +struct meta_floor_log2 +{ + // no value, error at compile time +}; + +template +struct random_default_impl +{ + static inline Scalar run(const Scalar& x, const Scalar& y) + { + if (y <= x) + return x; + // ScalarU is the unsigned counterpart of Scalar, possibly Scalar itself. + typedef typename make_unsigned::type ScalarU; + // ScalarX is the widest of ScalarU and unsigned int. + // We'll deal only with ScalarX and unsigned int below thus avoiding signed + // types and arithmetic and signed overflows (which are undefined behavior). + typedef typename conditional<(ScalarU(-1) > unsigned(-1)), ScalarU, unsigned>::type ScalarX; + // The following difference doesn't overflow, provided our integer types are two's + // complement and have the same number of padding bits in signed and unsigned variants. + // This is the case in most modern implementations of C++. + ScalarX range = ScalarX(y) - ScalarX(x); + ScalarX offset = 0; + ScalarX divisor = 1; + ScalarX multiplier = 1; + const unsigned rand_max = RAND_MAX; + if (range <= rand_max) divisor = (rand_max + 1) / (range + 1); + else multiplier = 1 + range / (rand_max + 1); + // Rejection sampling. + do { + offset = (unsigned(std::rand()) * multiplier) / divisor; + } while (offset > range); + return Scalar(ScalarX(x) + offset); + } + + static inline Scalar run() + { +#ifdef EIGEN_MAKING_DOCS + return run(Scalar(NumTraits::IsSigned ? -10 : 0), Scalar(10)); +#else + enum { rand_bits = meta_floor_log2<(unsigned int)(RAND_MAX)+1>::value, + scalar_bits = sizeof(Scalar) * CHAR_BIT, + shift = EIGEN_PLAIN_ENUM_MAX(0, int(rand_bits) - int(scalar_bits)), + offset = NumTraits::IsSigned ? (1 << (EIGEN_PLAIN_ENUM_MIN(rand_bits,scalar_bits)-1)) : 0 + }; + return Scalar((std::rand() >> shift) - offset); +#endif + } +}; + +template +struct random_default_impl +{ + static inline Scalar run(const Scalar& x, const Scalar& y) + { + return Scalar(random(real(x), real(y)), + random(imag(x), imag(y))); + } + static inline Scalar run() + { + typedef typename NumTraits::Real RealScalar; + return Scalar(random(), random()); + } +}; + +template +inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y) +{ + return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(x, y); +} + +template +inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random() +{ + return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(); +} + +// Implementatin of is* functions + +// std::is* do not work with fast-math and gcc, std::is* are available on MSVC 2013 and newer, as well as in clang. +#if (EIGEN_HAS_CXX11_MATH && !(EIGEN_COMP_GNUC_STRICT && __FINITE_MATH_ONLY__)) || (EIGEN_COMP_MSVC>=1800) || (EIGEN_COMP_CLANG) +#define EIGEN_USE_STD_FPCLASSIFY 1 +#else +#define EIGEN_USE_STD_FPCLASSIFY 0 +#endif + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if::value,bool>::type +isnan_impl(const T&) { return false; } + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if::value,bool>::type +isinf_impl(const T&) { return false; } + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if::value,bool>::type +isfinite_impl(const T&) { return true; } + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type +isfinite_impl(const T& x) +{ + #ifdef __CUDA_ARCH__ + return (::isfinite)(x); + #elif EIGEN_USE_STD_FPCLASSIFY + using std::isfinite; + return isfinite EIGEN_NOT_A_MACRO (x); + #else + return x<=NumTraits::highest() && x>=NumTraits::lowest(); + #endif +} + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type +isinf_impl(const T& x) +{ + #ifdef __CUDA_ARCH__ + return (::isinf)(x); + #elif EIGEN_USE_STD_FPCLASSIFY + using std::isinf; + return isinf EIGEN_NOT_A_MACRO (x); + #else + return x>NumTraits::highest() || x::lowest(); + #endif +} + +template +EIGEN_DEVICE_FUNC +typename internal::enable_if<(!internal::is_integral::value)&&(!NumTraits::IsComplex),bool>::type +isnan_impl(const T& x) +{ + #ifdef __CUDA_ARCH__ + return (::isnan)(x); + #elif EIGEN_USE_STD_FPCLASSIFY + using std::isnan; + return isnan EIGEN_NOT_A_MACRO (x); + #else + return x != x; + #endif +} + +#if (!EIGEN_USE_STD_FPCLASSIFY) + +#if EIGEN_COMP_MSVC + +template EIGEN_DEVICE_FUNC bool isinf_msvc_helper(T x) +{ + return _fpclass(x)==_FPCLASS_NINF || _fpclass(x)==_FPCLASS_PINF; +} + +//MSVC defines a _isnan builtin function, but for double only +EIGEN_DEVICE_FUNC inline bool isnan_impl(const long double& x) { return _isnan(x)!=0; } +EIGEN_DEVICE_FUNC inline bool isnan_impl(const double& x) { return _isnan(x)!=0; } +EIGEN_DEVICE_FUNC inline bool isnan_impl(const float& x) { return _isnan(x)!=0; } + +EIGEN_DEVICE_FUNC inline bool isinf_impl(const long double& x) { return isinf_msvc_helper(x); } +EIGEN_DEVICE_FUNC inline bool isinf_impl(const double& x) { return isinf_msvc_helper(x); } +EIGEN_DEVICE_FUNC inline bool isinf_impl(const float& x) { return isinf_msvc_helper(x); } + +#elif (defined __FINITE_MATH_ONLY__ && __FINITE_MATH_ONLY__ && EIGEN_COMP_GNUC) + +#if EIGEN_GNUC_AT_LEAST(5,0) + #define EIGEN_TMP_NOOPT_ATTRIB EIGEN_DEVICE_FUNC inline __attribute__((optimize("no-finite-math-only"))) +#else + // NOTE the inline qualifier and noinline attribute are both needed: the former is to avoid linking issue (duplicate symbol), + // while the second prevent too aggressive optimizations in fast-math mode: + #define EIGEN_TMP_NOOPT_ATTRIB EIGEN_DEVICE_FUNC inline __attribute__((noinline,optimize("no-finite-math-only"))) +#endif + +template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const long double& x) { return __builtin_isnan(x); } +template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const double& x) { return __builtin_isnan(x); } +template<> EIGEN_TMP_NOOPT_ATTRIB bool isnan_impl(const float& x) { return __builtin_isnan(x); } +template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const double& x) { return __builtin_isinf(x); } +template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const float& x) { return __builtin_isinf(x); } +template<> EIGEN_TMP_NOOPT_ATTRIB bool isinf_impl(const long double& x) { return __builtin_isinf(x); } + +#undef EIGEN_TMP_NOOPT_ATTRIB + +#endif + +#endif + +// The following overload are defined at the end of this file +template EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x); +template EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x); +template EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x); + +template T generic_fast_tanh_float(const T& a_x); + +} // end namespace internal + +/**************************************************************************** +* Generic math functions * +****************************************************************************/ + +namespace numext { + +#ifndef __CUDA_ARCH__ +template +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) +{ + EIGEN_USING_STD_MATH(min); + return min EIGEN_NOT_A_MACRO (x,y); +} + +template +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) +{ + EIGEN_USING_STD_MATH(max); + return max EIGEN_NOT_A_MACRO (x,y); +} +#else +template +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE T mini(const T& x, const T& y) +{ + return y < x ? y : x; +} +template<> +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE float mini(const float& x, const float& y) +{ + return fminf(x, y); +} +template +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE T maxi(const T& x, const T& y) +{ + return x < y ? y : x; +} +template<> +EIGEN_DEVICE_FUNC +EIGEN_ALWAYS_INLINE float maxi(const float& x, const float& y) +{ + return fmaxf(x, y); +} +#endif + + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(real, Scalar) real(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(real, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline typename internal::add_const_on_value_type< EIGEN_MATHFUNC_RETVAL(real_ref, Scalar) >::type real_ref(const Scalar& x) +{ + return internal::real_ref_impl::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(real_ref, Scalar) real_ref(Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(real_ref, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(imag, Scalar) imag(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(imag, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(arg, Scalar) arg(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(arg, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline typename internal::add_const_on_value_type< EIGEN_MATHFUNC_RETVAL(imag_ref, Scalar) >::type imag_ref(const Scalar& x) +{ + return internal::imag_ref_impl::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(imag_ref, Scalar) imag_ref(Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(imag_ref, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(conj, Scalar) conj(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(conj, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(abs2, Scalar) abs2(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(abs2, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(norm1, Scalar) norm1(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(norm1, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(hypot, Scalar) hypot(const Scalar& x, const Scalar& y) +{ + return EIGEN_MATHFUNC_IMPL(hypot, Scalar)::run(x, y); +} + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(log1p, Scalar) log1p(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(log1p, Scalar)::run(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float log1p(const float &x) { return ::log1pf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double log1p(const double &x) { return ::log1p(x); } +#endif + +template +EIGEN_DEVICE_FUNC +inline typename internal::pow_impl::result_type pow(const ScalarX& x, const ScalarY& y) +{ + return internal::pow_impl::run(x, y); +} + +template EIGEN_DEVICE_FUNC bool (isnan) (const T &x) { return internal::isnan_impl(x); } +template EIGEN_DEVICE_FUNC bool (isinf) (const T &x) { return internal::isinf_impl(x); } +template EIGEN_DEVICE_FUNC bool (isfinite)(const T &x) { return internal::isfinite_impl(x); } + +template +EIGEN_DEVICE_FUNC +inline EIGEN_MATHFUNC_RETVAL(round, Scalar) round(const Scalar& x) +{ + return EIGEN_MATHFUNC_IMPL(round, Scalar)::run(x); +} + +template +EIGEN_DEVICE_FUNC +T (floor)(const T& x) +{ + EIGEN_USING_STD_MATH(floor); + return floor(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float floor(const float &x) { return ::floorf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double floor(const double &x) { return ::floor(x); } +#endif + +template +EIGEN_DEVICE_FUNC +T (ceil)(const T& x) +{ + EIGEN_USING_STD_MATH(ceil); + return ceil(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float ceil(const float &x) { return ::ceilf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double ceil(const double &x) { return ::ceil(x); } +#endif + + +/** Log base 2 for 32 bits positive integers. + * Conveniently returns 0 for x==0. */ +inline int log2(int x) +{ + eigen_assert(x>=0); + unsigned int v(x); + static const int table[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + return table[(v * 0x07C4ACDDU) >> 27]; +} + +/** \returns the square root of \a x. + * + * It is essentially equivalent to + * \code using std::sqrt; return sqrt(x); \endcode + * but slightly faster for float/double and some compilers (e.g., gcc), thanks to + * specializations when SSE is enabled. + * + * It's usage is justified in performance critical functions, like norm/normalize. + */ +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T sqrt(const T &x) +{ + EIGEN_USING_STD_MATH(sqrt); + return sqrt(x); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T log(const T &x) { + EIGEN_USING_STD_MATH(log); + return log(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float log(const float &x) { return ::logf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double log(const double &x) { return ::log(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +typename internal::enable_if::IsSigned || NumTraits::IsComplex,typename NumTraits::Real>::type +abs(const T &x) { + EIGEN_USING_STD_MATH(abs); + return abs(x); +} + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +typename internal::enable_if::IsSigned || NumTraits::IsComplex),typename NumTraits::Real>::type +abs(const T &x) { + return x; +} + +#if defined(__SYCL_DEVICE_ONLY__) +EIGEN_ALWAYS_INLINE float abs(float x) { return cl::sycl::fabs(x); } +EIGEN_ALWAYS_INLINE double abs(double x) { return cl::sycl::fabs(x); } +#endif // defined(__SYCL_DEVICE_ONLY__) + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float abs(const float &x) { return ::fabsf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double abs(const double &x) { return ::fabs(x); } + +template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float abs(const std::complex& x) { + return ::hypotf(x.real(), x.imag()); +} + +template <> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double abs(const std::complex& x) { + return ::hypot(x.real(), x.imag()); +} +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T exp(const T &x) { + EIGEN_USING_STD_MATH(exp); + return exp(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float exp(const float &x) { return ::expf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double exp(const double &x) { return ::exp(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T cos(const T &x) { + EIGEN_USING_STD_MATH(cos); + return cos(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float cos(const float &x) { return ::cosf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double cos(const double &x) { return ::cos(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T sin(const T &x) { + EIGEN_USING_STD_MATH(sin); + return sin(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float sin(const float &x) { return ::sinf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double sin(const double &x) { return ::sin(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T tan(const T &x) { + EIGEN_USING_STD_MATH(tan); + return tan(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float tan(const float &x) { return ::tanf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double tan(const double &x) { return ::tan(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T acos(const T &x) { + EIGEN_USING_STD_MATH(acos); + return acos(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float acos(const float &x) { return ::acosf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double acos(const double &x) { return ::acos(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T asin(const T &x) { + EIGEN_USING_STD_MATH(asin); + return asin(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float asin(const float &x) { return ::asinf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double asin(const double &x) { return ::asin(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T atan(const T &x) { + EIGEN_USING_STD_MATH(atan); + return atan(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float atan(const float &x) { return ::atanf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double atan(const double &x) { return ::atan(x); } +#endif + + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T cosh(const T &x) { + EIGEN_USING_STD_MATH(cosh); + return cosh(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float cosh(const float &x) { return ::coshf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double cosh(const double &x) { return ::cosh(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T sinh(const T &x) { + EIGEN_USING_STD_MATH(sinh); + return sinh(x); +} + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float sinh(const float &x) { return ::sinhf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double sinh(const double &x) { return ::sinh(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T tanh(const T &x) { + EIGEN_USING_STD_MATH(tanh); + return tanh(x); +} + +#if (!defined(__CUDACC__)) && EIGEN_FAST_MATH +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float tanh(float x) { return internal::generic_fast_tanh_float(x); } +#endif + +#ifdef __CUDACC__ +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float tanh(const float &x) { return ::tanhf(x); } + +template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double tanh(const double &x) { return ::tanh(x); } +#endif + +template +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +T fmod(const T& a, const T& b) { + EIGEN_USING_STD_MATH(fmod); + return fmod(a, b); +} + +#ifdef __CUDACC__ +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +float fmod(const float& a, const float& b) { + return ::fmodf(a, b); +} + +template <> +EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE +double fmod(const double& a, const double& b) { + return ::fmod(a, b); +} +#endif + +} // end namespace numext + +namespace internal { + +template +EIGEN_DEVICE_FUNC bool isfinite_impl(const std::complex& x) +{ + return (numext::isfinite)(numext::real(x)) && (numext::isfinite)(numext::imag(x)); +} + +template +EIGEN_DEVICE_FUNC bool isnan_impl(const std::complex& x) +{ + return (numext::isnan)(numext::real(x)) || (numext::isnan)(numext::imag(x)); +} + +template +EIGEN_DEVICE_FUNC bool isinf_impl(const std::complex& x) +{ + return ((numext::isinf)(numext::real(x)) || (numext::isinf)(numext::imag(x))) && (!(numext::isnan)(x)); +} + +/**************************************************************************** +* Implementation of fuzzy comparisons * +****************************************************************************/ + +template +struct scalar_fuzzy_default_impl {}; + +template +struct scalar_fuzzy_default_impl +{ + typedef typename NumTraits::Real RealScalar; + template EIGEN_DEVICE_FUNC + static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, const RealScalar& prec) + { + return numext::abs(x) <= numext::abs(y) * prec; + } + EIGEN_DEVICE_FUNC + static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) + { + return numext::abs(x - y) <= numext::mini(numext::abs(x), numext::abs(y)) * prec; + } + EIGEN_DEVICE_FUNC + static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar& prec) + { + return x <= y || isApprox(x, y, prec); + } +}; + +template +struct scalar_fuzzy_default_impl +{ + typedef typename NumTraits::Real RealScalar; + template EIGEN_DEVICE_FUNC + static inline bool isMuchSmallerThan(const Scalar& x, const Scalar&, const RealScalar&) + { + return x == Scalar(0); + } + EIGEN_DEVICE_FUNC + static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar&) + { + return x == y; + } + EIGEN_DEVICE_FUNC + static inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, const RealScalar&) + { + return x <= y; + } +}; + +template +struct scalar_fuzzy_default_impl +{ + typedef typename NumTraits::Real RealScalar; + template EIGEN_DEVICE_FUNC + static inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, const RealScalar& prec) + { + return numext::abs2(x) <= numext::abs2(y) * prec * prec; + } + EIGEN_DEVICE_FUNC + static inline bool isApprox(const Scalar& x, const Scalar& y, const RealScalar& prec) + { + return numext::abs2(x - y) <= numext::mini(numext::abs2(x), numext::abs2(y)) * prec * prec; + } +}; + +template +struct scalar_fuzzy_impl : scalar_fuzzy_default_impl::IsComplex, NumTraits::IsInteger> {}; + +template EIGEN_DEVICE_FUNC +inline bool isMuchSmallerThan(const Scalar& x, const OtherScalar& y, + const typename NumTraits::Real &precision = NumTraits::dummy_precision()) +{ + return scalar_fuzzy_impl::template isMuchSmallerThan(x, y, precision); +} + +template EIGEN_DEVICE_FUNC +inline bool isApprox(const Scalar& x, const Scalar& y, + const typename NumTraits::Real &precision = NumTraits::dummy_precision()) +{ + return scalar_fuzzy_impl::isApprox(x, y, precision); +} + +template EIGEN_DEVICE_FUNC +inline bool isApproxOrLessThan(const Scalar& x, const Scalar& y, + const typename NumTraits::Real &precision = NumTraits::dummy_precision()) +{ + return scalar_fuzzy_impl::isApproxOrLessThan(x, y, precision); +} + +/****************************************** +*** The special case of the bool type *** +******************************************/ + +template<> struct random_impl +{ + static inline bool run() + { + return random(0,1)==0 ? false : true; + } +}; + +template<> struct scalar_fuzzy_impl +{ + typedef bool RealScalar; + + template EIGEN_DEVICE_FUNC + static inline bool isMuchSmallerThan(const bool& x, const bool&, const bool&) + { + return !x; + } + + EIGEN_DEVICE_FUNC + static inline bool isApprox(bool x, bool y, bool) + { + return x == y; + } + + EIGEN_DEVICE_FUNC + static inline bool isApproxOrLessThan(const bool& x, const bool& y, const bool&) + { + return (!x) || y; + } + +}; + + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_MATHFUNCTIONS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctionsImpl.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctionsImpl.h new file mode 100644 index 0000000000000000000000000000000000000000..9c1ceb0eb0f4a0bb2a03adef3b7fd72bc5b20b88 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MathFunctionsImpl.h @@ -0,0 +1,101 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Pedro Gonnet (pedro.gonnet@gmail.com) +// Copyright (C) 2016 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATHFUNCTIONSIMPL_H +#define EIGEN_MATHFUNCTIONSIMPL_H + +namespace Eigen { + +namespace internal { + +/** \internal \returns the hyperbolic tan of \a a (coeff-wise) + Doesn't do anything fancy, just a 13/6-degree rational interpolant which + is accurate up to a couple of ulp in the range [-9, 9], outside of which + the tanh(x) = +/-1. + + This implementation works on both scalars and packets. +*/ +template +T generic_fast_tanh_float(const T& a_x) +{ + // Clamp the inputs to the range [-9, 9] since anything outside + // this range is +/-1.0f in single-precision. + const T plus_9 = pset1(9.f); + const T minus_9 = pset1(-9.f); + // NOTE GCC prior to 6.3 might improperly optimize this max/min + // step such that if a_x is nan, x will be either 9 or -9, + // and tanh will return 1 or -1 instead of nan. + // This is supposed to be fixed in gcc6.3, + // see: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=72867 + const T x = pmax(minus_9,pmin(plus_9,a_x)); + // The monomial coefficients of the numerator polynomial (odd). + const T alpha_1 = pset1(4.89352455891786e-03f); + const T alpha_3 = pset1(6.37261928875436e-04f); + const T alpha_5 = pset1(1.48572235717979e-05f); + const T alpha_7 = pset1(5.12229709037114e-08f); + const T alpha_9 = pset1(-8.60467152213735e-11f); + const T alpha_11 = pset1(2.00018790482477e-13f); + const T alpha_13 = pset1(-2.76076847742355e-16f); + + // The monomial coefficients of the denominator polynomial (even). + const T beta_0 = pset1(4.89352518554385e-03f); + const T beta_2 = pset1(2.26843463243900e-03f); + const T beta_4 = pset1(1.18534705686654e-04f); + const T beta_6 = pset1(1.19825839466702e-06f); + + // Since the polynomials are odd/even, we need x^2. + const T x2 = pmul(x, x); + + // Evaluate the numerator polynomial p. + T p = pmadd(x2, alpha_13, alpha_11); + p = pmadd(x2, p, alpha_9); + p = pmadd(x2, p, alpha_7); + p = pmadd(x2, p, alpha_5); + p = pmadd(x2, p, alpha_3); + p = pmadd(x2, p, alpha_1); + p = pmul(x, p); + + // Evaluate the denominator polynomial p. + T q = pmadd(x2, beta_6, beta_4); + q = pmadd(x2, q, beta_2); + q = pmadd(x2, q, beta_0); + + // Divide the numerator by the denominator. + return pdiv(p, q); +} + +template +EIGEN_STRONG_INLINE +RealScalar positive_real_hypot(const RealScalar& x, const RealScalar& y) +{ + EIGEN_USING_STD_MATH(sqrt); + RealScalar p, qp; + p = numext::maxi(x,y); + if(p==RealScalar(0)) return RealScalar(0); + qp = numext::mini(y,x) / p; + return p * sqrt(RealScalar(1) + qp*qp); +} + +template +struct hypot_impl +{ + typedef typename NumTraits::Real RealScalar; + static inline RealScalar run(const Scalar& x, const Scalar& y) + { + EIGEN_USING_STD_MATH(abs); + return positive_real_hypot(abs(x), abs(y)); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_MATHFUNCTIONSIMPL_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Matrix.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Matrix.h new file mode 100644 index 0000000000000000000000000000000000000000..7f4a7af93c6bb14f9e81f24886759ddba79a6ee5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Matrix.h @@ -0,0 +1,459 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2010 Benoit Jacob +// Copyright (C) 2008-2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIX_H +#define EIGEN_MATRIX_H + +namespace Eigen { + +namespace internal { +template +struct traits > +{ +private: + enum { size = internal::size_at_compile_time<_Rows,_Cols>::ret }; + typedef typename find_best_packet<_Scalar,size>::type PacketScalar; + enum { + row_major_bit = _Options&RowMajor ? RowMajorBit : 0, + is_dynamic_size_storage = _MaxRows==Dynamic || _MaxCols==Dynamic, + max_size = is_dynamic_size_storage ? Dynamic : _MaxRows*_MaxCols, + default_alignment = compute_default_alignment<_Scalar,max_size>::value, + actual_alignment = ((_Options&DontAlign)==0) ? default_alignment : 0, + required_alignment = unpacket_traits::alignment, + packet_access_bit = (packet_traits<_Scalar>::Vectorizable && (EIGEN_UNALIGNED_VECTORIZE || (actual_alignment>=required_alignment))) ? PacketAccessBit : 0 + }; + +public: + typedef _Scalar Scalar; + typedef Dense StorageKind; + typedef Eigen::Index StorageIndex; + typedef MatrixXpr XprKind; + enum { + RowsAtCompileTime = _Rows, + ColsAtCompileTime = _Cols, + MaxRowsAtCompileTime = _MaxRows, + MaxColsAtCompileTime = _MaxCols, + Flags = compute_matrix_flags<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>::ret, + Options = _Options, + InnerStrideAtCompileTime = 1, + OuterStrideAtCompileTime = (Options&RowMajor) ? ColsAtCompileTime : RowsAtCompileTime, + + // FIXME, the following flag in only used to define NeedsToAlign in PlainObjectBase + EvaluatorFlags = LinearAccessBit | DirectAccessBit | packet_access_bit | row_major_bit, + Alignment = actual_alignment + }; +}; +} + +/** \class Matrix + * \ingroup Core_Module + * + * \brief The matrix class, also used for vectors and row-vectors + * + * The %Matrix class is the work-horse for all \em dense (\ref dense "note") matrices and vectors within Eigen. + * Vectors are matrices with one column, and row-vectors are matrices with one row. + * + * The %Matrix class encompasses \em both fixed-size and dynamic-size objects (\ref fixedsize "note"). + * + * The first three template parameters are required: + * \tparam _Scalar Numeric type, e.g. float, double, int or std::complex. + * User defined scalar types are supported as well (see \ref user_defined_scalars "here"). + * \tparam _Rows Number of rows, or \b Dynamic + * \tparam _Cols Number of columns, or \b Dynamic + * + * The remaining template parameters are optional -- in most cases you don't have to worry about them. + * \tparam _Options A combination of either \b #RowMajor or \b #ColMajor, and of either + * \b #AutoAlign or \b #DontAlign. + * The former controls \ref TopicStorageOrders "storage order", and defaults to column-major. The latter controls alignment, which is required + * for vectorization. It defaults to aligning matrices except for fixed sizes that aren't a multiple of the packet size. + * \tparam _MaxRows Maximum number of rows. Defaults to \a _Rows (\ref maxrows "note"). + * \tparam _MaxCols Maximum number of columns. Defaults to \a _Cols (\ref maxrows "note"). + * + * Eigen provides a number of typedefs covering the usual cases. Here are some examples: + * + * \li \c Matrix2d is a 2x2 square matrix of doubles (\c Matrix) + * \li \c Vector4f is a vector of 4 floats (\c Matrix) + * \li \c RowVector3i is a row-vector of 3 ints (\c Matrix) + * + * \li \c MatrixXf is a dynamic-size matrix of floats (\c Matrix) + * \li \c VectorXf is a dynamic-size vector of floats (\c Matrix) + * + * \li \c Matrix2Xf is a partially fixed-size (dynamic-size) matrix of floats (\c Matrix) + * \li \c MatrixX3d is a partially dynamic-size (fixed-size) matrix of double (\c Matrix) + * + * See \link matrixtypedefs this page \endlink for a complete list of predefined \em %Matrix and \em Vector typedefs. + * + * You can access elements of vectors and matrices using normal subscripting: + * + * \code + * Eigen::VectorXd v(10); + * v[0] = 0.1; + * v[1] = 0.2; + * v(0) = 0.3; + * v(1) = 0.4; + * + * Eigen::MatrixXi m(10, 10); + * m(0, 1) = 1; + * m(0, 2) = 2; + * m(0, 3) = 3; + * \endcode + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_MATRIX_PLUGIN. + * + * Some notes: + * + *
+ *
\anchor dense Dense versus sparse:
+ *
This %Matrix class handles dense, not sparse matrices and vectors. For sparse matrices and vectors, see the Sparse module. + * + * Dense matrices and vectors are plain usual arrays of coefficients. All the coefficients are stored, in an ordinary contiguous array. + * This is unlike Sparse matrices and vectors where the coefficients are stored as a list of nonzero coefficients.
+ * + *
\anchor fixedsize Fixed-size versus dynamic-size:
+ *
Fixed-size means that the numbers of rows and columns are known are compile-time. In this case, Eigen allocates the array + * of coefficients as a fixed-size array, as a class member. This makes sense for very small matrices, typically up to 4x4, sometimes up + * to 16x16. Larger matrices should be declared as dynamic-size even if one happens to know their size at compile-time. + * + * Dynamic-size means that the numbers of rows or columns are not necessarily known at compile-time. In this case they are runtime + * variables, and the array of coefficients is allocated dynamically on the heap. + * + * Note that \em dense matrices, be they Fixed-size or Dynamic-size, do not expand dynamically in the sense of a std::map. + * If you want this behavior, see the Sparse module.
+ * + *
\anchor maxrows _MaxRows and _MaxCols:
+ *
In most cases, one just leaves these parameters to the default values. + * These parameters mean the maximum size of rows and columns that the matrix may have. They are useful in cases + * when the exact numbers of rows and columns are not known are compile-time, but it is known at compile-time that they cannot + * exceed a certain value. This happens when taking dynamic-size blocks inside fixed-size matrices: in this case _MaxRows and _MaxCols + * are the dimensions of the original matrix, while _Rows and _Cols are Dynamic.
+ *
+ * + * ABI and storage layout + * + * The table below summarizes the ABI of some possible Matrix instances which is fixed thorough the lifetime of Eigen 3. + * + * + * + * + * + * + *
Matrix typeEquivalent C structure
\code Matrix \endcode\code + * struct { + * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 + * Eigen::Index rows, cols; + * }; + * \endcode
\code + * Matrix + * Matrix \endcode\code + * struct { + * T *data; // with (size_t(data)%EIGEN_MAX_ALIGN_BYTES)==0 + * Eigen::Index size; + * }; + * \endcode
\code Matrix \endcode\code + * struct { + * T data[Rows*Cols]; // with (size_t(data)%A(Rows*Cols*sizeof(T)))==0 + * }; + * \endcode
\code Matrix \endcode\code + * struct { + * T data[MaxRows*MaxCols]; // with (size_t(data)%A(MaxRows*MaxCols*sizeof(T)))==0 + * Eigen::Index rows, cols; + * }; + * \endcode
+ * Note that in this table Rows, Cols, MaxRows and MaxCols are all positive integers. A(S) is defined to the largest possible power-of-two + * smaller to EIGEN_MAX_STATIC_ALIGN_BYTES. + * + * \see MatrixBase for the majority of the API methods for matrices, \ref TopicClassHierarchy, + * \ref TopicStorageOrders + */ + +template +class Matrix + : public PlainObjectBase > +{ + public: + + /** \brief Base class typedef. + * \sa PlainObjectBase + */ + typedef PlainObjectBase Base; + + enum { Options = _Options }; + + EIGEN_DENSE_PUBLIC_INTERFACE(Matrix) + + typedef typename Base::PlainObject PlainObject; + + using Base::base; + using Base::coeffRef; + + /** + * \brief Assigns matrices to each other. + * + * \note This is a special case of the templated operator=. Its purpose is + * to prevent a default operator= from hiding the templated operator=. + * + * \callgraph + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix& operator=(const Matrix& other) + { + return Base::_set(other); + } + + /** \internal + * \brief Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix& operator=(const DenseBase& other) + { + return Base::_set(other); + } + + /* Here, doxygen failed to copy the brief information when using \copydoc */ + + /** + * \brief Copies the generic expression \a other into *this. + * \copydetails DenseBase::operator=(const EigenBase &other) + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix& operator=(const EigenBase &other) + { + return Base::operator=(other); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix& operator=(const ReturnByValue& func) + { + return Base::operator=(func); + } + + /** \brief Default constructor. + * + * For fixed-size matrices, does nothing. + * + * For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix + * is called a null matrix. This constructor is the unique way to create null matrices: resizing + * a matrix to 0 is not supported. + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix() : Base() + { + Base::_check_template_params(); + EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } + + // FIXME is it still needed + EIGEN_DEVICE_FUNC + explicit Matrix(internal::constructor_without_unaligned_array_assert) + : Base(internal::constructor_without_unaligned_array_assert()) + { Base::_check_template_params(); EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED } + +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + Matrix(Matrix&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible::value) + : Base(std::move(other)) + { + Base::_check_template_params(); + } + EIGEN_DEVICE_FUNC + Matrix& operator=(Matrix&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable::value) + { + other.swap(*this); + return *this; + } +#endif + + #ifndef EIGEN_PARSED_BY_DOXYGEN + + // This constructor is for both 1x1 matrices and dynamic vectors + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE explicit Matrix(const T& x) + { + Base::_check_template_params(); + Base::template _init1(x); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix(const T0& x, const T1& y) + { + Base::_check_template_params(); + Base::template _init2(x, y); + } + #else + /** \brief Constructs a fixed-sized matrix initialized with coefficients starting at \a data */ + EIGEN_DEVICE_FUNC + explicit Matrix(const Scalar *data); + + /** \brief Constructs a vector or row-vector with given dimension. \only_for_vectors + * + * This is useful for dynamic-size vectors. For fixed-size vectors, + * it is redundant to pass these parameters, so one should use the default constructor + * Matrix() instead. + * + * \warning This constructor is disabled for fixed-size \c 1x1 matrices. For instance, + * calling Matrix(1) will call the initialization constructor: Matrix(const Scalar&). + * For fixed-size \c 1x1 matrices it is therefore recommended to use the default + * constructor Matrix() instead, especially when using one of the non standard + * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). + */ + EIGEN_STRONG_INLINE explicit Matrix(Index dim); + /** \brief Constructs an initialized 1x1 matrix with the given coefficient */ + Matrix(const Scalar& x); + /** \brief Constructs an uninitialized matrix with \a rows rows and \a cols columns. + * + * This is useful for dynamic-size matrices. For fixed-size matrices, + * it is redundant to pass these parameters, so one should use the default constructor + * Matrix() instead. + * + * \warning This constructor is disabled for fixed-size \c 1x2 and \c 2x1 vectors. For instance, + * calling Matrix2f(2,1) will call the initialization constructor: Matrix(const Scalar& x, const Scalar& y). + * For fixed-size \c 1x2 or \c 2x1 vectors it is therefore recommended to use the default + * constructor Matrix() instead, especially when using one of the non standard + * \c EIGEN_INITIALIZE_MATRICES_BY_{ZERO,\c NAN} macros (see \ref TopicPreprocessorDirectives). + */ + EIGEN_DEVICE_FUNC + Matrix(Index rows, Index cols); + + /** \brief Constructs an initialized 2D vector with given coefficients */ + Matrix(const Scalar& x, const Scalar& y); + #endif + + /** \brief Constructs an initialized 3D vector with given coefficients */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z) + { + Base::_check_template_params(); + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 3) + m_storage.data()[0] = x; + m_storage.data()[1] = y; + m_storage.data()[2] = z; + } + /** \brief Constructs an initialized 4D vector with given coefficients */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix(const Scalar& x, const Scalar& y, const Scalar& z, const Scalar& w) + { + Base::_check_template_params(); + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Matrix, 4) + m_storage.data()[0] = x; + m_storage.data()[1] = y; + m_storage.data()[2] = z; + m_storage.data()[3] = w; + } + + + /** \brief Copy constructor */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix(const Matrix& other) : Base(other) + { } + + /** \brief Copy constructor for generic expressions. + * \sa MatrixBase::operator=(const EigenBase&) + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Matrix(const EigenBase &other) + : Base(other.derived()) + { } + + EIGEN_DEVICE_FUNC inline Index innerStride() const { return 1; } + EIGEN_DEVICE_FUNC inline Index outerStride() const { return this->innerSize(); } + + /////////// Geometry module /////////// + + template + EIGEN_DEVICE_FUNC + explicit Matrix(const RotationBase& r); + template + EIGEN_DEVICE_FUNC + Matrix& operator=(const RotationBase& r); + + // allow to extend Matrix outside Eigen + #ifdef EIGEN_MATRIX_PLUGIN + #include EIGEN_MATRIX_PLUGIN + #endif + + protected: + template + friend struct internal::conservative_resize_like_impl; + + using Base::m_storage; +}; + +/** \defgroup matrixtypedefs Global matrix typedefs + * + * \ingroup Core_Module + * + * Eigen defines several typedef shortcuts for most common matrix and vector types. + * + * The general patterns are the following: + * + * \c MatrixSizeType where \c Size can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size, + * and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd + * for complex double. + * + * For example, \c Matrix3d is a fixed-size 3x3 matrix type of doubles, and \c MatrixXf is a dynamic-size matrix of floats. + * + * There are also \c VectorSizeType and \c RowVectorSizeType which are self-explanatory. For example, \c Vector4cf is + * a fixed-size vector of 4 complex floats. + * + * \sa class Matrix + */ + +#define EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \ +/** \ingroup matrixtypedefs */ \ +typedef Matrix Matrix##SizeSuffix##TypeSuffix; \ +/** \ingroup matrixtypedefs */ \ +typedef Matrix Vector##SizeSuffix##TypeSuffix; \ +/** \ingroup matrixtypedefs */ \ +typedef Matrix RowVector##SizeSuffix##TypeSuffix; + +#define EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \ +/** \ingroup matrixtypedefs */ \ +typedef Matrix Matrix##Size##X##TypeSuffix; \ +/** \ingroup matrixtypedefs */ \ +typedef Matrix Matrix##X##Size##TypeSuffix; + +#define EIGEN_MAKE_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \ +EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 2, 2) \ +EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 3, 3) \ +EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, 4, 4) \ +EIGEN_MAKE_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \ +EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \ +EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \ +EIGEN_MAKE_FIXED_TYPEDEFS(Type, TypeSuffix, 4) + +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(int, i) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(float, f) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(double, d) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex, cf) +EIGEN_MAKE_TYPEDEFS_ALL_SIZES(std::complex, cd) + +#undef EIGEN_MAKE_TYPEDEFS_ALL_SIZES +#undef EIGEN_MAKE_TYPEDEFS +#undef EIGEN_MAKE_FIXED_TYPEDEFS + +} // end namespace Eigen + +#endif // EIGEN_MATRIX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MatrixBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MatrixBase.h new file mode 100644 index 0000000000000000000000000000000000000000..e6c35907c3960172141d1bc02bd5116ef757c85f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/MatrixBase.h @@ -0,0 +1,529 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2009 Benoit Jacob +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_MATRIXBASE_H +#define EIGEN_MATRIXBASE_H + +namespace Eigen { + +/** \class MatrixBase + * \ingroup Core_Module + * + * \brief Base class for all dense matrices, vectors, and expressions + * + * This class is the base that is inherited by all matrix, vector, and related expression + * types. Most of the Eigen API is contained in this class, and its base classes. Other important + * classes for the Eigen API are Matrix, and VectorwiseOp. + * + * Note that some methods are defined in other modules such as the \ref LU_Module LU module + * for all functions related to matrix inversions. + * + * \tparam Derived is the derived type, e.g. a matrix type, or an expression, etc. + * + * When writing a function taking Eigen objects as argument, if you want your function + * to take as argument any matrix, vector, or expression, just let it take a + * MatrixBase argument. As an example, here is a function printFirstRow which, given + * a matrix, vector, or expression \a x, prints the first row of \a x. + * + * \code + template + void printFirstRow(const Eigen::MatrixBase& x) + { + cout << x.row(0) << endl; + } + * \endcode + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_MATRIXBASE_PLUGIN. + * + * \sa \blank \ref TopicClassHierarchy + */ +template class MatrixBase + : public DenseBase +{ + public: +#ifndef EIGEN_PARSED_BY_DOXYGEN + typedef MatrixBase StorageBaseType; + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::StorageIndex StorageIndex; + typedef typename internal::traits::Scalar Scalar; + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + + typedef DenseBase Base; + using Base::RowsAtCompileTime; + using Base::ColsAtCompileTime; + using Base::SizeAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::IsVectorAtCompileTime; + using Base::Flags; + + using Base::derived; + using Base::const_cast_derived; + using Base::rows; + using Base::cols; + using Base::size; + using Base::coeff; + using Base::coeffRef; + using Base::lazyAssign; + using Base::eval; + using Base::operator+=; + using Base::operator-=; + using Base::operator*=; + using Base::operator/=; + + typedef typename Base::CoeffReturnType CoeffReturnType; + typedef typename Base::ConstTransposeReturnType ConstTransposeReturnType; + typedef typename Base::RowXpr RowXpr; + typedef typename Base::ColXpr ColXpr; +#endif // not EIGEN_PARSED_BY_DOXYGEN + + + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** type of the equivalent square matrix */ + typedef Matrix SquareMatrixType; +#endif // not EIGEN_PARSED_BY_DOXYGEN + + /** \returns the size of the main diagonal, which is min(rows(),cols()). + * \sa rows(), cols(), SizeAtCompileTime. */ + EIGEN_DEVICE_FUNC + inline Index diagonalSize() const { return (numext::mini)(rows(),cols()); } + + typedef typename Base::PlainObject PlainObject; + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal Represents a matrix with all coefficients equal to one another*/ + typedef CwiseNullaryOp,PlainObject> ConstantReturnType; + /** \internal the return type of MatrixBase::adjoint() */ + typedef typename internal::conditional::IsComplex, + CwiseUnaryOp, ConstTransposeReturnType>, + ConstTransposeReturnType + >::type AdjointReturnType; + /** \internal Return type of eigenvalues() */ + typedef Matrix, internal::traits::ColsAtCompileTime, 1, ColMajor> EigenvaluesReturnType; + /** \internal the return type of identity */ + typedef CwiseNullaryOp,PlainObject> IdentityReturnType; + /** \internal the return type of unit vectors */ + typedef Block, SquareMatrixType>, + internal::traits::RowsAtCompileTime, + internal::traits::ColsAtCompileTime> BasisReturnType; +#endif // not EIGEN_PARSED_BY_DOXYGEN + +#define EIGEN_CURRENT_STORAGE_BASE_CLASS Eigen::MatrixBase +#define EIGEN_DOC_UNARY_ADDONS(X,Y) +# include "../plugins/CommonCwiseUnaryOps.h" +# include "../plugins/CommonCwiseBinaryOps.h" +# include "../plugins/MatrixCwiseUnaryOps.h" +# include "../plugins/MatrixCwiseBinaryOps.h" +# ifdef EIGEN_MATRIXBASE_PLUGIN +# include EIGEN_MATRIXBASE_PLUGIN +# endif +#undef EIGEN_CURRENT_STORAGE_BASE_CLASS +#undef EIGEN_DOC_UNARY_ADDONS + + /** Special case of the template operator=, in order to prevent the compiler + * from generating a default operator= (issue hit with g++ 4.1) + */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const MatrixBase& other); + + // We cannot inherit here via Base::operator= since it is causing + // trouble with MSVC. + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator=(const DenseBase& other); + + template + EIGEN_DEVICE_FUNC + Derived& operator=(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC + Derived& operator=(const ReturnByValue& other); + + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator+=(const MatrixBase& other); + template + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + Derived& operator-=(const MatrixBase& other); + + template + EIGEN_DEVICE_FUNC + const Product + operator*(const MatrixBase &other) const; + + template + EIGEN_DEVICE_FUNC + const Product + lazyProduct(const MatrixBase &other) const; + + template + Derived& operator*=(const EigenBase& other); + + template + void applyOnTheLeft(const EigenBase& other); + + template + void applyOnTheRight(const EigenBase& other); + + template + EIGEN_DEVICE_FUNC + const Product + operator*(const DiagonalBase &diagonal) const; + + template + EIGEN_DEVICE_FUNC + typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType + dot(const MatrixBase& other) const; + + EIGEN_DEVICE_FUNC RealScalar squaredNorm() const; + EIGEN_DEVICE_FUNC RealScalar norm() const; + RealScalar stableNorm() const; + RealScalar blueNorm() const; + RealScalar hypotNorm() const; + EIGEN_DEVICE_FUNC const PlainObject normalized() const; + EIGEN_DEVICE_FUNC const PlainObject stableNormalized() const; + EIGEN_DEVICE_FUNC void normalize(); + EIGEN_DEVICE_FUNC void stableNormalize(); + + EIGEN_DEVICE_FUNC const AdjointReturnType adjoint() const; + EIGEN_DEVICE_FUNC void adjointInPlace(); + + typedef Diagonal DiagonalReturnType; + EIGEN_DEVICE_FUNC + DiagonalReturnType diagonal(); + + typedef typename internal::add_const >::type ConstDiagonalReturnType; + EIGEN_DEVICE_FUNC + ConstDiagonalReturnType diagonal() const; + + template struct DiagonalIndexReturnType { typedef Diagonal Type; }; + template struct ConstDiagonalIndexReturnType { typedef const Diagonal Type; }; + + template + EIGEN_DEVICE_FUNC + typename DiagonalIndexReturnType::Type diagonal(); + + template + EIGEN_DEVICE_FUNC + typename ConstDiagonalIndexReturnType::Type diagonal() const; + + typedef Diagonal DiagonalDynamicIndexReturnType; + typedef typename internal::add_const >::type ConstDiagonalDynamicIndexReturnType; + + EIGEN_DEVICE_FUNC + DiagonalDynamicIndexReturnType diagonal(Index index); + EIGEN_DEVICE_FUNC + ConstDiagonalDynamicIndexReturnType diagonal(Index index) const; + + template struct TriangularViewReturnType { typedef TriangularView Type; }; + template struct ConstTriangularViewReturnType { typedef const TriangularView Type; }; + + template + EIGEN_DEVICE_FUNC + typename TriangularViewReturnType::Type triangularView(); + template + EIGEN_DEVICE_FUNC + typename ConstTriangularViewReturnType::Type triangularView() const; + + template struct SelfAdjointViewReturnType { typedef SelfAdjointView Type; }; + template struct ConstSelfAdjointViewReturnType { typedef const SelfAdjointView Type; }; + + template + EIGEN_DEVICE_FUNC + typename SelfAdjointViewReturnType::Type selfadjointView(); + template + EIGEN_DEVICE_FUNC + typename ConstSelfAdjointViewReturnType::Type selfadjointView() const; + + const SparseView sparseView(const Scalar& m_reference = Scalar(0), + const typename NumTraits::Real& m_epsilon = NumTraits::dummy_precision()) const; + EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(); + EIGEN_DEVICE_FUNC static const IdentityReturnType Identity(Index rows, Index cols); + EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index size, Index i); + EIGEN_DEVICE_FUNC static const BasisReturnType Unit(Index i); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitX(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitY(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitZ(); + EIGEN_DEVICE_FUNC static const BasisReturnType UnitW(); + + EIGEN_DEVICE_FUNC + const DiagonalWrapper asDiagonal() const; + const PermutationWrapper asPermutation() const; + + EIGEN_DEVICE_FUNC + Derived& setIdentity(); + EIGEN_DEVICE_FUNC + Derived& setIdentity(Index rows, Index cols); + + bool isIdentity(const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isDiagonal(const RealScalar& prec = NumTraits::dummy_precision()) const; + + bool isUpperTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isLowerTriangular(const RealScalar& prec = NumTraits::dummy_precision()) const; + + template + bool isOrthogonal(const MatrixBase& other, + const RealScalar& prec = NumTraits::dummy_precision()) const; + bool isUnitary(const RealScalar& prec = NumTraits::dummy_precision()) const; + + /** \returns true if each coefficients of \c *this and \a other are all exactly equal. + * \warning When using floating point scalar values you probably should rather use a + * fuzzy comparison such as isApprox() + * \sa isApprox(), operator!= */ + template + EIGEN_DEVICE_FUNC inline bool operator==(const MatrixBase& other) const + { return cwiseEqual(other).all(); } + + /** \returns true if at least one pair of coefficients of \c *this and \a other are not exactly equal to each other. + * \warning When using floating point scalar values you probably should rather use a + * fuzzy comparison such as isApprox() + * \sa isApprox(), operator== */ + template + EIGEN_DEVICE_FUNC inline bool operator!=(const MatrixBase& other) const + { return cwiseNotEqual(other).any(); } + + NoAlias noalias(); + + // TODO forceAlignedAccess is temporarily disabled + // Need to find a nicer workaround. + inline const Derived& forceAlignedAccess() const { return derived(); } + inline Derived& forceAlignedAccess() { return derived(); } + template inline const Derived& forceAlignedAccessIf() const { return derived(); } + template inline Derived& forceAlignedAccessIf() { return derived(); } + + EIGEN_DEVICE_FUNC Scalar trace() const; + + template EIGEN_DEVICE_FUNC RealScalar lpNorm() const; + + EIGEN_DEVICE_FUNC MatrixBase& matrix() { return *this; } + EIGEN_DEVICE_FUNC const MatrixBase& matrix() const { return *this; } + + /** \returns an \link Eigen::ArrayBase Array \endlink expression of this matrix + * \sa ArrayBase::matrix() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE ArrayWrapper array() { return ArrayWrapper(derived()); } + /** \returns a const \link Eigen::ArrayBase Array \endlink expression of this matrix + * \sa ArrayBase::matrix() */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArrayWrapper array() const { return ArrayWrapper(derived()); } + +/////////// LU module /////////// + + inline const FullPivLU fullPivLu() const; + inline const PartialPivLU partialPivLu() const; + + inline const PartialPivLU lu() const; + + inline const Inverse inverse() const; + + template + inline void computeInverseAndDetWithCheck( + ResultType& inverse, + typename ResultType::Scalar& determinant, + bool& invertible, + const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision() + ) const; + template + inline void computeInverseWithCheck( + ResultType& inverse, + bool& invertible, + const RealScalar& absDeterminantThreshold = NumTraits::dummy_precision() + ) const; + Scalar determinant() const; + +/////////// Cholesky module /////////// + + inline const LLT llt() const; + inline const LDLT ldlt() const; + +/////////// QR module /////////// + + inline const HouseholderQR householderQr() const; + inline const ColPivHouseholderQR colPivHouseholderQr() const; + inline const FullPivHouseholderQR fullPivHouseholderQr() const; + inline const CompleteOrthogonalDecomposition completeOrthogonalDecomposition() const; + +/////////// Eigenvalues module /////////// + + inline EigenvaluesReturnType eigenvalues() const; + inline RealScalar operatorNorm() const; + +/////////// SVD module /////////// + + inline JacobiSVD jacobiSvd(unsigned int computationOptions = 0) const; + inline BDCSVD bdcSvd(unsigned int computationOptions = 0) const; + +/////////// Geometry module /////////// + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /// \internal helper struct to form the return type of the cross product + template struct cross_product_return_type { + typedef typename ScalarBinaryOpTraits::Scalar,typename internal::traits::Scalar>::ReturnType Scalar; + typedef Matrix type; + }; + #endif // EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC +#ifndef EIGEN_PARSED_BY_DOXYGEN + inline typename cross_product_return_type::type +#else + inline PlainObject +#endif + cross(const MatrixBase& other) const; + + template + EIGEN_DEVICE_FUNC + inline PlainObject cross3(const MatrixBase& other) const; + + EIGEN_DEVICE_FUNC + inline PlainObject unitOrthogonal(void) const; + + EIGEN_DEVICE_FUNC + inline Matrix eulerAngles(Index a0, Index a1, Index a2) const; + + // put this as separate enum value to work around possible GCC 4.3 bug (?) + enum { HomogeneousReturnTypeDirection = ColsAtCompileTime==1&&RowsAtCompileTime==1 ? ((internal::traits::Flags&RowMajorBit)==RowMajorBit ? Horizontal : Vertical) + : ColsAtCompileTime==1 ? Vertical : Horizontal }; + typedef Homogeneous HomogeneousReturnType; + EIGEN_DEVICE_FUNC + inline HomogeneousReturnType homogeneous() const; + + enum { + SizeMinusOne = SizeAtCompileTime==Dynamic ? Dynamic : SizeAtCompileTime-1 + }; + typedef Block::ColsAtCompileTime==1 ? SizeMinusOne : 1, + internal::traits::ColsAtCompileTime==1 ? 1 : SizeMinusOne> ConstStartMinusOne; + typedef EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(ConstStartMinusOne,Scalar,quotient) HNormalizedReturnType; + EIGEN_DEVICE_FUNC + inline const HNormalizedReturnType hnormalized() const; + +////////// Householder module /////////// + + void makeHouseholderInPlace(Scalar& tau, RealScalar& beta); + template + void makeHouseholder(EssentialPart& essential, + Scalar& tau, RealScalar& beta) const; + template + void applyHouseholderOnTheLeft(const EssentialPart& essential, + const Scalar& tau, + Scalar* workspace); + template + void applyHouseholderOnTheRight(const EssentialPart& essential, + const Scalar& tau, + Scalar* workspace); + +///////// Jacobi module ///////// + + template + void applyOnTheLeft(Index p, Index q, const JacobiRotation& j); + template + void applyOnTheRight(Index p, Index q, const JacobiRotation& j); + +///////// SparseCore module ///////// + + template + EIGEN_STRONG_INLINE const typename SparseMatrixBase::template CwiseProductDenseReturnType::Type + cwiseProduct(const SparseMatrixBase &other) const + { + return other.cwiseProduct(derived()); + } + +///////// MatrixFunctions module ///////// + + typedef typename internal::stem_function::type StemFunction; +#define EIGEN_MATRIX_FUNCTION(ReturnType, Name, Description) \ + /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the coefficient-wise Description use ArrayBase::##Name . */ \ + const ReturnType Name() const; +#define EIGEN_MATRIX_FUNCTION_1(ReturnType, Name, Description, Argument) \ + /** \returns an expression of the matrix Description of \c *this. \brief This function requires the unsupported MatrixFunctions module. To compute the coefficient-wise Description use ArrayBase::##Name . */ \ + const ReturnType Name(Argument) const; + + EIGEN_MATRIX_FUNCTION(MatrixExponentialReturnValue, exp, exponential) + /** \brief Helper function for the unsupported MatrixFunctions module.*/ + const MatrixFunctionReturnValue matrixFunction(StemFunction f) const; + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cosh, hyperbolic cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sinh, hyperbolic sine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, cos, cosine) + EIGEN_MATRIX_FUNCTION(MatrixFunctionReturnValue, sin, sine) + EIGEN_MATRIX_FUNCTION(MatrixSquareRootReturnValue, sqrt, square root) + EIGEN_MATRIX_FUNCTION(MatrixLogarithmReturnValue, log, logarithm) + EIGEN_MATRIX_FUNCTION_1(MatrixPowerReturnValue, pow, power to \c p, const RealScalar& p) + EIGEN_MATRIX_FUNCTION_1(MatrixComplexPowerReturnValue, pow, power to \c p, const std::complex& p) + + protected: + EIGEN_DEVICE_FUNC MatrixBase() : Base() {} + + private: + EIGEN_DEVICE_FUNC explicit MatrixBase(int); + EIGEN_DEVICE_FUNC MatrixBase(int,int); + template EIGEN_DEVICE_FUNC explicit MatrixBase(const MatrixBase&); + protected: + // mixing arrays and matrices is not legal + template Derived& operator+=(const ArrayBase& ) + {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} + // mixing arrays and matrices is not legal + template Derived& operator-=(const ArrayBase& ) + {EIGEN_STATIC_ASSERT(std::ptrdiff_t(sizeof(typename OtherDerived::Scalar))==-1,YOU_CANNOT_MIX_ARRAYS_AND_MATRICES); return *this;} +}; + + +/*************************************************************************** +* Implementation of matrix base methods +***************************************************************************/ + +/** replaces \c *this by \c *this * \a other. + * + * \returns a reference to \c *this + * + * Example: \include MatrixBase_applyOnTheRight.cpp + * Output: \verbinclude MatrixBase_applyOnTheRight.out + */ +template +template +inline Derived& +MatrixBase::operator*=(const EigenBase &other) +{ + other.derived().applyThisOnTheRight(derived()); + return derived(); +} + +/** replaces \c *this by \c *this * \a other. It is equivalent to MatrixBase::operator*=(). + * + * Example: \include MatrixBase_applyOnTheRight.cpp + * Output: \verbinclude MatrixBase_applyOnTheRight.out + */ +template +template +inline void MatrixBase::applyOnTheRight(const EigenBase &other) +{ + other.derived().applyThisOnTheRight(derived()); +} + +/** replaces \c *this by \a other * \c *this. + * + * Example: \include MatrixBase_applyOnTheLeft.cpp + * Output: \verbinclude MatrixBase_applyOnTheLeft.out + */ +template +template +inline void MatrixBase::applyOnTheLeft(const EigenBase &other) +{ + other.derived().applyThisOnTheLeft(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_MATRIXBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NestByValue.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NestByValue.h new file mode 100644 index 0000000000000000000000000000000000000000..13adf070e8987cb452d12256d7c1ff113b8f2721 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NestByValue.h @@ -0,0 +1,110 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NESTBYVALUE_H +#define EIGEN_NESTBYVALUE_H + +namespace Eigen { + +namespace internal { +template +struct traits > : public traits +{}; +} + +/** \class NestByValue + * \ingroup Core_Module + * + * \brief Expression which must be nested by value + * + * \tparam ExpressionType the type of the object of which we are requiring nesting-by-value + * + * This class is the return type of MatrixBase::nestByValue() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::nestByValue() + */ +template class NestByValue + : public internal::dense_xpr_base< NestByValue >::type +{ + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(NestByValue) + + EIGEN_DEVICE_FUNC explicit inline NestByValue(const ExpressionType& matrix) : m_expression(matrix) {} + + EIGEN_DEVICE_FUNC inline Index rows() const { return m_expression.rows(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return m_expression.cols(); } + EIGEN_DEVICE_FUNC inline Index outerStride() const { return m_expression.outerStride(); } + EIGEN_DEVICE_FUNC inline Index innerStride() const { return m_expression.innerStride(); } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index row, Index col) const + { + return m_expression.coeff(row, col); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index row, Index col) + { + return m_expression.const_cast_derived().coeffRef(row, col); + } + + EIGEN_DEVICE_FUNC inline const CoeffReturnType coeff(Index index) const + { + return m_expression.coeff(index); + } + + EIGEN_DEVICE_FUNC inline Scalar& coeffRef(Index index) + { + return m_expression.const_cast_derived().coeffRef(index); + } + + template + inline const PacketScalar packet(Index row, Index col) const + { + return m_expression.template packet(row, col); + } + + template + inline void writePacket(Index row, Index col, const PacketScalar& x) + { + m_expression.const_cast_derived().template writePacket(row, col, x); + } + + template + inline const PacketScalar packet(Index index) const + { + return m_expression.template packet(index); + } + + template + inline void writePacket(Index index, const PacketScalar& x) + { + m_expression.const_cast_derived().template writePacket(index, x); + } + + EIGEN_DEVICE_FUNC operator const ExpressionType&() const { return m_expression; } + + protected: + const ExpressionType m_expression; +}; + +/** \returns an expression of the temporary version of *this. + */ +template +inline const NestByValue +DenseBase::nestByValue() const +{ + return NestByValue(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_NESTBYVALUE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NoAlias.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NoAlias.h new file mode 100644 index 0000000000000000000000000000000000000000..33908010b4f13631146eb45a6bfdf04cae2e58c5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NoAlias.h @@ -0,0 +1,108 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NOALIAS_H +#define EIGEN_NOALIAS_H + +namespace Eigen { + +/** \class NoAlias + * \ingroup Core_Module + * + * \brief Pseudo expression providing an operator = assuming no aliasing + * + * \tparam ExpressionType the type of the object on which to do the lazy assignment + * + * This class represents an expression with special assignment operators + * assuming no aliasing between the target expression and the source expression. + * More precisely it alloas to bypass the EvalBeforeAssignBit flag of the source expression. + * It is the return type of MatrixBase::noalias() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::noalias() + */ +template class StorageBase> +class NoAlias +{ + public: + typedef typename ExpressionType::Scalar Scalar; + + explicit NoAlias(ExpressionType& expression) : m_expression(expression) {} + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE ExpressionType& operator=(const StorageBase& other) + { + call_assignment_no_alias(m_expression, other.derived(), internal::assign_op()); + return m_expression; + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE ExpressionType& operator+=(const StorageBase& other) + { + call_assignment_no_alias(m_expression, other.derived(), internal::add_assign_op()); + return m_expression; + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE ExpressionType& operator-=(const StorageBase& other) + { + call_assignment_no_alias(m_expression, other.derived(), internal::sub_assign_op()); + return m_expression; + } + + EIGEN_DEVICE_FUNC + ExpressionType& expression() const + { + return m_expression; + } + + protected: + ExpressionType& m_expression; +}; + +/** \returns a pseudo expression of \c *this with an operator= assuming + * no aliasing between \c *this and the source expression. + * + * More precisely, noalias() allows to bypass the EvalBeforeAssignBit flag. + * Currently, even though several expressions may alias, only product + * expressions have this flag. Therefore, noalias() is only usefull when + * the source expression contains a matrix product. + * + * Here are some examples where noalias is usefull: + * \code + * D.noalias() = A * B; + * D.noalias() += A.transpose() * B; + * D.noalias() -= 2 * A * B.adjoint(); + * \endcode + * + * On the other hand the following example will lead to a \b wrong result: + * \code + * A.noalias() = A * B; + * \endcode + * because the result matrix A is also an operand of the matrix product. Therefore, + * there is no alternative than evaluating A * B in a temporary, that is the default + * behavior when you write: + * \code + * A = A * B; + * \endcode + * + * \sa class NoAlias + */ +template +NoAlias MatrixBase::noalias() +{ + return NoAlias(derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_NOALIAS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NumTraits.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NumTraits.h new file mode 100644 index 0000000000000000000000000000000000000000..daf48987898f7a38e27b996515e9da44a8d4a7ef --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/NumTraits.h @@ -0,0 +1,248 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_NUMTRAITS_H +#define EIGEN_NUMTRAITS_H + +namespace Eigen { + +namespace internal { + +// default implementation of digits10(), based on numeric_limits if specialized, +// 0 for integer types, and log10(epsilon()) otherwise. +template< typename T, + bool use_numeric_limits = std::numeric_limits::is_specialized, + bool is_integer = NumTraits::IsInteger> +struct default_digits10_impl +{ + static int run() { return std::numeric_limits::digits10; } +}; + +template +struct default_digits10_impl // Floating point +{ + static int run() { + using std::log10; + using std::ceil; + typedef typename NumTraits::Real Real; + return int(ceil(-log10(NumTraits::epsilon()))); + } +}; + +template +struct default_digits10_impl // Integer +{ + static int run() { return 0; } +}; + +} // end namespace internal + +/** \class NumTraits + * \ingroup Core_Module + * + * \brief Holds information about the various numeric (i.e. scalar) types allowed by Eigen. + * + * \tparam T the numeric type at hand + * + * This class stores enums, typedefs and static methods giving information about a numeric type. + * + * The provided data consists of: + * \li A typedef \c Real, giving the "real part" type of \a T. If \a T is already real, + * then \c Real is just a typedef to \a T. If \a T is \c std::complex then \c Real + * is a typedef to \a U. + * \li A typedef \c NonInteger, giving the type that should be used for operations producing non-integral values, + * such as quotients, square roots, etc. If \a T is a floating-point type, then this typedef just gives + * \a T again. Note however that many Eigen functions such as internal::sqrt simply refuse to + * take integers. Outside of a few cases, Eigen doesn't do automatic type promotion. Thus, this typedef is + * only intended as a helper for code that needs to explicitly promote types. + * \li A typedef \c Literal giving the type to use for numeric literals such as "2" or "0.5". For instance, for \c std::complex, Literal is defined as \c U. + * Of course, this type must be fully compatible with \a T. In doubt, just use \a T here. + * \li A typedef \a Nested giving the type to use to nest a value inside of the expression tree. If you don't know what + * this means, just use \a T here. + * \li An enum value \a IsComplex. It is equal to 1 if \a T is a \c std::complex + * type, and to 0 otherwise. + * \li An enum value \a IsInteger. It is equal to \c 1 if \a T is an integer type such as \c int, + * and to \c 0 otherwise. + * \li Enum values ReadCost, AddCost and MulCost representing a rough estimate of the number of CPU cycles needed + * to by move / add / mul instructions respectively, assuming the data is already stored in CPU registers. + * Stay vague here. No need to do architecture-specific stuff. + * \li An enum value \a IsSigned. It is equal to \c 1 if \a T is a signed type and to 0 if \a T is unsigned. + * \li An enum value \a RequireInitialization. It is equal to \c 1 if the constructor of the numeric type \a T must + * be called, and to 0 if it is safe not to call it. Default is 0 if \a T is an arithmetic type, and 1 otherwise. + * \li An epsilon() function which, unlike std::numeric_limits::epsilon(), + * it returns a \a Real instead of a \a T. + * \li A dummy_precision() function returning a weak epsilon value. It is mainly used as a default + * value by the fuzzy comparison operators. + * \li highest() and lowest() functions returning the highest and lowest possible values respectively. + * \li digits10() function returning the number of decimal digits that can be represented without change. This is + * the analogue of std::numeric_limits::digits10 + * which is used as the default implementation if specialized. + */ + +template struct GenericNumTraits +{ + enum { + IsInteger = std::numeric_limits::is_integer, + IsSigned = std::numeric_limits::is_signed, + IsComplex = 0, + RequireInitialization = internal::is_arithmetic::value ? 0 : 1, + ReadCost = 1, + AddCost = 1, + MulCost = 1 + }; + + typedef T Real; + typedef typename internal::conditional< + IsInteger, + typename internal::conditional::type, + T + >::type NonInteger; + typedef T Nested; + typedef T Literal; + + EIGEN_DEVICE_FUNC + static inline Real epsilon() + { + return numext::numeric_limits::epsilon(); + } + + EIGEN_DEVICE_FUNC + static inline int digits10() + { + return internal::default_digits10_impl::run(); + } + + EIGEN_DEVICE_FUNC + static inline Real dummy_precision() + { + // make sure to override this for floating-point types + return Real(0); + } + + + EIGEN_DEVICE_FUNC + static inline T highest() { + return (numext::numeric_limits::max)(); + } + + EIGEN_DEVICE_FUNC + static inline T lowest() { + return IsInteger ? (numext::numeric_limits::min)() : (-(numext::numeric_limits::max)()); + } + + EIGEN_DEVICE_FUNC + static inline T infinity() { + return numext::numeric_limits::infinity(); + } + + EIGEN_DEVICE_FUNC + static inline T quiet_NaN() { + return numext::numeric_limits::quiet_NaN(); + } +}; + +template struct NumTraits : GenericNumTraits +{}; + +template<> struct NumTraits + : GenericNumTraits +{ + EIGEN_DEVICE_FUNC + static inline float dummy_precision() { return 1e-5f; } +}; + +template<> struct NumTraits : GenericNumTraits +{ + EIGEN_DEVICE_FUNC + static inline double dummy_precision() { return 1e-12; } +}; + +template<> struct NumTraits + : GenericNumTraits +{ + static inline long double dummy_precision() { return 1e-15l; } +}; + +template struct NumTraits > + : GenericNumTraits > +{ + typedef _Real Real; + typedef typename NumTraits<_Real>::Literal Literal; + enum { + IsComplex = 1, + RequireInitialization = NumTraits<_Real>::RequireInitialization, + ReadCost = 2 * NumTraits<_Real>::ReadCost, + AddCost = 2 * NumTraits::AddCost, + MulCost = 4 * NumTraits::MulCost + 2 * NumTraits::AddCost + }; + + EIGEN_DEVICE_FUNC + static inline Real epsilon() { return NumTraits::epsilon(); } + EIGEN_DEVICE_FUNC + static inline Real dummy_precision() { return NumTraits::dummy_precision(); } + EIGEN_DEVICE_FUNC + static inline int digits10() { return NumTraits::digits10(); } +}; + +template +struct NumTraits > +{ + typedef Array ArrayType; + typedef typename NumTraits::Real RealScalar; + typedef Array Real; + typedef typename NumTraits::NonInteger NonIntegerScalar; + typedef Array NonInteger; + typedef ArrayType & Nested; + typedef typename NumTraits::Literal Literal; + + enum { + IsComplex = NumTraits::IsComplex, + IsInteger = NumTraits::IsInteger, + IsSigned = NumTraits::IsSigned, + RequireInitialization = 1, + ReadCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * NumTraits::ReadCost, + AddCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * NumTraits::AddCost, + MulCost = ArrayType::SizeAtCompileTime==Dynamic ? HugeCost : ArrayType::SizeAtCompileTime * NumTraits::MulCost + }; + + EIGEN_DEVICE_FUNC + static inline RealScalar epsilon() { return NumTraits::epsilon(); } + EIGEN_DEVICE_FUNC + static inline RealScalar dummy_precision() { return NumTraits::dummy_precision(); } + + static inline int digits10() { return NumTraits::digits10(); } +}; + +template<> struct NumTraits + : GenericNumTraits +{ + enum { + RequireInitialization = 1, + ReadCost = HugeCost, + AddCost = HugeCost, + MulCost = HugeCost + }; + + static inline int digits10() { return 0; } + +private: + static inline std::string epsilon(); + static inline std::string dummy_precision(); + static inline std::string lowest(); + static inline std::string highest(); + static inline std::string infinity(); + static inline std::string quiet_NaN(); +}; + +// Empty specialization for void to allow template specialization based on NumTraits::Real with T==void and SFINAE. +template<> struct NumTraits {}; + +} // end namespace Eigen + +#endif // EIGEN_NUMTRAITS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PermutationMatrix.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PermutationMatrix.h new file mode 100644 index 0000000000000000000000000000000000000000..b1fb455b98c236588e5069a7fa18c3d64eeb71c5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PermutationMatrix.h @@ -0,0 +1,633 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Benoit Jacob +// Copyright (C) 2009-2015 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PERMUTATIONMATRIX_H +#define EIGEN_PERMUTATIONMATRIX_H + +namespace Eigen { + +namespace internal { + +enum PermPermProduct_t {PermPermProduct}; + +} // end namespace internal + +/** \class PermutationBase + * \ingroup Core_Module + * + * \brief Base class for permutations + * + * \tparam Derived the derived class + * + * This class is the base class for all expressions representing a permutation matrix, + * internally stored as a vector of integers. + * The convention followed here is that if \f$ \sigma \f$ is a permutation, the corresponding permutation matrix + * \f$ P_\sigma \f$ is such that if \f$ (e_1,\ldots,e_p) \f$ is the canonical basis, we have: + * \f[ P_\sigma(e_i) = e_{\sigma(i)}. \f] + * This convention ensures that for any two permutations \f$ \sigma, \tau \f$, we have: + * \f[ P_{\sigma\circ\tau} = P_\sigma P_\tau. \f] + * + * Permutation matrices are square and invertible. + * + * Notice that in addition to the member functions and operators listed here, there also are non-member + * operator* to multiply any kind of permutation object with any kind of matrix expression (MatrixBase) + * on either side. + * + * \sa class PermutationMatrix, class PermutationWrapper + */ +template +class PermutationBase : public EigenBase +{ + typedef internal::traits Traits; + typedef EigenBase Base; + public: + + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + enum { + Flags = Traits::Flags, + RowsAtCompileTime = Traits::RowsAtCompileTime, + ColsAtCompileTime = Traits::ColsAtCompileTime, + MaxRowsAtCompileTime = Traits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = Traits::MaxColsAtCompileTime + }; + typedef typename Traits::StorageIndex StorageIndex; + typedef Matrix + DenseMatrixType; + typedef PermutationMatrix + PlainPermutationType; + typedef PlainPermutationType PlainObject; + using Base::derived; + typedef Inverse InverseReturnType; + typedef void Scalar; + #endif + + /** Copies the other permutation into *this */ + template + Derived& operator=(const PermutationBase& other) + { + indices() = other.indices(); + return derived(); + } + + /** Assignment from the Transpositions \a tr */ + template + Derived& operator=(const TranspositionsBase& tr) + { + setIdentity(tr.size()); + for(Index k=size()-1; k>=0; --k) + applyTranspositionOnTheRight(k,tr.coeff(k)); + return derived(); + } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + Derived& operator=(const PermutationBase& other) + { + indices() = other.indices(); + return derived(); + } + #endif + + /** \returns the number of rows */ + inline Index rows() const { return Index(indices().size()); } + + /** \returns the number of columns */ + inline Index cols() const { return Index(indices().size()); } + + /** \returns the size of a side of the respective square matrix, i.e., the number of indices */ + inline Index size() const { return Index(indices().size()); } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + void evalTo(MatrixBase& other) const + { + other.setZero(); + for (Index i=0; i=0 && j>=0 && i=0 && j>=0 && i + void assignTranspose(const PermutationBase& other) + { + for (Index i=0; i + void assignProduct(const Lhs& lhs, const Rhs& rhs) + { + eigen_assert(lhs.cols() == rhs.rows()); + for (Index i=0; i + inline PlainPermutationType operator*(const PermutationBase& other) const + { return PlainPermutationType(internal::PermPermProduct, derived(), other.derived()); } + + /** \returns the product of a permutation with another inverse permutation. + * + * \note \blank \note_try_to_help_rvo + */ + template + inline PlainPermutationType operator*(const InverseImpl& other) const + { return PlainPermutationType(internal::PermPermProduct, *this, other.eval()); } + + /** \returns the product of an inverse permutation with another permutation. + * + * \note \blank \note_try_to_help_rvo + */ + template friend + inline PlainPermutationType operator*(const InverseImpl& other, const PermutationBase& perm) + { return PlainPermutationType(internal::PermPermProduct, other.eval(), perm); } + + /** \returns the determinant of the permutation matrix, which is either 1 or -1 depending on the parity of the permutation. + * + * This function is O(\c n) procedure allocating a buffer of \c n booleans. + */ + Index determinant() const + { + Index res = 1; + Index n = size(); + Matrix mask(n); + mask.fill(false); + Index r = 0; + while(r < n) + { + // search for the next seed + while(r=n) + break; + // we got one, let's follow it until we are back to the seed + Index k0 = r++; + mask.coeffRef(k0) = true; + for(Index k=indices().coeff(k0); k!=k0; k=indices().coeff(k)) + { + mask.coeffRef(k) = true; + res = -res; + } + } + return res; + } + + protected: + +}; + +namespace internal { +template +struct traits > + : traits > +{ + typedef PermutationStorage StorageKind; + typedef Matrix<_StorageIndex, SizeAtCompileTime, 1, 0, MaxSizeAtCompileTime, 1> IndicesType; + typedef _StorageIndex StorageIndex; + typedef void Scalar; +}; +} + +/** \class PermutationMatrix + * \ingroup Core_Module + * + * \brief Permutation matrix + * + * \tparam SizeAtCompileTime the number of rows/cols, or Dynamic + * \tparam MaxSizeAtCompileTime the maximum number of rows/cols, or Dynamic. This optional parameter defaults to SizeAtCompileTime. Most of the time, you should not have to specify it. + * \tparam _StorageIndex the integer type of the indices + * + * This class represents a permutation matrix, internally stored as a vector of integers. + * + * \sa class PermutationBase, class PermutationWrapper, class DiagonalMatrix + */ +template +class PermutationMatrix : public PermutationBase > +{ + typedef PermutationBase Base; + typedef internal::traits Traits; + public: + + typedef const PermutationMatrix& Nested; + + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + typedef typename Traits::StorageIndex StorageIndex; + #endif + + inline PermutationMatrix() + {} + + /** Constructs an uninitialized permutation matrix of given size. + */ + explicit inline PermutationMatrix(Index size) : m_indices(size) + { + eigen_internal_assert(size <= NumTraits::highest()); + } + + /** Copy constructor. */ + template + inline PermutationMatrix(const PermutationBase& other) + : m_indices(other.indices()) {} + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** Standard copy constructor. Defined only to prevent a default copy constructor + * from hiding the other templated constructor */ + inline PermutationMatrix(const PermutationMatrix& other) : m_indices(other.indices()) {} + #endif + + /** Generic constructor from expression of the indices. The indices + * array has the meaning that the permutations sends each integer i to indices[i]. + * + * \warning It is your responsibility to check that the indices array that you passes actually + * describes a permutation, i.e., each value between 0 and n-1 occurs exactly once, where n is the + * array's size. + */ + template + explicit inline PermutationMatrix(const MatrixBase& indices) : m_indices(indices) + {} + + /** Convert the Transpositions \a tr to a permutation matrix */ + template + explicit PermutationMatrix(const TranspositionsBase& tr) + : m_indices(tr.size()) + { + *this = tr; + } + + /** Copies the other permutation into *this */ + template + PermutationMatrix& operator=(const PermutationBase& other) + { + m_indices = other.indices(); + return *this; + } + + /** Assignment from the Transpositions \a tr */ + template + PermutationMatrix& operator=(const TranspositionsBase& tr) + { + return Base::operator=(tr.derived()); + } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + PermutationMatrix& operator=(const PermutationMatrix& other) + { + m_indices = other.m_indices; + return *this; + } + #endif + + /** const version of indices(). */ + const IndicesType& indices() const { return m_indices; } + /** \returns a reference to the stored array representing the permutation. */ + IndicesType& indices() { return m_indices; } + + + /**** multiplication helpers to hopefully get RVO ****/ + +#ifndef EIGEN_PARSED_BY_DOXYGEN + template + PermutationMatrix(const InverseImpl& other) + : m_indices(other.derived().nestedExpression().size()) + { + eigen_internal_assert(m_indices.size() <= NumTraits::highest()); + StorageIndex end = StorageIndex(m_indices.size()); + for (StorageIndex i=0; i + PermutationMatrix(internal::PermPermProduct_t, const Lhs& lhs, const Rhs& rhs) + : m_indices(lhs.indices().size()) + { + Base::assignProduct(lhs,rhs); + } +#endif + + protected: + + IndicesType m_indices; +}; + + +namespace internal { +template +struct traits,_PacketAccess> > + : traits > +{ + typedef PermutationStorage StorageKind; + typedef Map, _PacketAccess> IndicesType; + typedef _StorageIndex StorageIndex; + typedef void Scalar; +}; +} + +template +class Map,_PacketAccess> + : public PermutationBase,_PacketAccess> > +{ + typedef PermutationBase Base; + typedef internal::traits Traits; + public: + + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + typedef typename IndicesType::Scalar StorageIndex; + #endif + + inline Map(const StorageIndex* indicesPtr) + : m_indices(indicesPtr) + {} + + inline Map(const StorageIndex* indicesPtr, Index size) + : m_indices(indicesPtr,size) + {} + + /** Copies the other permutation into *this */ + template + Map& operator=(const PermutationBase& other) + { return Base::operator=(other.derived()); } + + /** Assignment from the Transpositions \a tr */ + template + Map& operator=(const TranspositionsBase& tr) + { return Base::operator=(tr.derived()); } + + #ifndef EIGEN_PARSED_BY_DOXYGEN + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + Map& operator=(const Map& other) + { + m_indices = other.m_indices; + return *this; + } + #endif + + /** const version of indices(). */ + const IndicesType& indices() const { return m_indices; } + /** \returns a reference to the stored array representing the permutation. */ + IndicesType& indices() { return m_indices; } + + protected: + + IndicesType m_indices; +}; + +template class TranspositionsWrapper; +namespace internal { +template +struct traits > +{ + typedef PermutationStorage StorageKind; + typedef void Scalar; + typedef typename _IndicesType::Scalar StorageIndex; + typedef _IndicesType IndicesType; + enum { + RowsAtCompileTime = _IndicesType::SizeAtCompileTime, + ColsAtCompileTime = _IndicesType::SizeAtCompileTime, + MaxRowsAtCompileTime = IndicesType::MaxSizeAtCompileTime, + MaxColsAtCompileTime = IndicesType::MaxSizeAtCompileTime, + Flags = 0 + }; +}; +} + +/** \class PermutationWrapper + * \ingroup Core_Module + * + * \brief Class to view a vector of integers as a permutation matrix + * + * \tparam _IndicesType the type of the vector of integer (can be any compatible expression) + * + * This class allows to view any vector expression of integers as a permutation matrix. + * + * \sa class PermutationBase, class PermutationMatrix + */ +template +class PermutationWrapper : public PermutationBase > +{ + typedef PermutationBase Base; + typedef internal::traits Traits; + public: + + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename Traits::IndicesType IndicesType; + #endif + + inline PermutationWrapper(const IndicesType& indices) + : m_indices(indices) + {} + + /** const version of indices(). */ + const typename internal::remove_all::type& + indices() const { return m_indices; } + + protected: + + typename IndicesType::Nested m_indices; +}; + + +/** \returns the matrix with the permutation applied to the columns. + */ +template +EIGEN_DEVICE_FUNC +const Product +operator*(const MatrixBase &matrix, + const PermutationBase& permutation) +{ + return Product + (matrix.derived(), permutation.derived()); +} + +/** \returns the matrix with the permutation applied to the rows. + */ +template +EIGEN_DEVICE_FUNC +const Product +operator*(const PermutationBase &permutation, + const MatrixBase& matrix) +{ + return Product + (permutation.derived(), matrix.derived()); +} + + +template +class InverseImpl + : public EigenBase > +{ + typedef typename PermutationType::PlainPermutationType PlainPermutationType; + typedef internal::traits PermTraits; + protected: + InverseImpl() {} + public: + typedef Inverse InverseType; + using EigenBase >::derived; + + #ifndef EIGEN_PARSED_BY_DOXYGEN + typedef typename PermutationType::DenseMatrixType DenseMatrixType; + enum { + RowsAtCompileTime = PermTraits::RowsAtCompileTime, + ColsAtCompileTime = PermTraits::ColsAtCompileTime, + MaxRowsAtCompileTime = PermTraits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = PermTraits::MaxColsAtCompileTime + }; + #endif + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + void evalTo(MatrixBase& other) const + { + other.setZero(); + for (Index i=0; i friend + const Product + operator*(const MatrixBase& matrix, const InverseType& trPerm) + { + return Product(matrix.derived(), trPerm.derived()); + } + + /** \returns the matrix with the inverse permutation applied to the rows. + */ + template + const Product + operator*(const MatrixBase& matrix) const + { + return Product(derived(), matrix.derived()); + } +}; + +template +const PermutationWrapper MatrixBase::asPermutation() const +{ + return derived(); +} + +namespace internal { + +template<> struct AssignmentKind { typedef EigenBase2EigenBase Kind; }; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_PERMUTATIONMATRIX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PlainObjectBase.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PlainObjectBase.h new file mode 100644 index 0000000000000000000000000000000000000000..1dc7e223af4b79f157bb0d0ee7952940f987b275 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/PlainObjectBase.h @@ -0,0 +1,1035 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2009 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_DENSESTORAGEBASE_H +#define EIGEN_DENSESTORAGEBASE_H + +#if defined(EIGEN_INITIALIZE_MATRICES_BY_ZERO) +# define EIGEN_INITIALIZE_COEFFS +# define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED for(int i=0;i::quiet_NaN(); +#else +# undef EIGEN_INITIALIZE_COEFFS +# define EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED +#endif + +namespace Eigen { + +namespace internal { + +template struct check_rows_cols_for_overflow { + template + EIGEN_DEVICE_FUNC + static EIGEN_ALWAYS_INLINE void run(Index, Index) + { + } +}; + +template<> struct check_rows_cols_for_overflow { + template + EIGEN_DEVICE_FUNC + static EIGEN_ALWAYS_INLINE void run(Index rows, Index cols) + { + // http://hg.mozilla.org/mozilla-central/file/6c8a909977d3/xpcom/ds/CheckedInt.h#l242 + // we assume Index is signed + Index max_index = (std::size_t(1) << (8 * sizeof(Index) - 1)) - 1; // assume Index is signed + bool error = (rows == 0 || cols == 0) ? false + : (rows > max_index / cols); + if (error) + throw_std_bad_alloc(); + } +}; + +template +struct conservative_resize_like_impl; + +template struct matrix_swap_impl; + +} // end namespace internal + +#ifdef EIGEN_PARSED_BY_DOXYGEN +namespace doxygen { + +// This is a workaround to doxygen not being able to understand the inheritance logic +// when it is hidden by the dense_xpr_base helper struct. +// Moreover, doxygen fails to include members that are not documented in the declaration body of +// MatrixBase if we inherits MatrixBase >, +// this is why we simply inherits MatrixBase, though this does not make sense. + +/** This class is just a workaround for Doxygen and it does not not actually exist. */ +template struct dense_xpr_base_dispatcher; +/** This class is just a workaround for Doxygen and it does not not actually exist. */ +template +struct dense_xpr_base_dispatcher > + : public MatrixBase {}; +/** This class is just a workaround for Doxygen and it does not not actually exist. */ +template +struct dense_xpr_base_dispatcher > + : public ArrayBase {}; + +} // namespace doxygen + +/** \class PlainObjectBase + * \ingroup Core_Module + * \brief %Dense storage base class for matrices and arrays. + * + * This class can be extended with the help of the plugin mechanism described on the page + * \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_PLAINOBJECTBASE_PLUGIN. + * + * \tparam Derived is the derived type, e.g., a Matrix or Array + * + * \sa \ref TopicClassHierarchy + */ +template +class PlainObjectBase : public doxygen::dense_xpr_base_dispatcher +#else +template +class PlainObjectBase : public internal::dense_xpr_base::type +#endif +{ + public: + enum { Options = internal::traits::Options }; + typedef typename internal::dense_xpr_base::type Base; + + typedef typename internal::traits::StorageKind StorageKind; + typedef typename internal::traits::Scalar Scalar; + + typedef typename internal::packet_traits::type PacketScalar; + typedef typename NumTraits::Real RealScalar; + typedef Derived DenseType; + + using Base::RowsAtCompileTime; + using Base::ColsAtCompileTime; + using Base::SizeAtCompileTime; + using Base::MaxRowsAtCompileTime; + using Base::MaxColsAtCompileTime; + using Base::MaxSizeAtCompileTime; + using Base::IsVectorAtCompileTime; + using Base::Flags; + + template friend class Eigen::Map; + friend class Eigen::Map; + typedef Eigen::Map MapType; + friend class Eigen::Map; + typedef const Eigen::Map ConstMapType; +#if EIGEN_MAX_ALIGN_BYTES>0 + // for EIGEN_MAX_ALIGN_BYTES==0, AlignedMax==Unaligned, and many compilers generate warnings for friend-ing a class twice. + friend class Eigen::Map; + friend class Eigen::Map; +#endif + typedef Eigen::Map AlignedMapType; + typedef const Eigen::Map ConstAlignedMapType; + template struct StridedMapType { typedef Eigen::Map type; }; + template struct StridedConstMapType { typedef Eigen::Map type; }; + template struct StridedAlignedMapType { typedef Eigen::Map type; }; + template struct StridedConstAlignedMapType { typedef Eigen::Map type; }; + + protected: + DenseStorage m_storage; + + public: + enum { NeedsToAlign = (SizeAtCompileTime != Dynamic) && (internal::traits::Alignment>0) }; + EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign) + + EIGEN_DEVICE_FUNC + Base& base() { return *static_cast(this); } + EIGEN_DEVICE_FUNC + const Base& base() const { return *static_cast(this); } + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index rows() const { return m_storage.rows(); } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Index cols() const { return m_storage.cols(); } + + /** This is an overloaded version of DenseCoeffsBase::coeff(Index,Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeff(Index) const for details. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeff(Index rowId, Index colId) const + { + if(Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } + + /** This is an overloaded version of DenseCoeffsBase::coeff(Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeff(Index) const for details. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeff(Index index) const + { + return m_storage.data()[index]; + } + + /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index,Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeffRef(Index,Index) const for details. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index rowId, Index colId) + { + if(Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } + + /** This is an overloaded version of DenseCoeffsBase::coeffRef(Index) const + * provided to by-pass the creation of an evaluator of the expression, thus saving compilation efforts. + * + * See DenseCoeffsBase::coeffRef(Index) const for details. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Scalar& coeffRef(Index index) + { + return m_storage.data()[index]; + } + + /** This is the const version of coeffRef(Index,Index) which is thus synonym of coeff(Index,Index). + * It is provided for convenience. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeffRef(Index rowId, Index colId) const + { + if(Flags & RowMajorBit) + return m_storage.data()[colId + rowId * m_storage.cols()]; + else // column-major + return m_storage.data()[rowId + colId * m_storage.rows()]; + } + + /** This is the const version of coeffRef(Index) which is thus synonym of coeff(Index). + * It is provided for convenience. */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE const Scalar& coeffRef(Index index) const + { + return m_storage.data()[index]; + } + + /** \internal */ + template + EIGEN_STRONG_INLINE PacketScalar packet(Index rowId, Index colId) const + { + return internal::ploadt + (m_storage.data() + (Flags & RowMajorBit + ? colId + rowId * m_storage.cols() + : rowId + colId * m_storage.rows())); + } + + /** \internal */ + template + EIGEN_STRONG_INLINE PacketScalar packet(Index index) const + { + return internal::ploadt(m_storage.data() + index); + } + + /** \internal */ + template + EIGEN_STRONG_INLINE void writePacket(Index rowId, Index colId, const PacketScalar& val) + { + internal::pstoret + (m_storage.data() + (Flags & RowMajorBit + ? colId + rowId * m_storage.cols() + : rowId + colId * m_storage.rows()), val); + } + + /** \internal */ + template + EIGEN_STRONG_INLINE void writePacket(Index index, const PacketScalar& val) + { + internal::pstoret(m_storage.data() + index, val); + } + + /** \returns a const pointer to the data array of this matrix */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar *data() const + { return m_storage.data(); } + + /** \returns a pointer to the data array of this matrix */ + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar *data() + { return m_storage.data(); } + + /** Resizes \c *this to a \a rows x \a cols matrix. + * + * This method is intended for dynamic-size matrices, although it is legal to call it on any + * matrix as long as fixed dimensions are left unchanged. If you only want to change the number + * of rows and/or of columns, you can use resize(NoChange_t, Index), resize(Index, NoChange_t). + * + * If the current number of coefficients of \c *this exactly matches the + * product \a rows * \a cols, then no memory allocation is performed and + * the current values are left unchanged. In all other cases, including + * shrinking, the data is reallocated and all previous values are lost. + * + * Example: \include Matrix_resize_int_int.cpp + * Output: \verbinclude Matrix_resize_int_int.out + * + * \sa resize(Index) for vectors, resize(NoChange_t, Index), resize(Index, NoChange_t) + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void resize(Index rows, Index cols) + { + eigen_assert( EIGEN_IMPLIES(RowsAtCompileTime!=Dynamic,rows==RowsAtCompileTime) + && EIGEN_IMPLIES(ColsAtCompileTime!=Dynamic,cols==ColsAtCompileTime) + && EIGEN_IMPLIES(RowsAtCompileTime==Dynamic && MaxRowsAtCompileTime!=Dynamic,rows<=MaxRowsAtCompileTime) + && EIGEN_IMPLIES(ColsAtCompileTime==Dynamic && MaxColsAtCompileTime!=Dynamic,cols<=MaxColsAtCompileTime) + && rows>=0 && cols>=0 && "Invalid sizes when resizing a matrix or array."); + internal::check_rows_cols_for_overflow::run(rows, cols); + #ifdef EIGEN_INITIALIZE_COEFFS + Index size = rows*cols; + bool size_changed = size != this->size(); + m_storage.resize(size, rows, cols); + if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + #else + m_storage.resize(rows*cols, rows, cols); + #endif + } + + /** Resizes \c *this to a vector of length \a size + * + * \only_for_vectors. This method does not work for + * partially dynamic matrices when the static dimension is anything other + * than 1. For example it will not work with Matrix. + * + * Example: \include Matrix_resize_int.cpp + * Output: \verbinclude Matrix_resize_int.out + * + * \sa resize(Index,Index), resize(NoChange_t, Index), resize(Index, NoChange_t) + */ + EIGEN_DEVICE_FUNC + inline void resize(Index size) + { + EIGEN_STATIC_ASSERT_VECTOR_ONLY(PlainObjectBase) + eigen_assert(((SizeAtCompileTime == Dynamic && (MaxSizeAtCompileTime==Dynamic || size<=MaxSizeAtCompileTime)) || SizeAtCompileTime == size) && size>=0); + #ifdef EIGEN_INITIALIZE_COEFFS + bool size_changed = size != this->size(); + #endif + if(RowsAtCompileTime == 1) + m_storage.resize(size, 1, size); + else + m_storage.resize(size, size, 1); + #ifdef EIGEN_INITIALIZE_COEFFS + if(size_changed) EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + #endif + } + + /** Resizes the matrix, changing only the number of columns. For the parameter of type NoChange_t, just pass the special value \c NoChange + * as in the example below. + * + * Example: \include Matrix_resize_NoChange_int.cpp + * Output: \verbinclude Matrix_resize_NoChange_int.out + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC + inline void resize(NoChange_t, Index cols) + { + resize(rows(), cols); + } + + /** Resizes the matrix, changing only the number of rows. For the parameter of type NoChange_t, just pass the special value \c NoChange + * as in the example below. + * + * Example: \include Matrix_resize_int_NoChange.cpp + * Output: \verbinclude Matrix_resize_int_NoChange.out + * + * \sa resize(Index,Index) + */ + EIGEN_DEVICE_FUNC + inline void resize(Index rows, NoChange_t) + { + resize(rows, cols()); + } + + /** Resizes \c *this to have the same dimensions as \a other. + * Takes care of doing all the checking that's needed. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void resizeLike(const EigenBase& _other) + { + const OtherDerived& other = _other.derived(); + internal::check_rows_cols_for_overflow::run(other.rows(), other.cols()); + const Index othersize = other.rows()*other.cols(); + if(RowsAtCompileTime == 1) + { + eigen_assert(other.rows() == 1 || other.cols() == 1); + resize(1, othersize); + } + else if(ColsAtCompileTime == 1) + { + eigen_assert(other.rows() == 1 || other.cols() == 1); + resize(othersize, 1); + } + else resize(other.rows(), other.cols()); + } + + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * The method is intended for matrices of dynamic size. If you only want to change the number + * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or + * conservativeResize(Index, NoChange_t). + * + * Matrices are resized relative to the top-left element. In case values need to be + * appended to the matrix they will be uninitialized. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void conservativeResize(Index rows, Index cols) + { + internal::conservative_resize_like_impl::run(*this, rows, cols); + } + + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * As opposed to conservativeResize(Index rows, Index cols), this version leaves + * the number of columns unchanged. + * + * In case the matrix is growing, new rows will be uninitialized. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void conservativeResize(Index rows, NoChange_t) + { + // Note: see the comment in conservativeResize(Index,Index) + conservativeResize(rows, cols()); + } + + /** Resizes the matrix to \a rows x \a cols while leaving old values untouched. + * + * As opposed to conservativeResize(Index rows, Index cols), this version leaves + * the number of rows unchanged. + * + * In case the matrix is growing, new columns will be uninitialized. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void conservativeResize(NoChange_t, Index cols) + { + // Note: see the comment in conservativeResize(Index,Index) + conservativeResize(rows(), cols); + } + + /** Resizes the vector to \a size while retaining old values. + * + * \only_for_vectors. This method does not work for + * partially dynamic matrices when the static dimension is anything other + * than 1. For example it will not work with Matrix. + * + * When values are appended, they will be uninitialized. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void conservativeResize(Index size) + { + internal::conservative_resize_like_impl::run(*this, size); + } + + /** Resizes the matrix to \a rows x \a cols of \c other, while leaving old values untouched. + * + * The method is intended for matrices of dynamic size. If you only want to change the number + * of rows and/or of columns, you can use conservativeResize(NoChange_t, Index) or + * conservativeResize(Index, NoChange_t). + * + * Matrices are resized relative to the top-left element. In case values need to be + * appended to the matrix they will copied from \c other. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void conservativeResizeLike(const DenseBase& other) + { + internal::conservative_resize_like_impl::run(*this, other); + } + + /** This is a special case of the templated operator=. Its purpose is to + * prevent a default operator= from hiding the templated operator=. + */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& operator=(const PlainObjectBase& other) + { + return _set(other); + } + + /** \sa MatrixBase::lazyAssign() */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& lazyAssign(const DenseBase& other) + { + _resize_to_match(other); + return Base::lazyAssign(other.derived()); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& operator=(const ReturnByValue& func) + { + resize(func.rows(), func.cols()); + return Base::operator=(func); + } + + // Prevent user from trying to instantiate PlainObjectBase objects + // by making all its constructor protected. See bug 1074. + protected: + + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase() : m_storage() + { +// _check_template_params(); +// EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } + +#ifndef EIGEN_PARSED_BY_DOXYGEN + // FIXME is it still needed ? + /** \internal */ + EIGEN_DEVICE_FUNC + explicit PlainObjectBase(internal::constructor_without_unaligned_array_assert) + : m_storage(internal::constructor_without_unaligned_array_assert()) + { +// _check_template_params(); EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } +#endif + +#if EIGEN_HAS_RVALUE_REFERENCES + EIGEN_DEVICE_FUNC + PlainObjectBase(PlainObjectBase&& other) EIGEN_NOEXCEPT + : m_storage( std::move(other.m_storage) ) + { + } + + EIGEN_DEVICE_FUNC + PlainObjectBase& operator=(PlainObjectBase&& other) EIGEN_NOEXCEPT + { + using std::swap; + swap(m_storage, other.m_storage); + return *this; + } +#endif + + /** Copy constructor */ + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase(const PlainObjectBase& other) + : Base(), m_storage(other.m_storage) { } + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase(Index size, Index rows, Index cols) + : m_storage(size, rows, cols) + { +// _check_template_params(); +// EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED + } + + /** \sa PlainObjectBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase(const DenseBase &other) + : m_storage() + { + _check_template_params(); + resizeLike(other); + _set_noalias(other); + } + + /** \sa PlainObjectBase::operator=(const EigenBase&) */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase(const EigenBase &other) + : m_storage() + { + _check_template_params(); + resizeLike(other); + *this = other.derived(); + } + /** \brief Copy constructor with in-place evaluation */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE PlainObjectBase(const ReturnByValue& other) + { + _check_template_params(); + // FIXME this does not automatically transpose vectors if necessary + resize(other.rows(), other.cols()); + other.evalTo(this->derived()); + } + + public: + + /** \brief Copies the generic expression \a other into *this. + * \copydetails DenseBase::operator=(const EigenBase &other) + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& operator=(const EigenBase &other) + { + _resize_to_match(other); + Base::operator=(other.derived()); + return this->derived(); + } + + /** \name Map + * These are convenience functions returning Map objects. The Map() static functions return unaligned Map objects, + * while the AlignedMap() functions return aligned Map objects and thus should be called only with 16-byte-aligned + * \a data pointers. + * + * Here is an example using strides: + * \include Matrix_Map_stride.cpp + * Output: \verbinclude Matrix_Map_stride.out + * + * \see class Map + */ + //@{ + static inline ConstMapType Map(const Scalar* data) + { return ConstMapType(data); } + static inline MapType Map(Scalar* data) + { return MapType(data); } + static inline ConstMapType Map(const Scalar* data, Index size) + { return ConstMapType(data, size); } + static inline MapType Map(Scalar* data, Index size) + { return MapType(data, size); } + static inline ConstMapType Map(const Scalar* data, Index rows, Index cols) + { return ConstMapType(data, rows, cols); } + static inline MapType Map(Scalar* data, Index rows, Index cols) + { return MapType(data, rows, cols); } + + static inline ConstAlignedMapType MapAligned(const Scalar* data) + { return ConstAlignedMapType(data); } + static inline AlignedMapType MapAligned(Scalar* data) + { return AlignedMapType(data); } + static inline ConstAlignedMapType MapAligned(const Scalar* data, Index size) + { return ConstAlignedMapType(data, size); } + static inline AlignedMapType MapAligned(Scalar* data, Index size) + { return AlignedMapType(data, size); } + static inline ConstAlignedMapType MapAligned(const Scalar* data, Index rows, Index cols) + { return ConstAlignedMapType(data, rows, cols); } + static inline AlignedMapType MapAligned(Scalar* data, Index rows, Index cols) + { return AlignedMapType(data, rows, cols); } + + template + static inline typename StridedConstMapType >::type Map(const Scalar* data, const Stride& stride) + { return typename StridedConstMapType >::type(data, stride); } + template + static inline typename StridedMapType >::type Map(Scalar* data, const Stride& stride) + { return typename StridedMapType >::type(data, stride); } + template + static inline typename StridedConstMapType >::type Map(const Scalar* data, Index size, const Stride& stride) + { return typename StridedConstMapType >::type(data, size, stride); } + template + static inline typename StridedMapType >::type Map(Scalar* data, Index size, const Stride& stride) + { return typename StridedMapType >::type(data, size, stride); } + template + static inline typename StridedConstMapType >::type Map(const Scalar* data, Index rows, Index cols, const Stride& stride) + { return typename StridedConstMapType >::type(data, rows, cols, stride); } + template + static inline typename StridedMapType >::type Map(Scalar* data, Index rows, Index cols, const Stride& stride) + { return typename StridedMapType >::type(data, rows, cols, stride); } + + template + static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, const Stride& stride) + { return typename StridedConstAlignedMapType >::type(data, stride); } + template + static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, const Stride& stride) + { return typename StridedAlignedMapType >::type(data, stride); } + template + static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, Index size, const Stride& stride) + { return typename StridedConstAlignedMapType >::type(data, size, stride); } + template + static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, Index size, const Stride& stride) + { return typename StridedAlignedMapType >::type(data, size, stride); } + template + static inline typename StridedConstAlignedMapType >::type MapAligned(const Scalar* data, Index rows, Index cols, const Stride& stride) + { return typename StridedConstAlignedMapType >::type(data, rows, cols, stride); } + template + static inline typename StridedAlignedMapType >::type MapAligned(Scalar* data, Index rows, Index cols, const Stride& stride) + { return typename StridedAlignedMapType >::type(data, rows, cols, stride); } + //@} + + using Base::setConstant; + EIGEN_DEVICE_FUNC Derived& setConstant(Index size, const Scalar& val); + EIGEN_DEVICE_FUNC Derived& setConstant(Index rows, Index cols, const Scalar& val); + + using Base::setZero; + EIGEN_DEVICE_FUNC Derived& setZero(Index size); + EIGEN_DEVICE_FUNC Derived& setZero(Index rows, Index cols); + + using Base::setOnes; + EIGEN_DEVICE_FUNC Derived& setOnes(Index size); + EIGEN_DEVICE_FUNC Derived& setOnes(Index rows, Index cols); + + using Base::setRandom; + Derived& setRandom(Index size); + Derived& setRandom(Index rows, Index cols); + + #ifdef EIGEN_PLAINOBJECTBASE_PLUGIN + #include EIGEN_PLAINOBJECTBASE_PLUGIN + #endif + + protected: + /** \internal Resizes *this in preparation for assigning \a other to it. + * Takes care of doing all the checking that's needed. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _resize_to_match(const EigenBase& other) + { + #ifdef EIGEN_NO_AUTOMATIC_RESIZING + eigen_assert((this->size()==0 || (IsVectorAtCompileTime ? (this->size() == other.size()) + : (rows() == other.rows() && cols() == other.cols()))) + && "Size mismatch. Automatic resizing is disabled because EIGEN_NO_AUTOMATIC_RESIZING is defined"); + EIGEN_ONLY_USED_FOR_DEBUG(other); + #else + resizeLike(other); + #endif + } + + /** + * \brief Copies the value of the expression \a other into \c *this with automatic resizing. + * + * *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized), + * it will be initialized. + * + * Note that copying a row-vector into a vector (and conversely) is allowed. + * The resizing, if any, is then done in the appropriate way so that row-vectors + * remain row-vectors and vectors remain vectors. + * + * \sa operator=(const MatrixBase&), _set_noalias() + * + * \internal + */ + // aliasing is dealt once in internall::call_assignment + // so at this stage we have to assume aliasing... and resising has to be done later. + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& _set(const DenseBase& other) + { + internal::call_assignment(this->derived(), other.derived()); + return this->derived(); + } + + /** \internal Like _set() but additionally makes the assumption that no aliasing effect can happen (which + * is the case when creating a new matrix) so one can enforce lazy evaluation. + * + * \sa operator=(const MatrixBase&), _set() + */ + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE Derived& _set_noalias(const DenseBase& other) + { + // I don't think we need this resize call since the lazyAssign will anyways resize + // and lazyAssign will be called by the assign selector. + //_resize_to_match(other); + // the 'false' below means to enforce lazy evaluation. We don't use lazyAssign() because + // it wouldn't allow to copy a row-vector into a column-vector. + internal::call_assignment_no_alias(this->derived(), other.derived(), internal::assign_op()); + return this->derived(); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init2(Index rows, Index cols, typename internal::enable_if::type* = 0) + { + EIGEN_STATIC_ASSERT(bool(NumTraits::IsInteger) && + bool(NumTraits::IsInteger), + FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED) + resize(rows,cols); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init2(const T0& val0, const T1& val1, typename internal::enable_if::type* = 0) + { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) + m_storage.data()[0] = Scalar(val0); + m_storage.data()[1] = Scalar(val1); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init2(const Index& val0, const Index& val1, + typename internal::enable_if< (!internal::is_same::value) + && (internal::is_same::value) + && (internal::is_same::value) + && Base::SizeAtCompileTime==2,T1>::type* = 0) + { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 2) + m_storage.data()[0] = Scalar(val0); + m_storage.data()[1] = Scalar(val1); + } + + // The argument is convertible to the Index type and we either have a non 1x1 Matrix, or a dynamic-sized Array, + // then the argument is meant to be the size of the object. + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(Index size, typename internal::enable_if< (Base::SizeAtCompileTime!=1 || !internal::is_convertible::value) + && ((!internal::is_same::XprKind,ArrayXpr>::value || Base::SizeAtCompileTime==Dynamic)),T>::type* = 0) + { + // NOTE MSVC 2008 complains if we directly put bool(NumTraits::IsInteger) as the EIGEN_STATIC_ASSERT argument. + const bool is_integer = NumTraits::IsInteger; + EIGEN_UNUSED_VARIABLE(is_integer); + EIGEN_STATIC_ASSERT(is_integer, + FLOATING_POINT_ARGUMENT_PASSED__INTEGER_WAS_EXPECTED) + resize(size); + } + + // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar type can be implicitely converted) + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Scalar& val0, typename internal::enable_if::value,T>::type* = 0) + { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) + m_storage.data()[0] = val0; + } + + // We have a 1x1 matrix/array => the argument is interpreted as the value of the unique coefficient (case where scalar type match the index type) + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Index& val0, + typename internal::enable_if< (!internal::is_same::value) + && (internal::is_same::value) + && Base::SizeAtCompileTime==1 + && internal::is_convertible::value,T*>::type* = 0) + { + EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(PlainObjectBase, 1) + m_storage.data()[0] = Scalar(val0); + } + + // Initialize a fixed size matrix from a pointer to raw data + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Scalar* data){ + this->_set_noalias(ConstMapType(data)); + } + + // Initialize an arbitrary matrix from a dense expression + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const DenseBase& other){ + this->_set_noalias(other); + } + + // Initialize an arbitrary matrix from an object convertible to the Derived type. + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Derived& other){ + this->_set_noalias(other); + } + + // Initialize an arbitrary matrix from a generic Eigen expression + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const EigenBase& other){ + this->derived() = other; + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const ReturnByValue& other) + { + resize(other.rows(), other.cols()); + other.evalTo(this->derived()); + } + + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const RotationBase& r) + { + this->derived() = r; + } + + // For fixed-size Array + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Scalar& val0, + typename internal::enable_if< Base::SizeAtCompileTime!=Dynamic + && Base::SizeAtCompileTime!=1 + && internal::is_convertible::value + && internal::is_same::XprKind,ArrayXpr>::value,T>::type* = 0) + { + Base::setConstant(val0); + } + + // For fixed-size Array + template + EIGEN_DEVICE_FUNC + EIGEN_STRONG_INLINE void _init1(const Index& val0, + typename internal::enable_if< (!internal::is_same::value) + && (internal::is_same::value) + && Base::SizeAtCompileTime!=Dynamic + && Base::SizeAtCompileTime!=1 + && internal::is_convertible::value + && internal::is_same::XprKind,ArrayXpr>::value,T*>::type* = 0) + { + Base::setConstant(val0); + } + + template + friend struct internal::matrix_swap_impl; + + public: + +#ifndef EIGEN_PARSED_BY_DOXYGEN + /** \internal + * \brief Override DenseBase::swap() since for dynamic-sized matrices + * of same type it is enough to swap the data pointers. + */ + template + EIGEN_DEVICE_FUNC + void swap(DenseBase & other) + { + enum { SwapPointers = internal::is_same::value && Base::SizeAtCompileTime==Dynamic }; + internal::matrix_swap_impl::run(this->derived(), other.derived()); + } + + /** \internal + * \brief const version forwarded to DenseBase::swap + */ + template + EIGEN_DEVICE_FUNC + void swap(DenseBase const & other) + { Base::swap(other.derived()); } + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE void _check_template_params() + { + EIGEN_STATIC_ASSERT((EIGEN_IMPLIES(MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1, (Options&RowMajor)==RowMajor) + && EIGEN_IMPLIES(MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1, (Options&RowMajor)==0) + && ((RowsAtCompileTime == Dynamic) || (RowsAtCompileTime >= 0)) + && ((ColsAtCompileTime == Dynamic) || (ColsAtCompileTime >= 0)) + && ((MaxRowsAtCompileTime == Dynamic) || (MaxRowsAtCompileTime >= 0)) + && ((MaxColsAtCompileTime == Dynamic) || (MaxColsAtCompileTime >= 0)) + && (MaxRowsAtCompileTime == RowsAtCompileTime || RowsAtCompileTime==Dynamic) + && (MaxColsAtCompileTime == ColsAtCompileTime || ColsAtCompileTime==Dynamic) + && (Options & (DontAlign|RowMajor)) == Options), + INVALID_MATRIX_TEMPLATE_PARAMETERS) + } + + enum { IsPlainObjectBase = 1 }; +#endif +}; + +namespace internal { + +template +struct conservative_resize_like_impl +{ + static void run(DenseBase& _this, Index rows, Index cols) + { + if (_this.rows() == rows && _this.cols() == cols) return; + EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(Derived) + + if ( ( Derived::IsRowMajor && _this.cols() == cols) || // row-major and we change only the number of rows + (!Derived::IsRowMajor && _this.rows() == rows) ) // column-major and we change only the number of columns + { + internal::check_rows_cols_for_overflow::run(rows, cols); + _this.derived().m_storage.conservativeResize(rows*cols,rows,cols); + } + else + { + // The storage order does not allow us to use reallocation. + typename Derived::PlainObject tmp(rows,cols); + const Index common_rows = numext::mini(rows, _this.rows()); + const Index common_cols = numext::mini(cols, _this.cols()); + tmp.block(0,0,common_rows,common_cols) = _this.block(0,0,common_rows,common_cols); + _this.derived().swap(tmp); + } + } + + static void run(DenseBase& _this, const DenseBase& other) + { + if (_this.rows() == other.rows() && _this.cols() == other.cols()) return; + + // Note: Here is space for improvement. Basically, for conservativeResize(Index,Index), + // neither RowsAtCompileTime or ColsAtCompileTime must be Dynamic. If only one of the + // dimensions is dynamic, one could use either conservativeResize(Index rows, NoChange_t) or + // conservativeResize(NoChange_t, Index cols). For these methods new static asserts like + // EIGEN_STATIC_ASSERT_DYNAMIC_ROWS and EIGEN_STATIC_ASSERT_DYNAMIC_COLS would be good. + EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(Derived) + EIGEN_STATIC_ASSERT_DYNAMIC_SIZE(OtherDerived) + + if ( ( Derived::IsRowMajor && _this.cols() == other.cols()) || // row-major and we change only the number of rows + (!Derived::IsRowMajor && _this.rows() == other.rows()) ) // column-major and we change only the number of columns + { + const Index new_rows = other.rows() - _this.rows(); + const Index new_cols = other.cols() - _this.cols(); + _this.derived().m_storage.conservativeResize(other.size(),other.rows(),other.cols()); + if (new_rows>0) + _this.bottomRightCorner(new_rows, other.cols()) = other.bottomRows(new_rows); + else if (new_cols>0) + _this.bottomRightCorner(other.rows(), new_cols) = other.rightCols(new_cols); + } + else + { + // The storage order does not allow us to use reallocation. + typename Derived::PlainObject tmp(other); + const Index common_rows = numext::mini(tmp.rows(), _this.rows()); + const Index common_cols = numext::mini(tmp.cols(), _this.cols()); + tmp.block(0,0,common_rows,common_cols) = _this.block(0,0,common_rows,common_cols); + _this.derived().swap(tmp); + } + } +}; + +// Here, the specialization for vectors inherits from the general matrix case +// to allow calling .conservativeResize(rows,cols) on vectors. +template +struct conservative_resize_like_impl + : conservative_resize_like_impl +{ + using conservative_resize_like_impl::run; + + static void run(DenseBase& _this, Index size) + { + const Index new_rows = Derived::RowsAtCompileTime==1 ? 1 : size; + const Index new_cols = Derived::RowsAtCompileTime==1 ? size : 1; + _this.derived().m_storage.conservativeResize(size,new_rows,new_cols); + } + + static void run(DenseBase& _this, const DenseBase& other) + { + if (_this.rows() == other.rows() && _this.cols() == other.cols()) return; + + const Index num_new_elements = other.size() - _this.size(); + + const Index new_rows = Derived::RowsAtCompileTime==1 ? 1 : other.rows(); + const Index new_cols = Derived::RowsAtCompileTime==1 ? other.cols() : 1; + _this.derived().m_storage.conservativeResize(other.size(),new_rows,new_cols); + + if (num_new_elements > 0) + _this.tail(num_new_elements) = other.tail(num_new_elements); + } +}; + +template +struct matrix_swap_impl +{ + EIGEN_DEVICE_FUNC + static inline void run(MatrixTypeA& a, MatrixTypeB& b) + { + a.base().swap(b); + } +}; + +template +struct matrix_swap_impl +{ + EIGEN_DEVICE_FUNC + static inline void run(MatrixTypeA& a, MatrixTypeB& b) + { + static_cast(a).m_storage.swap(static_cast(b).m_storage); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_DENSESTORAGEBASE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Product.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Product.h new file mode 100644 index 0000000000000000000000000000000000000000..676c48027792c944027c01ed4abff90cbffb09d6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Product.h @@ -0,0 +1,186 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2011 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_PRODUCT_H +#define EIGEN_PRODUCT_H + +namespace Eigen { + +template class ProductImpl; + +namespace internal { + +template +struct traits > +{ + typedef typename remove_all::type LhsCleaned; + typedef typename remove_all::type RhsCleaned; + typedef traits LhsTraits; + typedef traits RhsTraits; + + typedef MatrixXpr XprKind; + + typedef typename ScalarBinaryOpTraits::Scalar, typename traits::Scalar>::ReturnType Scalar; + typedef typename product_promote_storage_type::ret>::ret StorageKind; + typedef typename promote_index_type::type StorageIndex; + + enum { + RowsAtCompileTime = LhsTraits::RowsAtCompileTime, + ColsAtCompileTime = RhsTraits::ColsAtCompileTime, + MaxRowsAtCompileTime = LhsTraits::MaxRowsAtCompileTime, + MaxColsAtCompileTime = RhsTraits::MaxColsAtCompileTime, + + // FIXME: only needed by GeneralMatrixMatrixTriangular + InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsTraits::ColsAtCompileTime, RhsTraits::RowsAtCompileTime), + + // The storage order is somewhat arbitrary here. The correct one will be determined through the evaluator. + Flags = (MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1) ? RowMajorBit + : (MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1) ? 0 + : ( ((LhsTraits::Flags&NoPreferredStorageOrderBit) && (RhsTraits::Flags&RowMajorBit)) + || ((RhsTraits::Flags&NoPreferredStorageOrderBit) && (LhsTraits::Flags&RowMajorBit)) ) ? RowMajorBit + : NoPreferredStorageOrderBit + }; +}; + +} // end namespace internal + +/** \class Product + * \ingroup Core_Module + * + * \brief Expression of the product of two arbitrary matrices or vectors + * + * \tparam _Lhs the type of the left-hand side expression + * \tparam _Rhs the type of the right-hand side expression + * + * This class represents an expression of the product of two arbitrary matrices. + * + * The other template parameters are: + * \tparam Option can be DefaultProduct, AliasFreeProduct, or LazyProduct + * + */ +template +class Product : public ProductImpl<_Lhs,_Rhs,Option, + typename internal::product_promote_storage_type::StorageKind, + typename internal::traits<_Rhs>::StorageKind, + internal::product_type<_Lhs,_Rhs>::ret>::ret> +{ + public: + + typedef _Lhs Lhs; + typedef _Rhs Rhs; + + typedef typename ProductImpl< + Lhs, Rhs, Option, + typename internal::product_promote_storage_type::StorageKind, + typename internal::traits::StorageKind, + internal::product_type::ret>::ret>::Base Base; + EIGEN_GENERIC_PUBLIC_INTERFACE(Product) + + typedef typename internal::ref_selector::type LhsNested; + typedef typename internal::ref_selector::type RhsNested; + typedef typename internal::remove_all::type LhsNestedCleaned; + typedef typename internal::remove_all::type RhsNestedCleaned; + + EIGEN_DEVICE_FUNC Product(const Lhs& lhs, const Rhs& rhs) : m_lhs(lhs), m_rhs(rhs) + { + eigen_assert(lhs.cols() == rhs.rows() + && "invalid matrix product" + && "if you wanted a coeff-wise or a dot product use the respective explicit functions"); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index rows() const { return m_lhs.rows(); } + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Index cols() const { return m_rhs.cols(); } + + EIGEN_DEVICE_FUNC const LhsNestedCleaned& lhs() const { return m_lhs; } + EIGEN_DEVICE_FUNC const RhsNestedCleaned& rhs() const { return m_rhs; } + + protected: + + LhsNested m_lhs; + RhsNested m_rhs; +}; + +namespace internal { + +template::ret> +class dense_product_base + : public internal::dense_xpr_base >::type +{}; + +/** Convertion to scalar for inner-products */ +template +class dense_product_base + : public internal::dense_xpr_base >::type +{ + typedef Product ProductXpr; + typedef typename internal::dense_xpr_base::type Base; +public: + using Base::derived; + typedef typename Base::Scalar Scalar; + + EIGEN_STRONG_INLINE operator const Scalar() const + { + return internal::evaluator(derived()).coeff(0,0); + } +}; + +} // namespace internal + +// Generic API dispatcher +template +class ProductImpl : public internal::generic_xpr_base, MatrixXpr, StorageKind>::type +{ + public: + typedef typename internal::generic_xpr_base, MatrixXpr, StorageKind>::type Base; +}; + +template +class ProductImpl + : public internal::dense_product_base +{ + typedef Product Derived; + + public: + + typedef typename internal::dense_product_base Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Derived) + protected: + enum { + IsOneByOne = (RowsAtCompileTime == 1 || RowsAtCompileTime == Dynamic) && + (ColsAtCompileTime == 1 || ColsAtCompileTime == Dynamic), + EnableCoeff = IsOneByOne || Option==LazyProduct + }; + + public: + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index row, Index col) const + { + EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); + eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) ); + + return internal::evaluator(derived()).coeff(row,col); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Scalar coeff(Index i) const + { + EIGEN_STATIC_ASSERT(EnableCoeff, THIS_METHOD_IS_ONLY_FOR_INNER_OR_LAZY_PRODUCTS); + eigen_assert( (Option==LazyProduct) || (this->rows() == 1 && this->cols() == 1) ); + + return internal::evaluator(derived()).coeff(i); + } + + +}; + +} // end namespace Eigen + +#endif // EIGEN_PRODUCT_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ProductEvaluators.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ProductEvaluators.h new file mode 100644 index 0000000000000000000000000000000000000000..9b99bd769620bc35f68d2aeebecb0301fcdf9506 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ProductEvaluators.h @@ -0,0 +1,1112 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2008-2010 Gael Guennebaud +// Copyright (C) 2011 Jitse Niesen +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#ifndef EIGEN_PRODUCTEVALUATORS_H +#define EIGEN_PRODUCTEVALUATORS_H + +namespace Eigen { + +namespace internal { + +/** \internal + * Evaluator of a product expression. + * Since products require special treatments to handle all possible cases, + * we simply deffer the evaluation logic to a product_evaluator class + * which offers more partial specialization possibilities. + * + * \sa class product_evaluator + */ +template +struct evaluator > + : public product_evaluator > +{ + typedef Product XprType; + typedef product_evaluator Base; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) : Base(xpr) {} +}; + +// Catch "scalar * ( A * B )" and transform it to "(A*scalar) * B" +// TODO we should apply that rule only if that's really helpful +template +struct evaluator_assume_aliasing, + const CwiseNullaryOp, Plain1>, + const Product > > +{ + static const bool value = true; +}; +template +struct evaluator, + const CwiseNullaryOp, Plain1>, + const Product > > + : public evaluator > +{ + typedef CwiseBinaryOp, + const CwiseNullaryOp, Plain1>, + const Product > XprType; + typedef evaluator > Base; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) + : Base(xpr.lhs().functor().m_other * xpr.rhs().lhs() * xpr.rhs().rhs()) + {} +}; + + +template +struct evaluator, DiagIndex> > + : public evaluator, DiagIndex> > +{ + typedef Diagonal, DiagIndex> XprType; + typedef evaluator, DiagIndex> > Base; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE explicit evaluator(const XprType& xpr) + : Base(Diagonal, DiagIndex>( + Product(xpr.nestedExpression().lhs(), xpr.nestedExpression().rhs()), + xpr.index() )) + {} +}; + + +// Helper class to perform a matrix product with the destination at hand. +// Depending on the sizes of the factors, there are different evaluation strategies +// as controlled by internal::product_type. +template< typename Lhs, typename Rhs, + typename LhsShape = typename evaluator_traits::Shape, + typename RhsShape = typename evaluator_traits::Shape, + int ProductType = internal::product_type::value> +struct generic_product_impl; + +template +struct evaluator_assume_aliasing > { + static const bool value = true; +}; + +// This is the default evaluator implementation for products: +// It creates a temporary and call generic_product_impl +template +struct product_evaluator, ProductTag, LhsShape, RhsShape> + : public evaluator::PlainObject> +{ + typedef Product XprType; + typedef typename XprType::PlainObject PlainObject; + typedef evaluator Base; + enum { + Flags = Base::Flags | EvalBeforeNestingBit + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + explicit product_evaluator(const XprType& xpr) + : m_result(xpr.rows(), xpr.cols()) + { + ::new (static_cast(this)) Base(m_result); + +// FIXME shall we handle nested_eval here?, +// if so, then we must take care at removing the call to nested_eval in the specializations (e.g., in permutation_matrix_product, transposition_matrix_product, etc.) +// typedef typename internal::nested_eval::type LhsNested; +// typedef typename internal::nested_eval::type RhsNested; +// typedef typename internal::remove_all::type LhsNestedCleaned; +// typedef typename internal::remove_all::type RhsNestedCleaned; +// +// const LhsNested lhs(xpr.lhs()); +// const RhsNested rhs(xpr.rhs()); +// +// generic_product_impl::evalTo(m_result, lhs, rhs); + + generic_product_impl::evalTo(m_result, xpr.lhs(), xpr.rhs()); + } + +protected: + PlainObject m_result; +}; + +// The following three shortcuts are enabled only if the scalar types match excatly. +// TODO: we could enable them for different scalar types when the product is not vectorized. + +// Dense = Product +template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> +struct Assignment, internal::assign_op, Dense2Dense, + typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> +{ + typedef Product SrcXprType; + static EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const internal::assign_op &) + { + Index dstRows = src.rows(); + Index dstCols = src.cols(); + if((dst.rows()!=dstRows) || (dst.cols()!=dstCols)) + dst.resize(dstRows, dstCols); + // FIXME shall we handle nested_eval here? + generic_product_impl::evalTo(dst, src.lhs(), src.rhs()); + } +}; + +// Dense += Product +template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> +struct Assignment, internal::add_assign_op, Dense2Dense, + typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> +{ + typedef Product SrcXprType; + static EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const internal::add_assign_op &) + { + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); + // FIXME shall we handle nested_eval here? + generic_product_impl::addTo(dst, src.lhs(), src.rhs()); + } +}; + +// Dense -= Product +template< typename DstXprType, typename Lhs, typename Rhs, int Options, typename Scalar> +struct Assignment, internal::sub_assign_op, Dense2Dense, + typename enable_if<(Options==DefaultProduct || Options==AliasFreeProduct)>::type> +{ + typedef Product SrcXprType; + static EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const internal::sub_assign_op &) + { + eigen_assert(dst.rows() == src.rows() && dst.cols() == src.cols()); + // FIXME shall we handle nested_eval here? + generic_product_impl::subTo(dst, src.lhs(), src.rhs()); + } +}; + + +// Dense ?= scalar * Product +// TODO we should apply that rule if that's really helpful +// for instance, this is not good for inner products +template< typename DstXprType, typename Lhs, typename Rhs, typename AssignFunc, typename Scalar, typename ScalarBis, typename Plain> +struct Assignment, const CwiseNullaryOp,Plain>, + const Product >, AssignFunc, Dense2Dense> +{ + typedef CwiseBinaryOp, + const CwiseNullaryOp,Plain>, + const Product > SrcXprType; + static EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const AssignFunc& func) + { + call_assignment_no_alias(dst, (src.lhs().functor().m_other * src.rhs().lhs())*src.rhs().rhs(), func); + } +}; + +//---------------------------------------- +// Catch "Dense ?= xpr + Product<>" expression to save one temporary +// FIXME we could probably enable these rules for any product, i.e., not only Dense and DefaultProduct + +template +struct evaluator_assume_aliasing::Scalar>, const OtherXpr, + const Product >, DenseShape > { + static const bool value = true; +}; + +template +struct evaluator_assume_aliasing::Scalar>, const OtherXpr, + const Product >, DenseShape > { + static const bool value = true; +}; + +template +struct assignment_from_xpr_op_product +{ + template + static EIGEN_STRONG_INLINE + void run(DstXprType &dst, const SrcXprType &src, const InitialFunc& /*func*/) + { + call_assignment_no_alias(dst, src.lhs(), Func1()); + call_assignment_no_alias(dst, src.rhs(), Func2()); + } +}; + +#define EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(ASSIGN_OP,BINOP,ASSIGN_OP2) \ + template< typename DstXprType, typename OtherXpr, typename Lhs, typename Rhs, typename DstScalar, typename SrcScalar, typename OtherScalar,typename ProdScalar> \ + struct Assignment, const OtherXpr, \ + const Product >, internal::ASSIGN_OP, Dense2Dense> \ + : assignment_from_xpr_op_product, internal::ASSIGN_OP, internal::ASSIGN_OP2 > \ + {} + +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_sum_op,add_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op,scalar_sum_op,add_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op,scalar_sum_op,sub_assign_op); + +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(assign_op, scalar_difference_op,sub_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(add_assign_op,scalar_difference_op,sub_assign_op); +EIGEN_CATCH_ASSIGN_XPR_OP_PRODUCT(sub_assign_op,scalar_difference_op,add_assign_op); + +//---------------------------------------- + +template +struct generic_product_impl +{ + template + static EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + dst.coeffRef(0,0) = (lhs.transpose().cwiseProduct(rhs)).sum(); + } + + template + static EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + dst.coeffRef(0,0) += (lhs.transpose().cwiseProduct(rhs)).sum(); + } + + template + static EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { dst.coeffRef(0,0) -= (lhs.transpose().cwiseProduct(rhs)).sum(); } +}; + + +/*********************************************************************** +* Implementation of outer dense * dense vector product +***********************************************************************/ + +// Column major result +template +void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const false_type&) +{ + evaluator rhsEval(rhs); + typename nested_eval::type actual_lhs(lhs); + // FIXME if cols is large enough, then it might be useful to make sure that lhs is sequentially stored + // FIXME not very good if rhs is real and lhs complex while alpha is real too + const Index cols = dst.cols(); + for (Index j=0; j +void outer_product_selector_run(Dst& dst, const Lhs &lhs, const Rhs &rhs, const Func& func, const true_type&) +{ + evaluator lhsEval(lhs); + typename nested_eval::type actual_rhs(rhs); + // FIXME if rows is large enough, then it might be useful to make sure that rhs is sequentially stored + // FIXME not very good if lhs is real and rhs complex while alpha is real too + const Index rows = dst.rows(); + for (Index i=0; i +struct generic_product_impl +{ + template struct is_row_major : internal::conditional<(int(T::Flags)&RowMajorBit), internal::true_type, internal::false_type>::type {}; + typedef typename Product::Scalar Scalar; + + // TODO it would be nice to be able to exploit our *_assign_op functors for that purpose + struct set { template void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() = src; } }; + struct add { template void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() += src; } }; + struct sub { template void operator()(const Dst& dst, const Src& src) const { dst.const_cast_derived() -= src; } }; + struct adds { + Scalar m_scale; + explicit adds(const Scalar& s) : m_scale(s) {} + template void operator()(const Dst& dst, const Src& src) const { + dst.const_cast_derived() += m_scale * src; + } + }; + + template + static EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + internal::outer_product_selector_run(dst, lhs, rhs, set(), is_row_major()); + } + + template + static EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + internal::outer_product_selector_run(dst, lhs, rhs, add(), is_row_major()); + } + + template + static EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + internal::outer_product_selector_run(dst, lhs, rhs, sub(), is_row_major()); + } + + template + static EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + internal::outer_product_selector_run(dst, lhs, rhs, adds(alpha), is_row_major()); + } + +}; + + +// This base class provides default implementations for evalTo, addTo, subTo, in terms of scaleAndAddTo +template +struct generic_product_impl_base +{ + typedef typename Product::Scalar Scalar; + + template + static EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { dst.setZero(); scaleAndAddTo(dst, lhs, rhs, Scalar(1)); } + + template + static EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { scaleAndAddTo(dst,lhs, rhs, Scalar(1)); } + + template + static EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { scaleAndAddTo(dst, lhs, rhs, Scalar(-1)); } + + template + static EIGEN_STRONG_INLINE void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { Derived::scaleAndAddTo(dst,lhs,rhs,alpha); } + +}; + +template +struct generic_product_impl + : generic_product_impl_base > +{ + typedef typename nested_eval::type LhsNested; + typedef typename nested_eval::type RhsNested; + typedef typename Product::Scalar Scalar; + enum { Side = Lhs::IsVectorAtCompileTime ? OnTheLeft : OnTheRight }; + typedef typename internal::remove_all::type>::type MatrixType; + + template + static EIGEN_STRONG_INLINE void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + LhsNested actual_lhs(lhs); + RhsNested actual_rhs(rhs); + internal::gemv_dense_selector::HasUsableDirectAccess) + >::run(actual_lhs, actual_rhs, dst, alpha); + } +}; + +template +struct generic_product_impl +{ + typedef typename Product::Scalar Scalar; + + template + static EIGEN_STRONG_INLINE void evalTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + // Same as: dst.noalias() = lhs.lazyProduct(rhs); + // but easier on the compiler side + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::assign_op()); + } + + template + static EIGEN_STRONG_INLINE void addTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + // dst.noalias() += lhs.lazyProduct(rhs); + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::add_assign_op()); + } + + template + static EIGEN_STRONG_INLINE void subTo(Dst& dst, const Lhs& lhs, const Rhs& rhs) + { + // dst.noalias() -= lhs.lazyProduct(rhs); + call_assignment_no_alias(dst, lhs.lazyProduct(rhs), internal::sub_assign_op()); + } + +// template +// static inline void scaleAndAddTo(Dst& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) +// { dst.noalias() += alpha * lhs.lazyProduct(rhs); } +}; + +// This specialization enforces the use of a coefficient-based evaluation strategy +template +struct generic_product_impl + : generic_product_impl {}; + +// Case 2: Evaluate coeff by coeff +// +// This is mostly taken from CoeffBasedProduct.h +// The main difference is that we add an extra argument to the etor_product_*_impl::run() function +// for the inner dimension of the product, because evaluator object do not know their size. + +template +struct etor_product_coeff_impl; + +template +struct etor_product_packet_impl; + +template +struct product_evaluator, ProductTag, DenseShape, DenseShape> + : evaluator_base > +{ + typedef Product XprType; + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE + explicit product_evaluator(const XprType& xpr) + : m_lhs(xpr.lhs()), + m_rhs(xpr.rhs()), + m_lhsImpl(m_lhs), // FIXME the creation of the evaluator objects should result in a no-op, but check that! + m_rhsImpl(m_rhs), // Moreover, they are only useful for the packet path, so we could completely disable them when not needed, + // or perhaps declare them on the fly on the packet method... We have experiment to check what's best. + m_innerDim(xpr.lhs().cols()) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::MulCost); + EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::AddCost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); +#if 0 + std::cerr << "LhsOuterStrideBytes= " << LhsOuterStrideBytes << "\n"; + std::cerr << "RhsOuterStrideBytes= " << RhsOuterStrideBytes << "\n"; + std::cerr << "LhsAlignment= " << LhsAlignment << "\n"; + std::cerr << "RhsAlignment= " << RhsAlignment << "\n"; + std::cerr << "CanVectorizeLhs= " << CanVectorizeLhs << "\n"; + std::cerr << "CanVectorizeRhs= " << CanVectorizeRhs << "\n"; + std::cerr << "CanVectorizeInner= " << CanVectorizeInner << "\n"; + std::cerr << "EvalToRowMajor= " << EvalToRowMajor << "\n"; + std::cerr << "Alignment= " << Alignment << "\n"; + std::cerr << "Flags= " << Flags << "\n"; +#endif + } + + // Everything below here is taken from CoeffBasedProduct.h + + typedef typename internal::nested_eval::type LhsNested; + typedef typename internal::nested_eval::type RhsNested; + + typedef typename internal::remove_all::type LhsNestedCleaned; + typedef typename internal::remove_all::type RhsNestedCleaned; + + typedef evaluator LhsEtorType; + typedef evaluator RhsEtorType; + + enum { + RowsAtCompileTime = LhsNestedCleaned::RowsAtCompileTime, + ColsAtCompileTime = RhsNestedCleaned::ColsAtCompileTime, + InnerSize = EIGEN_SIZE_MIN_PREFER_FIXED(LhsNestedCleaned::ColsAtCompileTime, RhsNestedCleaned::RowsAtCompileTime), + MaxRowsAtCompileTime = LhsNestedCleaned::MaxRowsAtCompileTime, + MaxColsAtCompileTime = RhsNestedCleaned::MaxColsAtCompileTime + }; + + typedef typename find_best_packet::type LhsVecPacketType; + typedef typename find_best_packet::type RhsVecPacketType; + + enum { + + LhsCoeffReadCost = LhsEtorType::CoeffReadCost, + RhsCoeffReadCost = RhsEtorType::CoeffReadCost, + CoeffReadCost = InnerSize==0 ? NumTraits::ReadCost + : InnerSize == Dynamic ? HugeCost + : InnerSize * (NumTraits::MulCost + LhsCoeffReadCost + RhsCoeffReadCost) + + (InnerSize - 1) * NumTraits::AddCost, + + Unroll = CoeffReadCost <= EIGEN_UNROLLING_LIMIT, + + LhsFlags = LhsEtorType::Flags, + RhsFlags = RhsEtorType::Flags, + + LhsRowMajor = LhsFlags & RowMajorBit, + RhsRowMajor = RhsFlags & RowMajorBit, + + LhsVecPacketSize = unpacket_traits::size, + RhsVecPacketSize = unpacket_traits::size, + + // Here, we don't care about alignment larger than the usable packet size. + LhsAlignment = EIGEN_PLAIN_ENUM_MIN(LhsEtorType::Alignment,LhsVecPacketSize*int(sizeof(typename LhsNestedCleaned::Scalar))), + RhsAlignment = EIGEN_PLAIN_ENUM_MIN(RhsEtorType::Alignment,RhsVecPacketSize*int(sizeof(typename RhsNestedCleaned::Scalar))), + + SameType = is_same::value, + + CanVectorizeRhs = bool(RhsRowMajor) && (RhsFlags & PacketAccessBit) && (ColsAtCompileTime!=1), + CanVectorizeLhs = (!LhsRowMajor) && (LhsFlags & PacketAccessBit) && (RowsAtCompileTime!=1), + + EvalToRowMajor = (MaxRowsAtCompileTime==1&&MaxColsAtCompileTime!=1) ? 1 + : (MaxColsAtCompileTime==1&&MaxRowsAtCompileTime!=1) ? 0 + : (bool(RhsRowMajor) && !CanVectorizeLhs), + + Flags = ((unsigned int)(LhsFlags | RhsFlags) & HereditaryBits & ~RowMajorBit) + | (EvalToRowMajor ? RowMajorBit : 0) + // TODO enable vectorization for mixed types + | (SameType && (CanVectorizeLhs || CanVectorizeRhs) ? PacketAccessBit : 0) + | (XprType::IsVectorAtCompileTime ? LinearAccessBit : 0), + + LhsOuterStrideBytes = int(LhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename LhsNestedCleaned::Scalar)), + RhsOuterStrideBytes = int(RhsNestedCleaned::OuterStrideAtCompileTime) * int(sizeof(typename RhsNestedCleaned::Scalar)), + + Alignment = bool(CanVectorizeLhs) ? (LhsOuterStrideBytes<=0 || (int(LhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,LhsAlignment))!=0 ? 0 : LhsAlignment) + : bool(CanVectorizeRhs) ? (RhsOuterStrideBytes<=0 || (int(RhsOuterStrideBytes) % EIGEN_PLAIN_ENUM_MAX(1,RhsAlignment))!=0 ? 0 : RhsAlignment) + : 0, + + /* CanVectorizeInner deserves special explanation. It does not affect the product flags. It is not used outside + * of Product. If the Product itself is not a packet-access expression, there is still a chance that the inner + * loop of the product might be vectorized. This is the meaning of CanVectorizeInner. Since it doesn't affect + * the Flags, it is safe to make this value depend on ActualPacketAccessBit, that doesn't affect the ABI. + */ + CanVectorizeInner = SameType + && LhsRowMajor + && (!RhsRowMajor) + && (LhsFlags & RhsFlags & ActualPacketAccessBit) + && (InnerSize % packet_traits::size == 0) + }; + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const CoeffReturnType coeff(Index row, Index col) const + { + return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); + } + + /* Allow index-based non-packet access. It is impossible though to allow index-based packed access, + * which is why we don't set the LinearAccessBit. + * TODO: this seems possible when the result is a vector + */ + EIGEN_DEVICE_FUNC const CoeffReturnType coeff(Index index) const + { + const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? 0 : index; + const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? index : 0; + return (m_lhs.row(row).transpose().cwiseProduct( m_rhs.col(col) )).sum(); + } + + template + const PacketType packet(Index row, Index col) const + { + PacketType res; + typedef etor_product_packet_impl PacketImpl; + PacketImpl::run(row, col, m_lhsImpl, m_rhsImpl, m_innerDim, res); + return res; + } + + template + const PacketType packet(Index index) const + { + const Index row = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? 0 : index; + const Index col = (RowsAtCompileTime == 1 || MaxRowsAtCompileTime==1) ? index : 0; + return packet(row,col); + } + +protected: + typename internal::add_const_on_value_type::type m_lhs; + typename internal::add_const_on_value_type::type m_rhs; + + LhsEtorType m_lhsImpl; + RhsEtorType m_rhsImpl; + + // TODO: Get rid of m_innerDim if known at compile time + Index m_innerDim; +}; + +template +struct product_evaluator, LazyCoeffBasedProductMode, DenseShape, DenseShape> + : product_evaluator, CoeffBasedProductMode, DenseShape, DenseShape> +{ + typedef Product XprType; + typedef Product BaseProduct; + typedef product_evaluator Base; + enum { + Flags = Base::Flags | EvalBeforeNestingBit + }; + EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) + : Base(BaseProduct(xpr.lhs(),xpr.rhs())) + {} +}; + +/**************************************** +*** Coeff based product, Packet path *** +****************************************/ + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) + { + etor_product_packet_impl::run(row, col, lhs, rhs, innerDim, res); + res = pmadd(pset1(lhs.coeff(row, Index(UnrollingIndex-1))), rhs.template packet(Index(UnrollingIndex-1), col), res); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet &res) + { + etor_product_packet_impl::run(row, col, lhs, rhs, innerDim, res); + res = pmadd(lhs.template packet(row, Index(UnrollingIndex-1)), pset1(rhs.coeff(Index(UnrollingIndex-1), col)), res); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) + { + res = pmul(pset1(lhs.coeff(row, Index(0))),rhs.template packet(Index(0), col)); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index /*innerDim*/, Packet &res) + { + res = pmul(lhs.template packet(row, Index(0)), pset1(rhs.coeff(Index(0), col))); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) + { + res = pset1(typename unpacket_traits::type(0)); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index /*row*/, Index /*col*/, const Lhs& /*lhs*/, const Rhs& /*rhs*/, Index /*innerDim*/, Packet &res) + { + res = pset1(typename unpacket_traits::type(0)); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) + { + res = pset1(typename unpacket_traits::type(0)); + for(Index i = 0; i < innerDim; ++i) + res = pmadd(pset1(lhs.coeff(row, i)), rhs.template packet(i, col), res); + } +}; + +template +struct etor_product_packet_impl +{ + static EIGEN_STRONG_INLINE void run(Index row, Index col, const Lhs& lhs, const Rhs& rhs, Index innerDim, Packet& res) + { + res = pset1(typename unpacket_traits::type(0)); + for(Index i = 0; i < innerDim; ++i) + res = pmadd(lhs.template packet(row, i), pset1(rhs.coeff(i, col)), res); + } +}; + + +/*************************************************************************** +* Triangular products +***************************************************************************/ +template +struct triangular_product_impl; + +template +struct generic_product_impl + : generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + triangular_product_impl + ::run(dst, lhs.nestedExpression(), rhs, alpha); + } +}; + +template +struct generic_product_impl +: generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + triangular_product_impl::run(dst, lhs, rhs.nestedExpression(), alpha); + } +}; + + +/*************************************************************************** +* SelfAdjoint products +***************************************************************************/ +template +struct selfadjoint_product_impl; + +template +struct generic_product_impl + : generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + selfadjoint_product_impl::run(dst, lhs.nestedExpression(), rhs, alpha); + } +}; + +template +struct generic_product_impl +: generic_product_impl_base > +{ + typedef typename Product::Scalar Scalar; + + template + static void scaleAndAddTo(Dest& dst, const Lhs& lhs, const Rhs& rhs, const Scalar& alpha) + { + selfadjoint_product_impl::run(dst, lhs, rhs.nestedExpression(), alpha); + } +}; + + +/*************************************************************************** +* Diagonal products +***************************************************************************/ + +template +struct diagonal_product_evaluator_base + : evaluator_base +{ + typedef typename ScalarBinaryOpTraits::ReturnType Scalar; +public: + enum { + CoeffReadCost = NumTraits::MulCost + evaluator::CoeffReadCost + evaluator::CoeffReadCost, + + MatrixFlags = evaluator::Flags, + DiagFlags = evaluator::Flags, + _StorageOrder = MatrixFlags & RowMajorBit ? RowMajor : ColMajor, + _ScalarAccessOnDiag = !((int(_StorageOrder) == ColMajor && int(ProductOrder) == OnTheLeft) + ||(int(_StorageOrder) == RowMajor && int(ProductOrder) == OnTheRight)), + _SameTypes = is_same::value, + // FIXME currently we need same types, but in the future the next rule should be the one + //_Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && ((!_PacketOnDiag) || (_SameTypes && bool(int(DiagFlags)&PacketAccessBit))), + _Vectorizable = bool(int(MatrixFlags)&PacketAccessBit) && _SameTypes && (_ScalarAccessOnDiag || (bool(int(DiagFlags)&PacketAccessBit))), + _LinearAccessMask = (MatrixType::RowsAtCompileTime==1 || MatrixType::ColsAtCompileTime==1) ? LinearAccessBit : 0, + Flags = ((HereditaryBits|_LinearAccessMask) & (unsigned int)(MatrixFlags)) | (_Vectorizable ? PacketAccessBit : 0), + Alignment = evaluator::Alignment, + + AsScalarProduct = (DiagonalType::SizeAtCompileTime==1) + || (DiagonalType::SizeAtCompileTime==Dynamic && MatrixType::RowsAtCompileTime==1 && ProductOrder==OnTheLeft) + || (DiagonalType::SizeAtCompileTime==Dynamic && MatrixType::ColsAtCompileTime==1 && ProductOrder==OnTheRight) + }; + + diagonal_product_evaluator_base(const MatrixType &mat, const DiagonalType &diag) + : m_diagImpl(diag), m_matImpl(mat) + { + EIGEN_INTERNAL_CHECK_COST_VALUE(NumTraits::MulCost); + EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost); + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index idx) const + { + if(AsScalarProduct) + return m_diagImpl.coeff(0) * m_matImpl.coeff(idx); + else + return m_diagImpl.coeff(idx) * m_matImpl.coeff(idx); + } + +protected: + template + EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::true_type) const + { + return internal::pmul(m_matImpl.template packet(row, col), + internal::pset1(m_diagImpl.coeff(id))); + } + + template + EIGEN_STRONG_INLINE PacketType packet_impl(Index row, Index col, Index id, internal::false_type) const + { + enum { + InnerSize = (MatrixType::Flags & RowMajorBit) ? MatrixType::ColsAtCompileTime : MatrixType::RowsAtCompileTime, + DiagonalPacketLoadMode = EIGEN_PLAIN_ENUM_MIN(LoadMode,((InnerSize%16) == 0) ? int(Aligned16) : int(evaluator::Alignment)) // FIXME hardcoded 16!! + }; + return internal::pmul(m_matImpl.template packet(row, col), + m_diagImpl.template packet(id)); + } + + evaluator m_diagImpl; + evaluator m_matImpl; +}; + +// diagonal * dense +template +struct product_evaluator, ProductTag, DiagonalShape, DenseShape> + : diagonal_product_evaluator_base, OnTheLeft> +{ + typedef diagonal_product_evaluator_base, OnTheLeft> Base; + using Base::m_diagImpl; + using Base::m_matImpl; + using Base::coeff; + typedef typename Base::Scalar Scalar; + + typedef Product XprType; + typedef typename XprType::PlainObject PlainObject; + + enum { + StorageOrder = int(Rhs::Flags) & RowMajorBit ? RowMajor : ColMajor + }; + + EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) + : Base(xpr.rhs(), xpr.lhs().diagonal()) + { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const + { + return m_diagImpl.coeff(row) * m_matImpl.coeff(row, col); + } + +#ifndef __CUDACC__ + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const + { + // FIXME: NVCC used to complain about the template keyword, but we have to check whether this is still the case. + // See also similar calls below. + return this->template packet_impl(row,col, row, + typename internal::conditional::type()); + } + + template + EIGEN_STRONG_INLINE PacketType packet(Index idx) const + { + return packet(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); + } +#endif +}; + +// dense * diagonal +template +struct product_evaluator, ProductTag, DenseShape, DiagonalShape> + : diagonal_product_evaluator_base, OnTheRight> +{ + typedef diagonal_product_evaluator_base, OnTheRight> Base; + using Base::m_diagImpl; + using Base::m_matImpl; + using Base::coeff; + typedef typename Base::Scalar Scalar; + + typedef Product XprType; + typedef typename XprType::PlainObject PlainObject; + + enum { StorageOrder = int(Lhs::Flags) & RowMajorBit ? RowMajor : ColMajor }; + + EIGEN_DEVICE_FUNC explicit product_evaluator(const XprType& xpr) + : Base(xpr.lhs(), xpr.rhs().diagonal()) + { + } + + EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar coeff(Index row, Index col) const + { + return m_matImpl.coeff(row, col) * m_diagImpl.coeff(col); + } + +#ifndef __CUDACC__ + template + EIGEN_STRONG_INLINE PacketType packet(Index row, Index col) const + { + return this->template packet_impl(row,col, col, + typename internal::conditional::type()); + } + + template + EIGEN_STRONG_INLINE PacketType packet(Index idx) const + { + return packet(int(StorageOrder)==ColMajor?idx:0,int(StorageOrder)==ColMajor?0:idx); + } +#endif +}; + +/*************************************************************************** +* Products with permutation matrices +***************************************************************************/ + +/** \internal + * \class permutation_matrix_product + * Internal helper class implementing the product between a permutation matrix and a matrix. + * This class is specialized for DenseShape below and for SparseShape in SparseCore/SparsePermutation.h + */ +template +struct permutation_matrix_product; + +template +struct permutation_matrix_product +{ + typedef typename nested_eval::type MatrixType; + typedef typename remove_all::type MatrixTypeCleaned; + + template + static inline void run(Dest& dst, const PermutationType& perm, const ExpressionType& xpr) + { + MatrixType mat(xpr); + const Index n = Side==OnTheLeft ? mat.rows() : mat.cols(); + // FIXME we need an is_same for expression that is not sensitive to constness. For instance + // is_same_xpr, Block >::value should be true. + //if(is_same::value && extract_data(dst) == extract_data(mat)) + if(is_same_dense(dst, mat)) + { + // apply the permutation inplace + Matrix mask(perm.size()); + mask.fill(false); + Index r = 0; + while(r < perm.size()) + { + // search for the next seed + while(r=perm.size()) + break; + // we got one, let's follow it until we are back to the seed + Index k0 = r++; + Index kPrev = k0; + mask.coeffRef(k0) = true; + for(Index k=perm.indices().coeff(k0); k!=k0; k=perm.indices().coeff(k)) + { + Block(dst, k) + .swap(Block + (dst,((Side==OnTheLeft) ^ Transposed) ? k0 : kPrev)); + + mask.coeffRef(k) = true; + kPrev = k; + } + } + } + else + { + for(Index i = 0; i < n; ++i) + { + Block + (dst, ((Side==OnTheLeft) ^ Transposed) ? perm.indices().coeff(i) : i) + + = + + Block + (mat, ((Side==OnTheRight) ^ Transposed) ? perm.indices().coeff(i) : i); + } + } + } +}; + +template +struct generic_product_impl +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) + { + permutation_matrix_product::run(dst, lhs, rhs); + } +}; + +template +struct generic_product_impl +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) + { + permutation_matrix_product::run(dst, rhs, lhs); + } +}; + +template +struct generic_product_impl, Rhs, PermutationShape, MatrixShape, ProductTag> +{ + template + static void evalTo(Dest& dst, const Inverse& lhs, const Rhs& rhs) + { + permutation_matrix_product::run(dst, lhs.nestedExpression(), rhs); + } +}; + +template +struct generic_product_impl, MatrixShape, PermutationShape, ProductTag> +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Inverse& rhs) + { + permutation_matrix_product::run(dst, rhs.nestedExpression(), lhs); + } +}; + + +/*************************************************************************** +* Products with transpositions matrices +***************************************************************************/ + +// FIXME could we unify Transpositions and Permutation into a single "shape"?? + +/** \internal + * \class transposition_matrix_product + * Internal helper class implementing the product between a permutation matrix and a matrix. + */ +template +struct transposition_matrix_product +{ + typedef typename nested_eval::type MatrixType; + typedef typename remove_all::type MatrixTypeCleaned; + + template + static inline void run(Dest& dst, const TranspositionType& tr, const ExpressionType& xpr) + { + MatrixType mat(xpr); + typedef typename TranspositionType::StorageIndex StorageIndex; + const Index size = tr.size(); + StorageIndex j = 0; + + if(!is_same_dense(dst,mat)) + dst = mat; + + for(Index k=(Transposed?size-1:0) ; Transposed?k>=0:k +struct generic_product_impl +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) + { + transposition_matrix_product::run(dst, lhs, rhs); + } +}; + +template +struct generic_product_impl +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Rhs& rhs) + { + transposition_matrix_product::run(dst, rhs, lhs); + } +}; + + +template +struct generic_product_impl, Rhs, TranspositionsShape, MatrixShape, ProductTag> +{ + template + static void evalTo(Dest& dst, const Transpose& lhs, const Rhs& rhs) + { + transposition_matrix_product::run(dst, lhs.nestedExpression(), rhs); + } +}; + +template +struct generic_product_impl, MatrixShape, TranspositionsShape, ProductTag> +{ + template + static void evalTo(Dest& dst, const Lhs& lhs, const Transpose& rhs) + { + transposition_matrix_product::run(dst, rhs.nestedExpression(), lhs); + } +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_PRODUCT_EVALUATORS_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Random.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Random.h new file mode 100644 index 0000000000000000000000000000000000000000..6faf789c7618d90b15cbf8c8b39ca6a3b3992413 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Random.h @@ -0,0 +1,182 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_RANDOM_H +#define EIGEN_RANDOM_H + +namespace Eigen { + +namespace internal { + +template struct scalar_random_op { + EIGEN_EMPTY_STRUCT_CTOR(scalar_random_op) + inline const Scalar operator() () const { return random(); } +}; + +template +struct functor_traits > +{ enum { Cost = 5 * NumTraits::MulCost, PacketAccess = false, IsRepeatable = false }; }; + +} // end namespace internal + +/** \returns a random matrix expression + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * The parameters \a rows and \a cols are the number of rows and of columns of + * the returned matrix. Must be compatible with this MatrixBase type. + * + * \not_reentrant + * + * This variant is meant to be used for dynamic-size matrix types. For fixed-size types, + * it is redundant to pass \a rows and \a cols as arguments, so Random() should be used + * instead. + * + * + * Example: \include MatrixBase_random_int_int.cpp + * Output: \verbinclude MatrixBase_random_int_int.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * See DenseBase::NullaryExpr(Index, const CustomNullaryOp&) for an example using C++11 random generators. + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index), DenseBase::Random() + */ +template +inline const typename DenseBase::RandomReturnType +DenseBase::Random(Index rows, Index cols) +{ + return NullaryExpr(rows, cols, internal::scalar_random_op()); +} + +/** \returns a random vector expression + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * The parameter \a size is the size of the returned vector. + * Must be compatible with this MatrixBase type. + * + * \only_for_vectors + * \not_reentrant + * + * This variant is meant to be used for dynamic-size vector types. For fixed-size types, + * it is redundant to pass \a size as argument, so Random() should be used + * instead. + * + * Example: \include MatrixBase_random_int.cpp + * Output: \verbinclude MatrixBase_random_int.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary vector whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random() + */ +template +inline const typename DenseBase::RandomReturnType +DenseBase::Random(Index size) +{ + return NullaryExpr(size, internal::scalar_random_op()); +} + +/** \returns a fixed-size random matrix or vector expression + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * This variant is only for fixed-size MatrixBase types. For dynamic-size types, you + * need to use the variants taking size arguments. + * + * Example: \include MatrixBase_random.cpp + * Output: \verbinclude MatrixBase_random.out + * + * This expression has the "evaluate before nesting" flag so that it will be evaluated into + * a temporary matrix whenever it is nested in a larger expression. This prevents unexpected + * behavior with expressions involving random matrices. + * + * \not_reentrant + * + * \sa DenseBase::setRandom(), DenseBase::Random(Index,Index), DenseBase::Random(Index) + */ +template +inline const typename DenseBase::RandomReturnType +DenseBase::Random() +{ + return NullaryExpr(RowsAtCompileTime, ColsAtCompileTime, internal::scalar_random_op()); +} + +/** Sets all coefficients in this expression to random values. + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * Example: \include MatrixBase_setRandom.cpp + * Output: \verbinclude MatrixBase_setRandom.out + * + * \sa class CwiseNullaryOp, setRandom(Index), setRandom(Index,Index) + */ +template +inline Derived& DenseBase::setRandom() +{ + return *this = Random(rows(), cols()); +} + +/** Resizes to the given \a newSize, and sets all coefficients in this expression to random values. + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \only_for_vectors + * \not_reentrant + * + * Example: \include Matrix_setRandom_int.cpp + * Output: \verbinclude Matrix_setRandom_int.out + * + * \sa DenseBase::setRandom(), setRandom(Index,Index), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setRandom(Index newSize) +{ + resize(newSize); + return setRandom(); +} + +/** Resizes to the given size, and sets all coefficients in this expression to random values. + * + * Numbers are uniformly spread through their whole definition range for integer types, + * and in the [-1:1] range for floating point scalar types. + * + * \not_reentrant + * + * \param rows the new number of rows + * \param cols the new number of columns + * + * Example: \include Matrix_setRandom_int_int.cpp + * Output: \verbinclude Matrix_setRandom_int_int.out + * + * \sa DenseBase::setRandom(), setRandom(Index), class CwiseNullaryOp, DenseBase::Random() + */ +template +EIGEN_STRONG_INLINE Derived& +PlainObjectBase::setRandom(Index rows, Index cols) +{ + resize(rows, cols); + return setRandom(); +} + +} // end namespace Eigen + +#endif // EIGEN_RANDOM_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Redux.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Redux.h new file mode 100644 index 0000000000000000000000000000000000000000..760e9f86154cb7249436753d987e2d340bc40643 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Redux.h @@ -0,0 +1,505 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008 Gael Guennebaud +// Copyright (C) 2006-2008 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_REDUX_H +#define EIGEN_REDUX_H + +namespace Eigen { + +namespace internal { + +// TODO +// * implement other kind of vectorization +// * factorize code + +/*************************************************************************** +* Part 1 : the logic deciding a strategy for vectorization and unrolling +***************************************************************************/ + +template +struct redux_traits +{ +public: + typedef typename find_best_packet::type PacketType; + enum { + PacketSize = unpacket_traits::size, + InnerMaxSize = int(Derived::IsRowMajor) + ? Derived::MaxColsAtCompileTime + : Derived::MaxRowsAtCompileTime + }; + + enum { + MightVectorize = (int(Derived::Flags)&ActualPacketAccessBit) + && (functor_traits::PacketAccess), + MayLinearVectorize = bool(MightVectorize) && (int(Derived::Flags)&LinearAccessBit), + MaySliceVectorize = bool(MightVectorize) && int(InnerMaxSize)>=3*PacketSize + }; + +public: + enum { + Traversal = int(MayLinearVectorize) ? int(LinearVectorizedTraversal) + : int(MaySliceVectorize) ? int(SliceVectorizedTraversal) + : int(DefaultTraversal) + }; + +public: + enum { + Cost = Derived::SizeAtCompileTime == Dynamic ? HugeCost + : Derived::SizeAtCompileTime * Derived::CoeffReadCost + (Derived::SizeAtCompileTime-1) * functor_traits::Cost, + UnrollingLimit = EIGEN_UNROLLING_LIMIT * (int(Traversal) == int(DefaultTraversal) ? 1 : int(PacketSize)) + }; + +public: + enum { + Unrolling = Cost <= UnrollingLimit ? CompleteUnrolling : NoUnrolling + }; + +#ifdef EIGEN_DEBUG_ASSIGN + static void debug() + { + std::cerr << "Xpr: " << typeid(typename Derived::XprType).name() << std::endl; + std::cerr.setf(std::ios::hex, std::ios::basefield); + EIGEN_DEBUG_VAR(Derived::Flags) + std::cerr.unsetf(std::ios::hex); + EIGEN_DEBUG_VAR(InnerMaxSize) + EIGEN_DEBUG_VAR(PacketSize) + EIGEN_DEBUG_VAR(MightVectorize) + EIGEN_DEBUG_VAR(MayLinearVectorize) + EIGEN_DEBUG_VAR(MaySliceVectorize) + EIGEN_DEBUG_VAR(Traversal) + EIGEN_DEBUG_VAR(UnrollingLimit) + EIGEN_DEBUG_VAR(Unrolling) + std::cerr << std::endl; + } +#endif +}; + +/*************************************************************************** +* Part 2 : unrollers +***************************************************************************/ + +/*** no vectorization ***/ + +template +struct redux_novec_unroller +{ + enum { + HalfLength = Length/2 + }; + + typedef typename Derived::Scalar Scalar; + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func& func) + { + return func(redux_novec_unroller::run(mat,func), + redux_novec_unroller::run(mat,func)); + } +}; + +template +struct redux_novec_unroller +{ + enum { + outer = Start / Derived::InnerSizeAtCompileTime, + inner = Start % Derived::InnerSizeAtCompileTime + }; + + typedef typename Derived::Scalar Scalar; + + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func&) + { + return mat.coeffByOuterInner(outer, inner); + } +}; + +// This is actually dead code and will never be called. It is required +// to prevent false warnings regarding failed inlining though +// for 0 length run() will never be called at all. +template +struct redux_novec_unroller +{ + typedef typename Derived::Scalar Scalar; + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar run(const Derived&, const Func&) { return Scalar(); } +}; + +/*** vectorization ***/ + +template +struct redux_vec_unroller +{ + enum { + PacketSize = redux_traits::PacketSize, + HalfLength = Length/2 + }; + + typedef typename Derived::Scalar Scalar; + typedef typename redux_traits::PacketType PacketScalar; + + static EIGEN_STRONG_INLINE PacketScalar run(const Derived &mat, const Func& func) + { + return func.packetOp( + redux_vec_unroller::run(mat,func), + redux_vec_unroller::run(mat,func) ); + } +}; + +template +struct redux_vec_unroller +{ + enum { + index = Start * redux_traits::PacketSize, + outer = index / int(Derived::InnerSizeAtCompileTime), + inner = index % int(Derived::InnerSizeAtCompileTime), + alignment = Derived::Alignment + }; + + typedef typename Derived::Scalar Scalar; + typedef typename redux_traits::PacketType PacketScalar; + + static EIGEN_STRONG_INLINE PacketScalar run(const Derived &mat, const Func&) + { + return mat.template packetByOuterInner(outer, inner); + } +}; + +/*************************************************************************** +* Part 3 : implementation of all cases +***************************************************************************/ + +template::Traversal, + int Unrolling = redux_traits::Unrolling +> +struct redux_impl; + +template +struct redux_impl +{ + typedef typename Derived::Scalar Scalar; + EIGEN_DEVICE_FUNC + static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func& func) + { + eigen_assert(mat.rows()>0 && mat.cols()>0 && "you are using an empty matrix"); + Scalar res; + res = mat.coeffByOuterInner(0, 0); + for(Index i = 1; i < mat.innerSize(); ++i) + res = func(res, mat.coeffByOuterInner(0, i)); + for(Index i = 1; i < mat.outerSize(); ++i) + for(Index j = 0; j < mat.innerSize(); ++j) + res = func(res, mat.coeffByOuterInner(i, j)); + return res; + } +}; + +template +struct redux_impl + : public redux_novec_unroller +{}; + +template +struct redux_impl +{ + typedef typename Derived::Scalar Scalar; + typedef typename redux_traits::PacketType PacketScalar; + + static Scalar run(const Derived &mat, const Func& func) + { + const Index size = mat.size(); + + const Index packetSize = redux_traits::PacketSize; + const int packetAlignment = unpacket_traits::alignment; + enum { + alignment0 = (bool(Derived::Flags & DirectAccessBit) && bool(packet_traits::AlignedOnScalar)) ? int(packetAlignment) : int(Unaligned), + alignment = EIGEN_PLAIN_ENUM_MAX(alignment0, Derived::Alignment) + }; + const Index alignedStart = internal::first_default_aligned(mat.nestedExpression()); + const Index alignedSize2 = ((size-alignedStart)/(2*packetSize))*(2*packetSize); + const Index alignedSize = ((size-alignedStart)/(packetSize))*(packetSize); + const Index alignedEnd2 = alignedStart + alignedSize2; + const Index alignedEnd = alignedStart + alignedSize; + Scalar res; + if(alignedSize) + { + PacketScalar packet_res0 = mat.template packet(alignedStart); + if(alignedSize>packetSize) // we have at least two packets to partly unroll the loop + { + PacketScalar packet_res1 = mat.template packet(alignedStart+packetSize); + for(Index index = alignedStart + 2*packetSize; index < alignedEnd2; index += 2*packetSize) + { + packet_res0 = func.packetOp(packet_res0, mat.template packet(index)); + packet_res1 = func.packetOp(packet_res1, mat.template packet(index+packetSize)); + } + + packet_res0 = func.packetOp(packet_res0,packet_res1); + if(alignedEnd>alignedEnd2) + packet_res0 = func.packetOp(packet_res0, mat.template packet(alignedEnd2)); + } + res = func.predux(packet_res0); + + for(Index index = 0; index < alignedStart; ++index) + res = func(res,mat.coeff(index)); + + for(Index index = alignedEnd; index < size; ++index) + res = func(res,mat.coeff(index)); + } + else // too small to vectorize anything. + // since this is dynamic-size hence inefficient anyway for such small sizes, don't try to optimize. + { + res = mat.coeff(0); + for(Index index = 1; index < size; ++index) + res = func(res,mat.coeff(index)); + } + + return res; + } +}; + +// NOTE: for SliceVectorizedTraversal we simply bypass unrolling +template +struct redux_impl +{ + typedef typename Derived::Scalar Scalar; + typedef typename redux_traits::PacketType PacketType; + + EIGEN_DEVICE_FUNC static Scalar run(const Derived &mat, const Func& func) + { + eigen_assert(mat.rows()>0 && mat.cols()>0 && "you are using an empty matrix"); + const Index innerSize = mat.innerSize(); + const Index outerSize = mat.outerSize(); + enum { + packetSize = redux_traits::PacketSize + }; + const Index packetedInnerSize = ((innerSize)/packetSize)*packetSize; + Scalar res; + if(packetedInnerSize) + { + PacketType packet_res = mat.template packet(0,0); + for(Index j=0; j(j,i)); + + res = func.predux(packet_res); + for(Index j=0; j::run(mat, func); + } + + return res; + } +}; + +template +struct redux_impl +{ + typedef typename Derived::Scalar Scalar; + + typedef typename redux_traits::PacketType PacketScalar; + enum { + PacketSize = redux_traits::PacketSize, + Size = Derived::SizeAtCompileTime, + VectorizedSize = (Size / PacketSize) * PacketSize + }; + EIGEN_DEVICE_FUNC static EIGEN_STRONG_INLINE Scalar run(const Derived &mat, const Func& func) + { + eigen_assert(mat.rows()>0 && mat.cols()>0 && "you are using an empty matrix"); + if (VectorizedSize > 0) { + Scalar res = func.predux(redux_vec_unroller::run(mat,func)); + if (VectorizedSize != Size) + res = func(res,redux_novec_unroller::run(mat,func)); + return res; + } + else { + return redux_novec_unroller::run(mat,func); + } + } +}; + +// evaluator adaptor +template +class redux_evaluator +{ +public: + typedef _XprType XprType; + EIGEN_DEVICE_FUNC explicit redux_evaluator(const XprType &xpr) : m_evaluator(xpr), m_xpr(xpr) {} + + typedef typename XprType::Scalar Scalar; + typedef typename XprType::CoeffReturnType CoeffReturnType; + typedef typename XprType::PacketScalar PacketScalar; + typedef typename XprType::PacketReturnType PacketReturnType; + + enum { + MaxRowsAtCompileTime = XprType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = XprType::MaxColsAtCompileTime, + // TODO we should not remove DirectAccessBit and rather find an elegant way to query the alignment offset at runtime from the evaluator + Flags = evaluator::Flags & ~DirectAccessBit, + IsRowMajor = XprType::IsRowMajor, + SizeAtCompileTime = XprType::SizeAtCompileTime, + InnerSizeAtCompileTime = XprType::InnerSizeAtCompileTime, + CoeffReadCost = evaluator::CoeffReadCost, + Alignment = evaluator::Alignment + }; + + EIGEN_DEVICE_FUNC Index rows() const { return m_xpr.rows(); } + EIGEN_DEVICE_FUNC Index cols() const { return m_xpr.cols(); } + EIGEN_DEVICE_FUNC Index size() const { return m_xpr.size(); } + EIGEN_DEVICE_FUNC Index innerSize() const { return m_xpr.innerSize(); } + EIGEN_DEVICE_FUNC Index outerSize() const { return m_xpr.outerSize(); } + + EIGEN_DEVICE_FUNC + CoeffReturnType coeff(Index row, Index col) const + { return m_evaluator.coeff(row, col); } + + EIGEN_DEVICE_FUNC + CoeffReturnType coeff(Index index) const + { return m_evaluator.coeff(index); } + + template + PacketType packet(Index row, Index col) const + { return m_evaluator.template packet(row, col); } + + template + PacketType packet(Index index) const + { return m_evaluator.template packet(index); } + + EIGEN_DEVICE_FUNC + CoeffReturnType coeffByOuterInner(Index outer, Index inner) const + { return m_evaluator.coeff(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); } + + template + PacketType packetByOuterInner(Index outer, Index inner) const + { return m_evaluator.template packet(IsRowMajor ? outer : inner, IsRowMajor ? inner : outer); } + + const XprType & nestedExpression() const { return m_xpr; } + +protected: + internal::evaluator m_evaluator; + const XprType &m_xpr; +}; + +} // end namespace internal + +/*************************************************************************** +* Part 4 : public API +***************************************************************************/ + + +/** \returns the result of a full redux operation on the whole matrix or vector using \a func + * + * The template parameter \a BinaryOp is the type of the functor \a func which must be + * an associative operator. Both current C++98 and C++11 functor styles are handled. + * + * \sa DenseBase::sum(), DenseBase::minCoeff(), DenseBase::maxCoeff(), MatrixBase::colwise(), MatrixBase::rowwise() + */ +template +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::redux(const Func& func) const +{ + eigen_assert(this->rows()>0 && this->cols()>0 && "you are using an empty matrix"); + + typedef typename internal::redux_evaluator ThisEvaluator; + ThisEvaluator thisEval(derived()); + + return internal::redux_impl::run(thisEval, func); +} + +/** \returns the minimum of all coefficients of \c *this. + * \warning the result is undefined if \c *this contains NaN. + */ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::minCoeff() const +{ + return derived().redux(Eigen::internal::scalar_min_op()); +} + +/** \returns the maximum of all coefficients of \c *this. + * \warning the result is undefined if \c *this contains NaN. + */ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::maxCoeff() const +{ + return derived().redux(Eigen::internal::scalar_max_op()); +} + +/** \returns the sum of all coefficients of \c *this + * + * If \c *this is empty, then the value 0 is returned. + * + * \sa trace(), prod(), mean() + */ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::sum() const +{ + if(SizeAtCompileTime==0 || (SizeAtCompileTime==Dynamic && size()==0)) + return Scalar(0); + return derived().redux(Eigen::internal::scalar_sum_op()); +} + +/** \returns the mean of all coefficients of *this +* +* \sa trace(), prod(), sum() +*/ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::mean() const +{ +#ifdef __INTEL_COMPILER + #pragma warning push + #pragma warning ( disable : 2259 ) +#endif + return Scalar(derived().redux(Eigen::internal::scalar_sum_op())) / Scalar(this->size()); +#ifdef __INTEL_COMPILER + #pragma warning pop +#endif +} + +/** \returns the product of all coefficients of *this + * + * Example: \include MatrixBase_prod.cpp + * Output: \verbinclude MatrixBase_prod.out + * + * \sa sum(), mean(), trace() + */ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +DenseBase::prod() const +{ + if(SizeAtCompileTime==0 || (SizeAtCompileTime==Dynamic && size()==0)) + return Scalar(1); + return derived().redux(Eigen::internal::scalar_product_op()); +} + +/** \returns the trace of \c *this, i.e. the sum of the coefficients on the main diagonal. + * + * \c *this can be any matrix, not necessarily square. + * + * \sa diagonal(), sum() + */ +template +EIGEN_STRONG_INLINE typename internal::traits::Scalar +MatrixBase::trace() const +{ + return derived().diagonal().sum(); +} + +} // end namespace Eigen + +#endif // EIGEN_REDUX_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Ref.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Ref.h new file mode 100644 index 0000000000000000000000000000000000000000..9c6e3c5d9b012a3f26c665b17a6142847779aca5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Ref.h @@ -0,0 +1,283 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_REF_H +#define EIGEN_REF_H + +namespace Eigen { + +namespace internal { + +template +struct traits > + : public traits > +{ + typedef _PlainObjectType PlainObjectType; + typedef _StrideType StrideType; + enum { + Options = _Options, + Flags = traits >::Flags | NestByRefBit, + Alignment = traits >::Alignment + }; + + template struct match { + enum { + HasDirectAccess = internal::has_direct_access::ret, + StorageOrderMatch = PlainObjectType::IsVectorAtCompileTime || Derived::IsVectorAtCompileTime || ((PlainObjectType::Flags&RowMajorBit)==(Derived::Flags&RowMajorBit)), + InnerStrideMatch = int(StrideType::InnerStrideAtCompileTime)==int(Dynamic) + || int(StrideType::InnerStrideAtCompileTime)==int(Derived::InnerStrideAtCompileTime) + || (int(StrideType::InnerStrideAtCompileTime)==0 && int(Derived::InnerStrideAtCompileTime)==1), + OuterStrideMatch = Derived::IsVectorAtCompileTime + || int(StrideType::OuterStrideAtCompileTime)==int(Dynamic) || int(StrideType::OuterStrideAtCompileTime)==int(Derived::OuterStrideAtCompileTime), + // NOTE, this indirection of evaluator::Alignment is needed + // to workaround a very strange bug in MSVC related to the instantiation + // of has_*ary_operator in evaluator. + // This line is surprisingly very sensitive. For instance, simply adding parenthesis + // as "DerivedAlignment = (int(evaluator::Alignment))," will make MSVC fail... + DerivedAlignment = int(evaluator::Alignment), + AlignmentMatch = (int(traits::Alignment)==int(Unaligned)) || (DerivedAlignment >= int(Alignment)), // FIXME the first condition is not very clear, it should be replaced by the required alignment + ScalarTypeMatch = internal::is_same::value, + MatchAtCompileTime = HasDirectAccess && StorageOrderMatch && InnerStrideMatch && OuterStrideMatch && AlignmentMatch && ScalarTypeMatch + }; + typedef typename internal::conditional::type type; + }; + +}; + +template +struct traits > : public traits {}; + +} + +template class RefBase + : public MapBase +{ + typedef typename internal::traits::PlainObjectType PlainObjectType; + typedef typename internal::traits::StrideType StrideType; + +public: + + typedef MapBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(RefBase) + + EIGEN_DEVICE_FUNC inline Index innerStride() const + { + return StrideType::InnerStrideAtCompileTime != 0 ? m_stride.inner() : 1; + } + + EIGEN_DEVICE_FUNC inline Index outerStride() const + { + return StrideType::OuterStrideAtCompileTime != 0 ? m_stride.outer() + : IsVectorAtCompileTime ? this->size() + : int(Flags)&RowMajorBit ? this->cols() + : this->rows(); + } + + EIGEN_DEVICE_FUNC RefBase() + : Base(0,RowsAtCompileTime==Dynamic?0:RowsAtCompileTime,ColsAtCompileTime==Dynamic?0:ColsAtCompileTime), + // Stride<> does not allow default ctor for Dynamic strides, so let' initialize it with dummy values: + m_stride(StrideType::OuterStrideAtCompileTime==Dynamic?0:StrideType::OuterStrideAtCompileTime, + StrideType::InnerStrideAtCompileTime==Dynamic?0:StrideType::InnerStrideAtCompileTime) + {} + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(RefBase) + +protected: + + typedef Stride StrideBase; + + template + EIGEN_DEVICE_FUNC void construct(Expression& expr) + { + EIGEN_STATIC_ASSERT_SAME_MATRIX_SIZE(PlainObjectType,Expression); + + if(PlainObjectType::RowsAtCompileTime==1) + { + eigen_assert(expr.rows()==1 || expr.cols()==1); + ::new (static_cast(this)) Base(expr.data(), 1, expr.size()); + } + else if(PlainObjectType::ColsAtCompileTime==1) + { + eigen_assert(expr.rows()==1 || expr.cols()==1); + ::new (static_cast(this)) Base(expr.data(), expr.size(), 1); + } + else + ::new (static_cast(this)) Base(expr.data(), expr.rows(), expr.cols()); + + if(Expression::IsVectorAtCompileTime && (!PlainObjectType::IsVectorAtCompileTime) && ((Expression::Flags&RowMajorBit)!=(PlainObjectType::Flags&RowMajorBit))) + ::new (&m_stride) StrideBase(expr.innerStride(), StrideType::InnerStrideAtCompileTime==0?0:1); + else + ::new (&m_stride) StrideBase(StrideType::OuterStrideAtCompileTime==0?0:expr.outerStride(), + StrideType::InnerStrideAtCompileTime==0?0:expr.innerStride()); + } + + StrideBase m_stride; +}; + +/** \class Ref + * \ingroup Core_Module + * + * \brief A matrix or vector expression mapping an existing expression + * + * \tparam PlainObjectType the equivalent matrix type of the mapped data + * \tparam Options specifies the pointer alignment in bytes. It can be: \c #Aligned128, , \c #Aligned64, \c #Aligned32, \c #Aligned16, \c #Aligned8 or \c #Unaligned. + * The default is \c #Unaligned. + * \tparam StrideType optionally specifies strides. By default, Ref implies a contiguous storage along the inner dimension (inner stride==1), + * but accepts a variable outer stride (leading dimension). + * This can be overridden by specifying strides. + * The type passed here must be a specialization of the Stride template, see examples below. + * + * This class provides a way to write non-template functions taking Eigen objects as parameters while limiting the number of copies. + * A Ref<> object can represent either a const expression or a l-value: + * \code + * // in-out argument: + * void foo1(Ref x); + * + * // read-only const argument: + * void foo2(const Ref& x); + * \endcode + * + * In the in-out case, the input argument must satisfy the constraints of the actual Ref<> type, otherwise a compilation issue will be triggered. + * By default, a Ref can reference any dense vector expression of float having a contiguous memory layout. + * Likewise, a Ref can reference any column-major dense matrix expression of float whose column's elements are contiguously stored with + * the possibility to have a constant space in-between each column, i.e. the inner stride must be equal to 1, but the outer stride (or leading dimension) + * can be greater than the number of rows. + * + * In the const case, if the input expression does not match the above requirement, then it is evaluated into a temporary before being passed to the function. + * Here are some examples: + * \code + * MatrixXf A; + * VectorXf a; + * foo1(a.head()); // OK + * foo1(A.col()); // OK + * foo1(A.row()); // Compilation error because here innerstride!=1 + * foo2(A.row()); // Compilation error because A.row() is a 1xN object while foo2 is expecting a Nx1 object + * foo2(A.row().transpose()); // The row is copied into a contiguous temporary + * foo2(2*a); // The expression is evaluated into a temporary + * foo2(A.col().segment(2,4)); // No temporary + * \endcode + * + * The range of inputs that can be referenced without temporary can be enlarged using the last two template parameters. + * Here is an example accepting an innerstride!=1: + * \code + * // in-out argument: + * void foo3(Ref > x); + * foo3(A.row()); // OK + * \endcode + * The downside here is that the function foo3 might be significantly slower than foo1 because it won't be able to exploit vectorization, and will involve more + * expensive address computations even if the input is contiguously stored in memory. To overcome this issue, one might propose to overload internally calling a + * template function, e.g.: + * \code + * // in the .h: + * void foo(const Ref& A); + * void foo(const Ref >& A); + * + * // in the .cpp: + * template void foo_impl(const TypeOfA& A) { + * ... // crazy code goes here + * } + * void foo(const Ref& A) { foo_impl(A); } + * void foo(const Ref >& A) { foo_impl(A); } + * \endcode + * + * + * \sa PlainObjectBase::Map(), \ref TopicStorageOrders + */ +template class Ref + : public RefBase > +{ + private: + typedef internal::traits Traits; + template + EIGEN_DEVICE_FUNC inline Ref(const PlainObjectBase& expr, + typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0); + public: + + typedef RefBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Ref) + + + #ifndef EIGEN_PARSED_BY_DOXYGEN + template + EIGEN_DEVICE_FUNC inline Ref(PlainObjectBase& expr, + typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0) + { + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + Base::construct(expr.derived()); + } + template + EIGEN_DEVICE_FUNC inline Ref(const DenseBase& expr, + typename internal::enable_if::MatchAtCompileTime),Derived>::type* = 0) + #else + /** Implicit constructor from any dense expression */ + template + inline Ref(DenseBase& expr) + #endif + { + EIGEN_STATIC_ASSERT(bool(internal::is_lvalue::value), THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + EIGEN_STATIC_ASSERT(bool(Traits::template match::MatchAtCompileTime), STORAGE_LAYOUT_DOES_NOT_MATCH); + EIGEN_STATIC_ASSERT(!Derived::IsPlainObjectBase,THIS_EXPRESSION_IS_NOT_A_LVALUE__IT_IS_READ_ONLY); + Base::construct(expr.const_cast_derived()); + } + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Ref) + +}; + +// this is the const ref version +template class Ref + : public RefBase > +{ + typedef internal::traits Traits; + public: + + typedef RefBase Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Ref) + + template + EIGEN_DEVICE_FUNC inline Ref(const DenseBase& expr, + typename internal::enable_if::ScalarTypeMatch),Derived>::type* = 0) + { +// std::cout << match_helper::HasDirectAccess << "," << match_helper::OuterStrideMatch << "," << match_helper::InnerStrideMatch << "\n"; +// std::cout << int(StrideType::OuterStrideAtCompileTime) << " - " << int(Derived::OuterStrideAtCompileTime) << "\n"; +// std::cout << int(StrideType::InnerStrideAtCompileTime) << " - " << int(Derived::InnerStrideAtCompileTime) << "\n"; + construct(expr.derived(), typename Traits::template match::type()); + } + + EIGEN_DEVICE_FUNC inline Ref(const Ref& other) : Base(other) { + // copy constructor shall not copy the m_object, to avoid unnecessary malloc and copy + } + + template + EIGEN_DEVICE_FUNC inline Ref(const RefBase& other) { + construct(other.derived(), typename Traits::template match::type()); + } + + protected: + + template + EIGEN_DEVICE_FUNC void construct(const Expression& expr,internal::true_type) + { + Base::construct(expr); + } + + template + EIGEN_DEVICE_FUNC void construct(const Expression& expr, internal::false_type) + { + internal::call_assignment_no_alias(m_object,expr,internal::assign_op()); + Base::construct(m_object); + } + + protected: + TPlainObjectType m_object; +}; + +} // end namespace Eigen + +#endif // EIGEN_REF_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Replicate.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Replicate.h new file mode 100644 index 0000000000000000000000000000000000000000..9960ef884ef68f5828caa3784e2cba2b177a9594 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Replicate.h @@ -0,0 +1,142 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_REPLICATE_H +#define EIGEN_REPLICATE_H + +namespace Eigen { + +namespace internal { +template +struct traits > + : traits +{ + typedef typename MatrixType::Scalar Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::XprKind XprKind; + typedef typename ref_selector::type MatrixTypeNested; + typedef typename remove_reference::type _MatrixTypeNested; + enum { + RowsAtCompileTime = RowFactor==Dynamic || int(MatrixType::RowsAtCompileTime)==Dynamic + ? Dynamic + : RowFactor * MatrixType::RowsAtCompileTime, + ColsAtCompileTime = ColFactor==Dynamic || int(MatrixType::ColsAtCompileTime)==Dynamic + ? Dynamic + : ColFactor * MatrixType::ColsAtCompileTime, + //FIXME we don't propagate the max sizes !!! + MaxRowsAtCompileTime = RowsAtCompileTime, + MaxColsAtCompileTime = ColsAtCompileTime, + IsRowMajor = MaxRowsAtCompileTime==1 && MaxColsAtCompileTime!=1 ? 1 + : MaxColsAtCompileTime==1 && MaxRowsAtCompileTime!=1 ? 0 + : (MatrixType::Flags & RowMajorBit) ? 1 : 0, + + // FIXME enable DirectAccess with negative strides? + Flags = IsRowMajor ? RowMajorBit : 0 + }; +}; +} + +/** + * \class Replicate + * \ingroup Core_Module + * + * \brief Expression of the multiple replication of a matrix or vector + * + * \tparam MatrixType the type of the object we are replicating + * \tparam RowFactor number of repetitions at compile time along the vertical direction, can be Dynamic. + * \tparam ColFactor number of repetitions at compile time along the horizontal direction, can be Dynamic. + * + * This class represents an expression of the multiple replication of a matrix or vector. + * It is the return type of DenseBase::replicate() and most of the time + * this is the only way it is used. + * + * \sa DenseBase::replicate() + */ +template class Replicate + : public internal::dense_xpr_base< Replicate >::type +{ + typedef typename internal::traits::MatrixTypeNested MatrixTypeNested; + typedef typename internal::traits::_MatrixTypeNested _MatrixTypeNested; + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Replicate) + typedef typename internal::remove_all::type NestedExpression; + + template + EIGEN_DEVICE_FUNC + inline explicit Replicate(const OriginalMatrixType& matrix) + : m_matrix(matrix), m_rowFactor(RowFactor), m_colFactor(ColFactor) + { + EIGEN_STATIC_ASSERT((internal::is_same::type,OriginalMatrixType>::value), + THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE) + eigen_assert(RowFactor!=Dynamic && ColFactor!=Dynamic); + } + + template + EIGEN_DEVICE_FUNC + inline Replicate(const OriginalMatrixType& matrix, Index rowFactor, Index colFactor) + : m_matrix(matrix), m_rowFactor(rowFactor), m_colFactor(colFactor) + { + EIGEN_STATIC_ASSERT((internal::is_same::type,OriginalMatrixType>::value), + THE_MATRIX_OR_EXPRESSION_THAT_YOU_PASSED_DOES_NOT_HAVE_THE_EXPECTED_TYPE) + } + + EIGEN_DEVICE_FUNC + inline Index rows() const { return m_matrix.rows() * m_rowFactor.value(); } + EIGEN_DEVICE_FUNC + inline Index cols() const { return m_matrix.cols() * m_colFactor.value(); } + + EIGEN_DEVICE_FUNC + const _MatrixTypeNested& nestedExpression() const + { + return m_matrix; + } + + protected: + MatrixTypeNested m_matrix; + const internal::variable_if_dynamic m_rowFactor; + const internal::variable_if_dynamic m_colFactor; +}; + +/** + * \return an expression of the replication of \c *this + * + * Example: \include MatrixBase_replicate.cpp + * Output: \verbinclude MatrixBase_replicate.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(Index,Index), class Replicate + */ +template +template +const Replicate +DenseBase::replicate() const +{ + return Replicate(derived()); +} + +/** + * \return an expression of the replication of each column (or row) of \c *this + * + * Example: \include DirectionWise_replicate_int.cpp + * Output: \verbinclude DirectionWise_replicate_int.out + * + * \sa VectorwiseOp::replicate(), DenseBase::replicate(), class Replicate + */ +template +const typename VectorwiseOp::ReplicateReturnType +VectorwiseOp::replicate(Index factor) const +{ + return typename VectorwiseOp::ReplicateReturnType + (_expression(),Direction==Vertical?factor:1,Direction==Horizontal?factor:1); +} + +} // end namespace Eigen + +#endif // EIGEN_REPLICATE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ReturnByValue.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ReturnByValue.h new file mode 100644 index 0000000000000000000000000000000000000000..c44b7673bb3ef689ae9f1073989a75fb5fd1f27f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/ReturnByValue.h @@ -0,0 +1,117 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009-2010 Gael Guennebaud +// Copyright (C) 2009-2010 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_RETURNBYVALUE_H +#define EIGEN_RETURNBYVALUE_H + +namespace Eigen { + +namespace internal { + +template +struct traits > + : public traits::ReturnType> +{ + enum { + // We're disabling the DirectAccess because e.g. the constructor of + // the Block-with-DirectAccess expression requires to have a coeffRef method. + // Also, we don't want to have to implement the stride stuff. + Flags = (traits::ReturnType>::Flags + | EvalBeforeNestingBit) & ~DirectAccessBit + }; +}; + +/* The ReturnByValue object doesn't even have a coeff() method. + * So the only way that nesting it in an expression can work, is by evaluating it into a plain matrix. + * So internal::nested always gives the plain return matrix type. + * + * FIXME: I don't understand why we need this specialization: isn't this taken care of by the EvalBeforeNestingBit ?? + * Answer: EvalBeforeNestingBit should be deprecated since we have the evaluators + */ +template +struct nested_eval, n, PlainObject> +{ + typedef typename traits::ReturnType type; +}; + +} // end namespace internal + +/** \class ReturnByValue + * \ingroup Core_Module + * + */ +template class ReturnByValue + : public internal::dense_xpr_base< ReturnByValue >::type, internal::no_assignment_operator +{ + public: + typedef typename internal::traits::ReturnType ReturnType; + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(ReturnByValue) + + template + EIGEN_DEVICE_FUNC + inline void evalTo(Dest& dst) const + { static_cast(this)->evalTo(dst); } + EIGEN_DEVICE_FUNC inline Index rows() const { return static_cast(this)->rows(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return static_cast(this)->cols(); } + +#ifndef EIGEN_PARSED_BY_DOXYGEN +#define Unusable YOU_ARE_TRYING_TO_ACCESS_A_SINGLE_COEFFICIENT_IN_A_SPECIAL_EXPRESSION_WHERE_THAT_IS_NOT_ALLOWED_BECAUSE_THAT_WOULD_BE_INEFFICIENT + class Unusable{ + Unusable(const Unusable&) {} + Unusable& operator=(const Unusable&) {return *this;} + }; + const Unusable& coeff(Index) const { return *reinterpret_cast(this); } + const Unusable& coeff(Index,Index) const { return *reinterpret_cast(this); } + Unusable& coeffRef(Index) { return *reinterpret_cast(this); } + Unusable& coeffRef(Index,Index) { return *reinterpret_cast(this); } +#undef Unusable +#endif +}; + +template +template +Derived& DenseBase::operator=(const ReturnByValue& other) +{ + other.evalTo(derived()); + return derived(); +} + +namespace internal { + +// Expression is evaluated in a temporary; default implementation of Assignment is bypassed so that +// when a ReturnByValue expression is assigned, the evaluator is not constructed. +// TODO: Finalize port to new regime; ReturnByValue should not exist in the expression world + +template +struct evaluator > + : public evaluator::ReturnType> +{ + typedef ReturnByValue XprType; + typedef typename internal::traits::ReturnType PlainObject; + typedef evaluator Base; + + EIGEN_DEVICE_FUNC explicit evaluator(const XprType& xpr) + : m_result(xpr.rows(), xpr.cols()) + { + ::new (static_cast(this)) Base(m_result); + xpr.evalTo(m_result); + } + +protected: + PlainObject m_result; +}; + +} // end namespace internal + +} // end namespace Eigen + +#endif // EIGEN_RETURNBYVALUE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Reverse.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Reverse.h new file mode 100644 index 0000000000000000000000000000000000000000..0640cda2a1509e099bd16a434b3114de7b1c0d38 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Reverse.h @@ -0,0 +1,211 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2006-2008 Benoit Jacob +// Copyright (C) 2009 Ricard Marxer +// Copyright (C) 2009-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_REVERSE_H +#define EIGEN_REVERSE_H + +namespace Eigen { + +namespace internal { + +template +struct traits > + : traits +{ + typedef typename MatrixType::Scalar Scalar; + typedef typename traits::StorageKind StorageKind; + typedef typename traits::XprKind XprKind; + typedef typename ref_selector::type MatrixTypeNested; + typedef typename remove_reference::type _MatrixTypeNested; + enum { + RowsAtCompileTime = MatrixType::RowsAtCompileTime, + ColsAtCompileTime = MatrixType::ColsAtCompileTime, + MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, + Flags = _MatrixTypeNested::Flags & (RowMajorBit | LvalueBit) + }; +}; + +template struct reverse_packet_cond +{ + static inline PacketType run(const PacketType& x) { return preverse(x); } +}; + +template struct reverse_packet_cond +{ + static inline PacketType run(const PacketType& x) { return x; } +}; + +} // end namespace internal + +/** \class Reverse + * \ingroup Core_Module + * + * \brief Expression of the reverse of a vector or matrix + * + * \tparam MatrixType the type of the object of which we are taking the reverse + * \tparam Direction defines the direction of the reverse operation, can be Vertical, Horizontal, or BothDirections + * + * This class represents an expression of the reverse of a vector. + * It is the return type of MatrixBase::reverse() and VectorwiseOp::reverse() + * and most of the time this is the only way it is used. + * + * \sa MatrixBase::reverse(), VectorwiseOp::reverse() + */ +template class Reverse + : public internal::dense_xpr_base< Reverse >::type +{ + public: + + typedef typename internal::dense_xpr_base::type Base; + EIGEN_DENSE_PUBLIC_INTERFACE(Reverse) + typedef typename internal::remove_all::type NestedExpression; + using Base::IsRowMajor; + + protected: + enum { + PacketSize = internal::packet_traits::size, + IsColMajor = !IsRowMajor, + ReverseRow = (Direction == Vertical) || (Direction == BothDirections), + ReverseCol = (Direction == Horizontal) || (Direction == BothDirections), + OffsetRow = ReverseRow && IsColMajor ? PacketSize : 1, + OffsetCol = ReverseCol && IsRowMajor ? PacketSize : 1, + ReversePacket = (Direction == BothDirections) + || ((Direction == Vertical) && IsColMajor) + || ((Direction == Horizontal) && IsRowMajor) + }; + typedef internal::reverse_packet_cond reverse_packet; + public: + + EIGEN_DEVICE_FUNC explicit inline Reverse(const MatrixType& matrix) : m_matrix(matrix) { } + + EIGEN_INHERIT_ASSIGNMENT_OPERATORS(Reverse) + + EIGEN_DEVICE_FUNC inline Index rows() const { return m_matrix.rows(); } + EIGEN_DEVICE_FUNC inline Index cols() const { return m_matrix.cols(); } + + EIGEN_DEVICE_FUNC inline Index innerStride() const + { + return -m_matrix.innerStride(); + } + + EIGEN_DEVICE_FUNC const typename internal::remove_all::type& + nestedExpression() const + { + return m_matrix; + } + + protected: + typename MatrixType::Nested m_matrix; +}; + +/** \returns an expression of the reverse of *this. + * + * Example: \include MatrixBase_reverse.cpp + * Output: \verbinclude MatrixBase_reverse.out + * + */ +template +inline typename DenseBase::ReverseReturnType +DenseBase::reverse() +{ + return ReverseReturnType(derived()); +} + + +//reverse const overload moved DenseBase.h due to a CUDA compiler bug + +/** This is the "in place" version of reverse: it reverses \c *this. + * + * In most cases it is probably better to simply use the reversed expression + * of a matrix. However, when reversing the matrix data itself is really needed, + * then this "in-place" version is probably the right choice because it provides + * the following additional benefits: + * - less error prone: doing the same operation with .reverse() requires special care: + * \code m = m.reverse().eval(); \endcode + * - this API enables reverse operations without the need for a temporary + * - it allows future optimizations (cache friendliness, etc.) + * + * \sa VectorwiseOp::reverseInPlace(), reverse() */ +template +inline void DenseBase::reverseInPlace() +{ + if(cols()>rows()) + { + Index half = cols()/2; + leftCols(half).swap(rightCols(half).reverse()); + if((cols()%2)==1) + { + Index half2 = rows()/2; + col(half).head(half2).swap(col(half).tail(half2).reverse()); + } + } + else + { + Index half = rows()/2; + topRows(half).swap(bottomRows(half).reverse()); + if((rows()%2)==1) + { + Index half2 = cols()/2; + row(half).head(half2).swap(row(half).tail(half2).reverse()); + } + } +} + +namespace internal { + +template +struct vectorwise_reverse_inplace_impl; + +template<> +struct vectorwise_reverse_inplace_impl +{ + template + static void run(ExpressionType &xpr) + { + Index half = xpr.rows()/2; + xpr.topRows(half).swap(xpr.bottomRows(half).colwise().reverse()); + } +}; + +template<> +struct vectorwise_reverse_inplace_impl +{ + template + static void run(ExpressionType &xpr) + { + Index half = xpr.cols()/2; + xpr.leftCols(half).swap(xpr.rightCols(half).rowwise().reverse()); + } +}; + +} // end namespace internal + +/** This is the "in place" version of VectorwiseOp::reverse: it reverses each column or row of \c *this. + * + * In most cases it is probably better to simply use the reversed expression + * of a matrix. However, when reversing the matrix data itself is really needed, + * then this "in-place" version is probably the right choice because it provides + * the following additional benefits: + * - less error prone: doing the same operation with .reverse() requires special care: + * \code m = m.reverse().eval(); \endcode + * - this API enables reverse operations without the need for a temporary + * + * \sa DenseBase::reverseInPlace(), reverse() */ +template +void VectorwiseOp::reverseInPlace() +{ + internal::vectorwise_reverse_inplace_impl::run(_expression().const_cast_derived()); +} + +} // end namespace Eigen + +#endif // EIGEN_REVERSE_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Select.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Select.h new file mode 100644 index 0000000000000000000000000000000000000000..79eec1b5b0e08a5eb045e3d482ed42d1da4e9d32 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/Eigen/src/Core/Select.h @@ -0,0 +1,162 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2008-2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifndef EIGEN_SELECT_H +#define EIGEN_SELECT_H + +namespace Eigen { + +/** \class Select + * \ingroup Core_Module + * + * \brief Expression of a coefficient wise version of the C++ ternary operator ?: + * + * \param ConditionMatrixType the type of the \em condition expression which must be a boolean matrix + * \param ThenMatrixType the type of the \em then expression + * \param ElseMatrixType the type of the \em else expression + * + * This class represents an expression of a coefficient wise version of the C++ ternary operator ?:. + * It is the return type of DenseBase::select() and most of the time this is the only way it is used. + * + * \sa DenseBase::select(const DenseBase&, const DenseBase&) const + */ + +namespace internal { +template +struct traits > + : traits +{ + typedef typename traits::Scalar Scalar; + typedef Dense StorageKind; + typedef typename traits::XprKind XprKind; + typedef typename ConditionMatrixType::Nested ConditionMatrixNested; + typedef typename ThenMatrixType::Nested ThenMatrixNested; + typedef typename ElseMatrixType::Nested ElseMatrixNested; + enum { + RowsAtCompileTime = ConditionMatrixType::RowsAtCompileTime, + ColsAtCompileTime = ConditionMatrixType::ColsAtCompileTime, + MaxRowsAtCompileTime = ConditionMatrixType::MaxRowsAtCompileTime, + MaxColsAtCompileTime = ConditionMatrixType::MaxColsAtCompileTime, + Flags = (unsigned int)ThenMatrixType::Flags & ElseMatrixType::Flags & RowMajorBit + }; +}; +} + +template +class Select : public internal::dense_xpr_base< Select >::type, + internal::no_assignment_operator +{ + public: + + typedef typename internal::dense_xpr_base" << endl; + cerr << "available actions:" << endl; + for (auto it = available_actions.begin(); it != available_actions.end(); ++it) { + cerr << " " << (*it)->invokation_name() << endl; + } + cerr << "the input files should each contain an output of benchmark-blocking-sizes" << endl; + exit(1); +} + +int main(int argc, char* argv[]) +{ + cout.precision(default_precision); + cerr.precision(default_precision); + + vector> available_actions; + available_actions.emplace_back(new partition_action_t); + available_actions.emplace_back(new evaluate_defaults_action_t); + + vector input_filenames; + + action_t* action = nullptr; + + if (argc < 2) { + show_usage_and_exit(argc, argv, available_actions); + } + for (int i = 1; i < argc; i++) { + bool arg_handled = false; + // Step 1. Try to match action invokation names. + for (auto it = available_actions.begin(); it != available_actions.end(); ++it) { + if (!strcmp(argv[i], (*it)->invokation_name())) { + if (!action) { + action = it->get(); + arg_handled = true; + break; + } else { + cerr << "can't specify more than one action!" << endl; + show_usage_and_exit(argc, argv, available_actions); + } + } + } + if (arg_handled) { + continue; + } + // Step 2. Try to match option names. + if (argv[i][0] == '-') { + if (!strcmp(argv[i], "--only-cubic-sizes")) { + only_cubic_sizes = true; + arg_handled = true; + } + if (!strcmp(argv[i], "--dump-tables")) { + dump_tables = true; + arg_handled = true; + } + if (!arg_handled) { + cerr << "Unrecognized option: " << argv[i] << endl; + show_usage_and_exit(argc, argv, available_actions); + } + } + if (arg_handled) { + continue; + } + // Step 3. Default to interpreting args as input filenames. + input_filenames.emplace_back(argv[i]); + } + + if (dump_tables && only_cubic_sizes) { + cerr << "Incompatible options: --only-cubic-sizes and --dump-tables." << endl; + show_usage_and_exit(argc, argv, available_actions); + } + + if (!action) { + show_usage_and_exit(argc, argv, available_actions); + } + + action->run(input_filenames); +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbench.cxxlist b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbench.cxxlist new file mode 100644 index 0000000000000000000000000000000000000000..a8ab34e0df72f2a172885d98472910d1c035c3d1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbench.cxxlist @@ -0,0 +1,28 @@ +#!/bin/bash + +# CLIST[((g++))]="g++-3.4 -O3 -DNDEBUG" +# CLIST[((g++))]="g++-3.4 -O3 -DNDEBUG -finline-limit=20000" + +# CLIST[((g++))]="g++-4.1 -O3 -DNDEBUG" +#CLIST[((g++))]="g++-4.1 -O3 -DNDEBUG -finline-limit=20000" + +# CLIST[((g++))]="g++-4.2 -O3 -DNDEBUG" +#CLIST[((g++))]="g++-4.2 -O3 -DNDEBUG -finline-limit=20000" +# CLIST[((g++))]="g++-4.2 -O3 -DNDEBUG -finline-limit=20000 -fprofile-generate" +# CLIST[((g++))]="g++-4.2 -O3 -DNDEBUG -finline-limit=20000 -fprofile-use" + +# CLIST[((g++))]="g++-4.3 -O3 -DNDEBUG" +#CLIST[((g++))]="g++-4.3 -O3 -DNDEBUG -finline-limit=20000" +# CLIST[((g++))]="g++-4.3 -O3 -DNDEBUG -finline-limit=20000 -fprofile-generate" +# CLIST[((g++))]="g++-4.3 -O3 -DNDEBUG -finline-limit=20000 -fprofile-use" + +# CLIST[((g++))]="icpc -fast -DNDEBUG -fno-exceptions -no-inline-max-size -prof-genx" +# CLIST[((g++))]="icpc -fast -DNDEBUG -fno-exceptions -no-inline-max-size -prof-use" + +#CLIST[((g++))]="/opt/intel/Compiler/11.1/072/bin/intel64/icpc -fast -DNDEBUG -fno-exceptions -no-inline-max-size -lrt" +CLIST[((g++))]="/home/orzel/svn/llvm/Release/bin/clang++ -O3 -DNDEBUG -DEIGEN_DONT_VECTORIZE -lrt" +CLIST[((g++))]="/home/orzel/svn/llvm/Release/bin/clang++ -O3 -DNDEBUG -lrt" +CLIST[((g++))]="g++-4.4.4 -O3 -DNDEBUG -DEIGEN_DONT_VECTORIZE -lrt" +CLIST[((g++))]="g++-4.4.4 -O3 -DNDEBUG -lrt" +CLIST[((g++))]="g++-4.5.0 -O3 -DNDEBUG -DEIGEN_DONT_VECTORIZE -lrt" +CLIST[((g++))]="g++-4.5.0 -O3 -DNDEBUG -lrt" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a26ea853fc753d9b0caf35d5ea9c90b829b48c98 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.cpp @@ -0,0 +1,35 @@ + +#include +#include "BenchUtil.h" +#include "basicbenchmark.h" + +int main(int argc, char *argv[]) +{ + DISABLE_SSE_EXCEPTIONS(); + + // this is the list of matrix type and size we want to bench: + // ((suffix) (matrix size) (number of iterations)) + #define MODES ((3d)(3)(4000000)) ((4d)(4)(1000000)) ((Xd)(4)(1000000)) ((Xd)(20)(10000)) +// #define MODES ((Xd)(20)(10000)) + + #define _GENERATE_HEADER(R,ARG,EL) << BOOST_PP_STRINGIZE(BOOST_PP_SEQ_HEAD(EL)) << "-" \ + << BOOST_PP_STRINGIZE(BOOST_PP_SEQ_ELEM(1,EL)) << "x" \ + << BOOST_PP_STRINGIZE(BOOST_PP_SEQ_ELEM(1,EL)) << " / " + + std::cout BOOST_PP_SEQ_FOR_EACH(_GENERATE_HEADER, ~, MODES ) << endl; + + const int tries = 10; + + #define _RUN_BENCH(R,ARG,EL) \ + std::cout << ARG( \ + BOOST_PP_CAT(Matrix, BOOST_PP_SEQ_HEAD(EL)) (\ + BOOST_PP_SEQ_ELEM(1,EL),BOOST_PP_SEQ_ELEM(1,EL)), BOOST_PP_SEQ_ELEM(2,EL), tries) \ + << " "; + + BOOST_PP_SEQ_FOR_EACH(_RUN_BENCH, benchBasic, MODES ); + std::cout << endl; + BOOST_PP_SEQ_FOR_EACH(_RUN_BENCH, benchBasic, MODES ); + std::cout << endl; + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.h new file mode 100644 index 0000000000000000000000000000000000000000..3fdc35732f02010997e1bcfd745854a60cdf69be --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/basicbenchmark.h @@ -0,0 +1,63 @@ + +#ifndef EIGEN_BENCH_BASICBENCH_H +#define EIGEN_BENCH_BASICBENCH_H + +enum {LazyEval, EarlyEval, OmpEval}; + +template +void benchBasic_loop(const MatrixType& I, MatrixType& m, int iterations) __attribute__((noinline)); + +template +void benchBasic_loop(const MatrixType& I, MatrixType& m, int iterations) +{ + for(int a = 0; a < iterations; a++) + { + if (Mode==LazyEval) + { + asm("#begin_bench_loop LazyEval"); + if (MatrixType::SizeAtCompileTime!=Eigen::Dynamic) asm("#fixedsize"); + m = (I + 0.00005 * (m + m.lazy() * m)).eval(); + } + else if (Mode==OmpEval) + { + asm("#begin_bench_loop OmpEval"); + if (MatrixType::SizeAtCompileTime!=Eigen::Dynamic) asm("#fixedsize"); + m = (I + 0.00005 * (m + m.lazy() * m)).evalOMP(); + } + else + { + asm("#begin_bench_loop EarlyEval"); + if (MatrixType::SizeAtCompileTime!=Eigen::Dynamic) asm("#fixedsize"); + m = I + 0.00005 * (m + m * m); + } + asm("#end_bench_loop"); + } +} + +template +double benchBasic(const MatrixType& mat, int size, int tries) __attribute__((noinline)); + +template +double benchBasic(const MatrixType& mat, int iterations, int tries) +{ + const int rows = mat.rows(); + const int cols = mat.cols(); + + MatrixType I(rows,cols); + MatrixType m(rows,cols); + + initMatrix_identity(I); + + Eigen::BenchTimer timer; + for(uint t=0; t(I, m, iterations); + timer.stop(); + cerr << m; + } + return timer.value(); +}; + +#endif // EIGEN_BENCH_BASICBENCH_H diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchBlasGemm.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchBlasGemm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb086a555a3678b2854ecf9959e8dcbd63b17904 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchBlasGemm.cpp @@ -0,0 +1,219 @@ +// g++ -O3 -DNDEBUG -I.. -L /usr/lib64/atlas/ benchBlasGemm.cpp -o benchBlasGemm -lrt -lcblas +// possible options: +// -DEIGEN_DONT_VECTORIZE +// -msse2 + +// #define EIGEN_DEFAULT_TO_ROW_MAJOR +#define _FLOAT + +#include + +#include +#include "BenchTimer.h" + +// include the BLAS headers +extern "C" { +#include +} +#include + +#ifdef _FLOAT +typedef float Scalar; +#define CBLAS_GEMM cblas_sgemm +#else +typedef double Scalar; +#define CBLAS_GEMM cblas_dgemm +#endif + + +typedef Eigen::Matrix MyMatrix; +void bench_eigengemm(MyMatrix& mc, const MyMatrix& ma, const MyMatrix& mb, int nbloops); +void check_product(int M, int N, int K); +void check_product(void); + +int main(int argc, char *argv[]) +{ + // disable SSE exceptions + #ifdef __GNUC__ + { + int aux; + asm( + "stmxcsr %[aux] \n\t" + "orl $32832, %[aux] \n\t" + "ldmxcsr %[aux] \n\t" + : : [aux] "m" (aux)); + } + #endif + + int nbtries=1, nbloops=1, M, N, K; + + if (argc==2) + { + if (std::string(argv[1])=="check") + check_product(); + else + M = N = K = atoi(argv[1]); + } + else if ((argc==3) && (std::string(argv[1])=="auto")) + { + M = N = K = atoi(argv[2]); + nbloops = 1000000000/(M*M*M); + if (nbloops<1) + nbloops = 1; + nbtries = 6; + } + else if (argc==4) + { + M = N = K = atoi(argv[1]); + nbloops = atoi(argv[2]); + nbtries = atoi(argv[3]); + } + else if (argc==6) + { + M = atoi(argv[1]); + N = atoi(argv[2]); + K = atoi(argv[3]); + nbloops = atoi(argv[4]); + nbtries = atoi(argv[5]); + } + else + { + std::cout << "Usage: " << argv[0] << " size \n"; + std::cout << "Usage: " << argv[0] << " auto size\n"; + std::cout << "Usage: " << argv[0] << " size nbloops nbtries\n"; + std::cout << "Usage: " << argv[0] << " M N K nbloops nbtries\n"; + std::cout << "Usage: " << argv[0] << " check\n"; + std::cout << "Options:\n"; + std::cout << " size unique size of the 2 matrices (integer)\n"; + std::cout << " auto automatically set the number of repetitions and tries\n"; + std::cout << " nbloops number of times the GEMM routines is executed\n"; + std::cout << " nbtries number of times the loop is benched (return the best try)\n"; + std::cout << " M N K sizes of the matrices: MxN = MxK * KxN (integers)\n"; + std::cout << " check check eigen product using cblas as a reference\n"; + exit(1); + } + + double nbmad = double(M) * double(N) * double(K) * double(nbloops); + + if (!(std::string(argv[1])=="auto")) + std::cout << M << " x " << N << " x " << K << "\n"; + + Scalar alpha, beta; + MyMatrix ma(M,K), mb(K,N), mc(M,N); + ma = MyMatrix::Random(M,K); + mb = MyMatrix::Random(K,N); + mc = MyMatrix::Random(M,N); + + Eigen::BenchTimer timer; + + // we simply compute c += a*b, so: + alpha = 1; + beta = 1; + + // bench cblas + // ROWS_A, COLS_B, COLS_A, 1.0, A, COLS_A, B, COLS_B, 0.0, C, COLS_B); + if (!(std::string(argv[1])=="auto")) + { + timer.reset(); + for (uint k=0 ; k(1,64); + N = internal::random(1,768); + K = internal::random(1,768); + M = (0 + M) * 1; + std::cout << M << " x " << N << " x " << K << "\n"; + check_product(M, N, K); + } +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchCholesky.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchCholesky.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a8e7cf638857b3c2999a3c9bda91ddac868fd11 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchCholesky.cpp @@ -0,0 +1,142 @@ + +// g++ -DNDEBUG -O3 -I.. benchLLT.cpp -o benchLLT && ./benchLLT +// options: +// -DBENCH_GSL -lgsl /usr/lib/libcblas.so.3 +// -DEIGEN_DONT_VECTORIZE +// -msse2 +// -DREPEAT=100 +// -DTRIES=10 +// -DSCALAR=double + +#include + +#include +#include +#include +using namespace Eigen; + +#ifndef REPEAT +#define REPEAT 10000 +#endif + +#ifndef TRIES +#define TRIES 10 +#endif + +typedef float Scalar; + +template +__attribute__ ((noinline)) void benchLLT(const MatrixType& m) +{ + int rows = m.rows(); + int cols = m.cols(); + + double cost = 0; + for (int j=0; j SquareMatrixType; + + MatrixType a = MatrixType::Random(rows,cols); + SquareMatrixType covMat = a * a.adjoint(); + + BenchTimer timerNoSqrt, timerSqrt; + + Scalar acc = 0; + int r = internal::random(0,covMat.rows()-1); + int c = internal::random(0,covMat.cols()-1); + for (int t=0; t cholnosqrt(covMat); + acc += cholnosqrt.matrixL().coeff(r,c); + } + timerNoSqrt.stop(); + } + + for (int t=0; t chol(covMat); + acc += chol.matrixL().coeff(r,c); + } + timerSqrt.stop(); + } + + if (MatrixType::RowsAtCompileTime==Dynamic) + std::cout << "dyn "; + else + std::cout << "fixed "; + std::cout << covMat.rows() << " \t" + << (timerNoSqrt.best()) / repeats << "s " + << "(" << 1e-9 * cost*repeats/timerNoSqrt.best() << " GFLOPS)\t" + << (timerSqrt.best()) / repeats << "s " + << "(" << 1e-9 * cost*repeats/timerSqrt.best() << " GFLOPS)\n"; + + + #ifdef BENCH_GSL + if (MatrixType::RowsAtCompileTime==Dynamic) + { + timerSqrt.reset(); + + gsl_matrix* gslCovMat = gsl_matrix_alloc(covMat.rows(),covMat.cols()); + gsl_matrix* gslCopy = gsl_matrix_alloc(covMat.rows(),covMat.cols()); + + eiToGsl(covMat, &gslCovMat); + for (int t=0; t0; ++i) + benchLLT(Matrix(dynsizes[i],dynsizes[i])); + + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + benchLLT(Matrix()); + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchEigenSolver.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchEigenSolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd78c7e016fac442179349b13e807ade01fcb9bd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchEigenSolver.cpp @@ -0,0 +1,212 @@ + +// g++ -DNDEBUG -O3 -I.. benchEigenSolver.cpp -o benchEigenSolver && ./benchEigenSolver +// options: +// -DBENCH_GMM +// -DBENCH_GSL -lgsl /usr/lib/libcblas.so.3 +// -DEIGEN_DONT_VECTORIZE +// -msse2 +// -DREPEAT=100 +// -DTRIES=10 +// -DSCALAR=double + +#include + +#include +#include +#include +using namespace Eigen; + +#ifndef REPEAT +#define REPEAT 1000 +#endif + +#ifndef TRIES +#define TRIES 4 +#endif + +#ifndef SCALAR +#define SCALAR float +#endif + +typedef SCALAR Scalar; + +template +__attribute__ ((noinline)) void benchEigenSolver(const MatrixType& m) +{ + int rows = m.rows(); + int cols = m.cols(); + + int stdRepeats = std::max(1,int((REPEAT*1000)/(rows*rows*sqrt(rows)))); + int saRepeats = stdRepeats * 4; + + typedef typename MatrixType::Scalar Scalar; + typedef Matrix SquareMatrixType; + + MatrixType a = MatrixType::Random(rows,cols); + SquareMatrixType covMat = a * a.adjoint(); + + BenchTimer timerSa, timerStd; + + Scalar acc = 0; + int r = internal::random(0,covMat.rows()-1); + int c = internal::random(0,covMat.cols()-1); + { + SelfAdjointEigenSolver ei(covMat); + for (int t=0; t ei(covMat); + for (int t=0; t gmmCovMat(covMat.rows(),covMat.cols()); + gmm::dense_matrix eigvect(covMat.rows(),covMat.cols()); + std::vector eigval(covMat.rows()); + eiToGmm(covMat, gmmCovMat); + for (int t=0; t0; ++i) + benchEigenSolver(Matrix(dynsizes[i],dynsizes[i])); + + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + benchEigenSolver(Matrix()); + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchFFT.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchFFT.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3eb1a1ac01bd267021bab0ee8167ab3d2c95477d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchFFT.cpp @@ -0,0 +1,115 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2009 Mark Borgerding mark a borgerding net +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include + +#include +#include +#include +#include + +#include + +using namespace Eigen; +using namespace std; + + +template +string nameof(); + +template <> string nameof() {return "float";} +template <> string nameof() {return "double";} +template <> string nameof() {return "long double";} + +#ifndef TYPE +#define TYPE float +#endif + +#ifndef NFFT +#define NFFT 1024 +#endif +#ifndef NDATA +#define NDATA 1000000 +#endif + +using namespace Eigen; + +template +void bench(int nfft,bool fwd,bool unscaled=false, bool halfspec=false) +{ + typedef typename NumTraits::Real Scalar; + typedef typename std::complex Complex; + int nits = NDATA/nfft; + vector inbuf(nfft); + vector outbuf(nfft); + FFT< Scalar > fft; + + if (unscaled) { + fft.SetFlag(fft.Unscaled); + cout << "unscaled "; + } + if (halfspec) { + fft.SetFlag(fft.HalfSpectrum); + cout << "halfspec "; + } + + + std::fill(inbuf.begin(),inbuf.end(),0); + fft.fwd( outbuf , inbuf); + + BenchTimer timer; + timer.reset(); + for (int k=0;k<8;++k) { + timer.start(); + if (fwd) + for(int i = 0; i < nits; i++) + fft.fwd( outbuf , inbuf); + else + for(int i = 0; i < nits; i++) + fft.inv(inbuf,outbuf); + timer.stop(); + } + + cout << nameof() << " "; + double mflops = 5.*nfft*log2((double)nfft) / (1e6 * timer.value() / (double)nits ); + if ( NumTraits::IsComplex ) { + cout << "complex"; + }else{ + cout << "real "; + mflops /= 2; + } + + + if (fwd) + cout << " fwd"; + else + cout << " inv"; + + cout << " NFFT=" << nfft << " " << (double(1e-6*nfft*nits)/timer.value()) << " MS/s " << mflops << "MFLOPS\n"; +} + +int main(int argc,char ** argv) +{ + bench >(NFFT,true); + bench >(NFFT,false); + bench(NFFT,true); + bench(NFFT,false); + bench(NFFT,false,true); + bench(NFFT,false,true,true); + + bench >(NFFT,true); + bench >(NFFT,false); + bench(NFFT,true); + bench(NFFT,false); + bench >(NFFT,true); + bench >(NFFT,false); + bench(NFFT,true); + bench(NFFT,false); + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchGeometry.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchGeometry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e16c0331d84829cb1042837fbb8f3c1e8f10c4e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchGeometry.cpp @@ -0,0 +1,134 @@ +#include +#include +#include +#include +#include + +using namespace Eigen; +using namespace std; + +#ifndef REPEAT +#define REPEAT 1000000 +#endif + +enum func_opt +{ + TV, + TMATV, + TMATVMAT, +}; + + +template +struct func; + +template +struct func +{ + static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 ) + { + asm (""); + return a1 * a2; + } +}; + +template +struct func +{ + static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 ) + { + asm (""); + return a1.matrix() * a2; + } +}; + +template +struct func +{ + static EIGEN_DONT_INLINE res run( arg1& a1, arg2& a2 ) + { + asm (""); + return res(a1.matrix() * a2.matrix()); + } +}; + +template +struct test_transform +{ + static void run() + { + arg1 a1; + a1.setIdentity(); + arg2 a2; + a2.setIdentity(); + + BenchTimer timer; + timer.reset(); + for (int k=0; k<10; ++k) + { + timer.start(); + for (int k=0; k Trans;\ + typedef Matrix Vec;\ + typedef func Func;\ + test_transform< Func, Trans, Vec >::run();\ + } + +#define run_trans( op, scalar, mode, option ) \ + std::cout << #scalar << "\t " << #mode << "\t " << #option << " "; \ + {\ + typedef Transform Trans;\ + typedef func Func;\ + test_transform< Func, Trans, Trans >::run();\ + } + +int main(int argc, char* argv[]) +{ + cout << "vec = trans * vec" << endl; + run_vec(TV, float, Isometry, AutoAlign, 3); + run_vec(TV, float, Isometry, DontAlign, 3); + run_vec(TV, float, Isometry, AutoAlign, 4); + run_vec(TV, float, Isometry, DontAlign, 4); + run_vec(TV, float, Projective, AutoAlign, 4); + run_vec(TV, float, Projective, DontAlign, 4); + run_vec(TV, double, Isometry, AutoAlign, 3); + run_vec(TV, double, Isometry, DontAlign, 3); + run_vec(TV, double, Isometry, AutoAlign, 4); + run_vec(TV, double, Isometry, DontAlign, 4); + run_vec(TV, double, Projective, AutoAlign, 4); + run_vec(TV, double, Projective, DontAlign, 4); + + cout << "vec = trans.matrix() * vec" << endl; + run_vec(TMATV, float, Isometry, AutoAlign, 4); + run_vec(TMATV, float, Isometry, DontAlign, 4); + run_vec(TMATV, double, Isometry, AutoAlign, 4); + run_vec(TMATV, double, Isometry, DontAlign, 4); + + cout << "trans = trans1 * trans" << endl; + run_trans(TV, float, Isometry, AutoAlign); + run_trans(TV, float, Isometry, DontAlign); + run_trans(TV, double, Isometry, AutoAlign); + run_trans(TV, double, Isometry, DontAlign); + run_trans(TV, float, Projective, AutoAlign); + run_trans(TV, float, Projective, DontAlign); + run_trans(TV, double, Projective, AutoAlign); + run_trans(TV, double, Projective, DontAlign); + + cout << "trans = trans1.matrix() * trans.matrix()" << endl; + run_trans(TMATVMAT, float, Isometry, AutoAlign); + run_trans(TMATVMAT, float, Isometry, DontAlign); + run_trans(TMATVMAT, double, Isometry, AutoAlign); + run_trans(TMATVMAT, double, Isometry, DontAlign); +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchVecAdd.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchVecAdd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce8e1e91103e6388b021dadf2abf3bb4e706bce4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchVecAdd.cpp @@ -0,0 +1,135 @@ + +#include +#include +#include +using namespace Eigen; + +#ifndef SIZE +#define SIZE 50 +#endif + +#ifndef REPEAT +#define REPEAT 10000 +#endif + +typedef float Scalar; + +__attribute__ ((noinline)) void benchVec(Scalar* a, Scalar* b, Scalar* c, int size); +__attribute__ ((noinline)) void benchVec(MatrixXf& a, MatrixXf& b, MatrixXf& c); +__attribute__ ((noinline)) void benchVec(VectorXf& a, VectorXf& b, VectorXf& c); + +int main(int argc, char* argv[]) +{ + int size = SIZE * 8; + int size2 = size * size; + Scalar* a = internal::aligned_new(size2); + Scalar* b = internal::aligned_new(size2+4)+1; + Scalar* c = internal::aligned_new(size2); + + for (int i=0; i2 ; --innersize) + { + if (size2%innersize==0) + { + int outersize = size2/innersize; + MatrixXf ma = Map(a, innersize, outersize ); + MatrixXf mb = Map(b, innersize, outersize ); + MatrixXf mc = Map(c, innersize, outersize ); + timer.reset(); + for (int k=0; k<3; ++k) + { + timer.start(); + benchVec(ma, mb, mc); + timer.stop(); + } + std::cout << innersize << " x " << outersize << " " << timer.value() << "s " << (double(size2*REPEAT)/timer.value())/(1024.*1024.*1024.) << " GFlops\n"; + } + } + + VectorXf va = Map(a, size2); + VectorXf vb = Map(b, size2); + VectorXf vc = Map(c, size2); + timer.reset(); + for (int k=0; k<3; ++k) + { + timer.start(); + benchVec(va, vb, vc); + timer.stop(); + } + std::cout << timer.value() << "s " << (double(size2*REPEAT)/timer.value())/(1024.*1024.*1024.) << " GFlops\n"; + + return 0; +} + +void benchVec(MatrixXf& a, MatrixXf& b, MatrixXf& c) +{ + for (int k=0; k::type PacketScalar; + const int PacketSize = internal::packet_traits::size; + PacketScalar a0, a1, a2, a3, b0, b1, b2, b3; + for (int k=0; k +// -DSCALARA=double or -DSCALARB=double +// -DHAVE_BLAS +// -DDECOUPLED +// + +#include +#include +#include + +using namespace std; +using namespace Eigen; + +#ifndef SCALAR +// #define SCALAR std::complex +#define SCALAR float +#endif + +#ifndef SCALARA +#define SCALARA SCALAR +#endif + +#ifndef SCALARB +#define SCALARB SCALAR +#endif + +typedef SCALAR Scalar; +typedef NumTraits::Real RealScalar; +typedef Matrix A; +typedef Matrix B; +typedef Matrix C; +typedef Matrix M; + +#ifdef HAVE_BLAS + +extern "C" { + #include +} + +static float fone = 1; +static float fzero = 0; +static double done = 1; +static double szero = 0; +static std::complex cfone = 1; +static std::complex cfzero = 0; +static std::complex cdone = 1; +static std::complex cdzero = 0; +static char notrans = 'N'; +static char trans = 'T'; +static char nonunit = 'N'; +static char lower = 'L'; +static char right = 'R'; +static int intone = 1; + +void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) +{ + int M = c.rows(); int N = c.cols(); int K = a.cols(); + int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); + + sgemm_(¬rans,¬rans,&M,&N,&K,&fone, + const_cast(a.data()),&lda, + const_cast(b.data()),&ldb,&fone, + c.data(),&ldc); +} + +EIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) +{ + int M = c.rows(); int N = c.cols(); int K = a.cols(); + int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); + + dgemm_(¬rans,¬rans,&M,&N,&K,&done, + const_cast(a.data()),&lda, + const_cast(b.data()),&ldb,&done, + c.data(),&ldc); +} + +void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c) +{ + int M = c.rows(); int N = c.cols(); int K = a.cols(); + int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); + + cgemm_(¬rans,¬rans,&M,&N,&K,(float*)&cfone, + const_cast((const float*)a.data()),&lda, + const_cast((const float*)b.data()),&ldb,(float*)&cfone, + (float*)c.data(),&ldc); +} + +void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c) +{ + int M = c.rows(); int N = c.cols(); int K = a.cols(); + int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); + + zgemm_(¬rans,¬rans,&M,&N,&K,(double*)&cdone, + const_cast((const double*)a.data()),&lda, + const_cast((const double*)b.data()),&ldb,(double*)&cdone, + (double*)c.data(),&ldc); +} + + + +#endif + +void matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci) +{ + cr.noalias() += ar * br; + cr.noalias() -= ai * bi; + ci.noalias() += ar * bi; + ci.noalias() += ai * br; +} + +void matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci) +{ + cr.noalias() += a * br; + ci.noalias() += a * bi; +} + +void matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci) +{ + cr.noalias() += ar * b; + ci.noalias() += ai * b; +} + +template +EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c) +{ + c.noalias() += a * b; +} + +int main(int argc, char ** argv) +{ + std::ptrdiff_t l1 = internal::queryL1CacheSize(); + std::ptrdiff_t l2 = internal::queryTopLevelCacheSize(); + std::cout << "L1 cache size = " << (l1>0 ? l1/1024 : -1) << " KB\n"; + std::cout << "L2/L3 cache size = " << (l2>0 ? l2/1024 : -1) << " KB\n"; + typedef internal::gebp_traits Traits; + std::cout << "Register blocking = " << Traits::mr << " x " << Traits::nr << "\n"; + + int rep = 1; // number of repetitions per try + int tries = 2; // number of tries, we keep the best + + int s = 2048; + int m = s; + int n = s; + int p = s; + int cache_size1=-1, cache_size2=l2, cache_size3 = 0; + + bool need_help = false; + for (int i=1; i -c -t -p \n"; + std::cout << " : size\n"; + std::cout << " : rows columns depth\n"; + return 1; + } + +#if EIGEN_VERSION_AT_LEAST(3,2,90) + if(cache_size1>0) + setCpuCacheSizes(cache_size1,cache_size2,cache_size3); +#endif + + A a(m,p); a.setRandom(); + B b(p,n); b.setRandom(); + C c(m,n); c.setOnes(); + C rc = c; + + std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n"; + std::ptrdiff_t mc(m), nc(n), kc(p); + internal::computeProductBlockingSizes(kc, mc, nc); + std::cout << "blocking size (mc x kc) = " << mc << " x " << kc << "\n"; + + C r = c; + + // check the parallel product is correct + #if defined EIGEN_HAS_OPENMP + Eigen::initParallel(); + int procs = omp_get_max_threads(); + if(procs>1) + { + #ifdef HAVE_BLAS + blas_gemm(a,b,r); + #else + omp_set_num_threads(1); + r.noalias() += a * b; + omp_set_num_threads(procs); + #endif + c.noalias() += a * b; + if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; + } + #elif defined HAVE_BLAS + blas_gemm(a,b,r); + c.noalias() += a * b; + if(!r.isApprox(c)) { + std::cout << r - c << "\n"; + std::cerr << "Warning, your product is crap!\n\n"; + } + #else + if(1.*m*n*p<2000.*2000*2000) + { + gemm(a,b,c); + r.noalias() += a.cast() .lazyProduct( b.cast() ); + if(!r.isApprox(c)) { + std::cout << r - c << "\n"; + std::cerr << "Warning, your product is crap!\n\n"; + } + } + #endif + + #ifdef HAVE_BLAS + BenchTimer tblas; + c = rc; + BENCH(tblas, tries, rep, blas_gemm(a,b,c)); + std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; + std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; + #endif + + BenchTimer tmt; + c = rc; + BENCH(tmt, tries, rep, gemm(a,b,c)); + std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; + std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; + + #ifdef EIGEN_HAS_OPENMP + if(procs>1) + { + BenchTimer tmono; + omp_set_num_threads(1); + Eigen::setNbThreads(1); + c = rc; + BENCH(tmono, tries, rep, gemm(a,b,c)); + std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; + std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; + std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; + } + #endif + + if(1.*m*n*p<30*30*30) + { + BenchTimer tmt; + c = rc; + BENCH(tmt, tries, rep, c.noalias()+=a.lazyProduct(b)); + std::cout << "lazy cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; + std::cout << "lazy real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; + } + + #ifdef DECOUPLED + if((NumTraits::IsComplex) && (NumTraits::IsComplex)) + { + M ar(m,p); ar.setRandom(); + M ai(m,p); ai.setRandom(); + M br(p,n); br.setRandom(); + M bi(p,n); bi.setRandom(); + M cr(m,n); cr.setRandom(); + M ci(m,n); ci.setRandom(); + + BenchTimer t; + BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci)); + std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; + std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; + } + if((!NumTraits::IsComplex) && (NumTraits::IsComplex)) + { + M a(m,p); a.setRandom(); + M br(p,n); br.setRandom(); + M bi(p,n); bi.setRandom(); + M cr(m,n); cr.setRandom(); + M ci(m,n); ci.setRandom(); + + BenchTimer t; + BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci)); + std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; + std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; + } + if((NumTraits::IsComplex) && (!NumTraits::IsComplex)) + { + M ar(m,p); ar.setRandom(); + M ai(m,p); ai.setRandom(); + M b(p,n); b.setRandom(); + M cr(m,n); cr.setRandom(); + M ci(m,n); ci.setRandom(); + + BenchTimer t; + BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci)); + std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; + std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; + } + #endif + + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_multi_compilers.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_multi_compilers.sh new file mode 100644 index 0000000000000000000000000000000000000000..27e91f1d5ebfa8ccbd47c9073f68ed0b86641ac3 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_multi_compilers.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +if (($# < 2)); then + echo "Usage: $0 compilerlist.txt benchfile.cpp" +else + +compilerlist=$1 +benchfile=$2 + +g=0 +source $compilerlist + +# for each compiler, compile benchfile and run the benchmark +for (( i=0 ; i /dev/null + echo "" + else + echo "compiler not found: $compiler" + fi +done + +fi diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_norm.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_norm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..129afcfb25635afb2553e27d586695ae88ab5c15 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_norm.cpp @@ -0,0 +1,360 @@ +#include +#include +#include +#include "BenchTimer.h" +using namespace Eigen; +using namespace std; + +template +EIGEN_DONT_INLINE typename T::Scalar sqsumNorm(T& v) +{ + return v.norm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar stableNorm(T& v) +{ + return v.stableNorm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar hypotNorm(T& v) +{ + return v.hypotNorm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar blueNorm(T& v) +{ + return v.blueNorm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar lapackNorm(T& v) +{ + typedef typename T::Scalar Scalar; + int n = v.size(); + Scalar scale = 0; + Scalar ssq = 1; + for (int i=0;i= ax) + { + ssq += numext::abs2(ax/scale); + } + else + { + ssq = Scalar(1) + ssq * numext::abs2(scale/ax); + scale = ax; + } + } + return scale * std::sqrt(ssq); +} + +template +EIGEN_DONT_INLINE typename T::Scalar twopassNorm(T& v) +{ + typedef typename T::Scalar Scalar; + Scalar s = v.array().abs().maxCoeff(); + return s*(v/s).norm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar bl2passNorm(T& v) +{ + return v.stableNorm(); +} + +template +EIGEN_DONT_INLINE typename T::Scalar divacNorm(T& v) +{ + int n =v.size() / 2; + for (int i=0;i0) + { + for (int i=0;i +EIGEN_DONT_INLINE typename T::Scalar pblueNorm(const T& v) +{ + #ifndef EIGEN_VECTORIZE + return v.blueNorm(); + #else + typedef typename T::Scalar Scalar; + + static int nmax = 0; + static Scalar b1, b2, s1m, s2m, overfl, rbig, relerr; + int n; + + if(nmax <= 0) + { + int nbig, ibeta, it, iemin, iemax, iexp; + Scalar abig, eps; + + nbig = std::numeric_limits::max(); // largest integer + ibeta = std::numeric_limits::radix; //NumTraits::Base; // base for floating-point numbers + it = std::numeric_limits::digits; //NumTraits::Mantissa; // number of base-beta digits in mantissa + iemin = std::numeric_limits::min_exponent; // minimum exponent + iemax = std::numeric_limits::max_exponent; // maximum exponent + rbig = std::numeric_limits::max(); // largest floating-point number + + // Check the basic machine-dependent constants. + if(iemin > 1 - 2*it || 1+it>iemax || (it==2 && ibeta<5) + || (it<=4 && ibeta <= 3 ) || it<2) + { + eigen_assert(false && "the algorithm cannot be guaranteed on this computer"); + } + iexp = -((1-iemin)/2); + b1 = std::pow(ibeta, iexp); // lower boundary of midrange + iexp = (iemax + 1 - it)/2; + b2 = std::pow(ibeta,iexp); // upper boundary of midrange + + iexp = (2-iemin)/2; + s1m = std::pow(ibeta,iexp); // scaling factor for lower range + iexp = - ((iemax+it)/2); + s2m = std::pow(ibeta,iexp); // scaling factor for upper range + + overfl = rbig*s2m; // overfow boundary for abig + eps = std::pow(ibeta, 1-it); + relerr = std::sqrt(eps); // tolerance for neglecting asml + abig = 1.0/eps - 1.0; + if (Scalar(nbig)>abig) nmax = abig; // largest safe n + else nmax = nbig; + } + + typedef typename internal::packet_traits::type Packet; + const int ps = internal::packet_traits::size; + Packet pasml = internal::pset1(Scalar(0)); + Packet pamed = internal::pset1(Scalar(0)); + Packet pabig = internal::pset1(Scalar(0)); + Packet ps2m = internal::pset1(s2m); + Packet ps1m = internal::pset1(s1m); + Packet pb2 = internal::pset1(b2); + Packet pb1 = internal::pset1(b1); + for(int j=0; j(j)); + Packet ax_s2m = internal::pmul(ax,ps2m); + Packet ax_s1m = internal::pmul(ax,ps1m); + Packet maskBig = internal::plt(pb2,ax); + Packet maskSml = internal::plt(ax,pb1); + +// Packet maskMed = internal::pand(maskSml,maskBig); +// Packet scale = internal::pset1(Scalar(0)); +// scale = internal::por(scale, internal::pand(maskBig,ps2m)); +// scale = internal::por(scale, internal::pand(maskSml,ps1m)); +// scale = internal::por(scale, internal::pandnot(internal::pset1(Scalar(1)),maskMed)); +// ax = internal::pmul(ax,scale); +// ax = internal::pmul(ax,ax); +// pabig = internal::padd(pabig, internal::pand(maskBig, ax)); +// pasml = internal::padd(pasml, internal::pand(maskSml, ax)); +// pamed = internal::padd(pamed, internal::pandnot(ax,maskMed)); + + + pabig = internal::padd(pabig, internal::pand(maskBig, internal::pmul(ax_s2m,ax_s2m))); + pasml = internal::padd(pasml, internal::pand(maskSml, internal::pmul(ax_s1m,ax_s1m))); + pamed = internal::padd(pamed, internal::pandnot(internal::pmul(ax,ax),internal::pand(maskSml,maskBig))); + } + Scalar abig = internal::predux(pabig); + Scalar asml = internal::predux(pasml); + Scalar amed = internal::predux(pamed); + if(abig > Scalar(0)) + { + abig = std::sqrt(abig); + if(abig > overfl) + { + eigen_assert(false && "overflow"); + return rbig; + } + if(amed > Scalar(0)) + { + abig = abig/s2m; + amed = std::sqrt(amed); + } + else + { + return abig/s2m; + } + + } + else if(asml > Scalar(0)) + { + if (amed > Scalar(0)) + { + abig = std::sqrt(amed); + amed = std::sqrt(asml) / s1m; + } + else + { + return std::sqrt(asml)/s1m; + } + } + else + { + return std::sqrt(amed); + } + asml = std::min(abig, amed); + abig = std::max(abig, amed); + if(asml <= abig*relerr) + return abig; + else + return abig * std::sqrt(Scalar(1) + numext::abs2(asml/abig)); + #endif +} + +#define BENCH_PERF(NRM) { \ + float af = 0; double ad = 0; std::complex ac = 0; \ + Eigen::BenchTimer tf, td, tcf; tf.reset(); td.reset(); tcf.reset();\ + for (int k=0; k()); + double yd = based * std::abs(internal::random()); + VectorXf vf = VectorXf::Ones(s) * yf; + VectorXd vd = VectorXd::Ones(s) * yd; + + std::cout << "reference\t" << std::sqrt(double(s))*yf << "\t" << std::sqrt(double(s))*yd << "\n"; + std::cout << "sqsumNorm\t" << sqsumNorm(vf) << "\t" << sqsumNorm(vd) << "\n"; + std::cout << "hypotNorm\t" << hypotNorm(vf) << "\t" << hypotNorm(vd) << "\n"; + std::cout << "blueNorm\t" << blueNorm(vf) << "\t" << blueNorm(vd) << "\n"; + std::cout << "pblueNorm\t" << pblueNorm(vf) << "\t" << pblueNorm(vd) << "\n"; + std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\n"; + std::cout << "twopassNorm\t" << twopassNorm(vf) << "\t" << twopassNorm(vd) << "\n"; + std::cout << "bl2passNorm\t" << bl2passNorm(vf) << "\t" << bl2passNorm(vd) << "\n"; +} + +void check_accuracy_var(int ef0, int ef1, int ed0, int ed1, int s) +{ + VectorXf vf(s); + VectorXd vd(s); + for (int i=0; i()) * std::pow(double(10), internal::random(ef0,ef1)); + vd[i] = std::abs(internal::random()) * std::pow(double(10), internal::random(ed0,ed1)); + } + + //std::cout << "reference\t" << internal::sqrt(double(s))*yf << "\t" << internal::sqrt(double(s))*yd << "\n"; + std::cout << "sqsumNorm\t" << sqsumNorm(vf) << "\t" << sqsumNorm(vd) << "\t" << sqsumNorm(vf.cast()) << "\t" << sqsumNorm(vd.cast()) << "\n"; + std::cout << "hypotNorm\t" << hypotNorm(vf) << "\t" << hypotNorm(vd) << "\t" << hypotNorm(vf.cast()) << "\t" << hypotNorm(vd.cast()) << "\n"; + std::cout << "blueNorm\t" << blueNorm(vf) << "\t" << blueNorm(vd) << "\t" << blueNorm(vf.cast()) << "\t" << blueNorm(vd.cast()) << "\n"; + std::cout << "pblueNorm\t" << pblueNorm(vf) << "\t" << pblueNorm(vd) << "\t" << blueNorm(vf.cast()) << "\t" << blueNorm(vd.cast()) << "\n"; + std::cout << "lapackNorm\t" << lapackNorm(vf) << "\t" << lapackNorm(vd) << "\t" << lapackNorm(vf.cast()) << "\t" << lapackNorm(vd.cast()) << "\n"; + std::cout << "twopassNorm\t" << twopassNorm(vf) << "\t" << twopassNorm(vd) << "\t" << twopassNorm(vf.cast()) << "\t" << twopassNorm(vd.cast()) << "\n"; +// std::cout << "bl2passNorm\t" << bl2passNorm(vf) << "\t" << bl2passNorm(vd) << "\t" << bl2passNorm(vf.cast()) << "\t" << bl2passNorm(vd.cast()) << "\n"; +} + +int main(int argc, char** argv) +{ + int tries = 10; + int iters = 100000; + double y = 1.1345743233455785456788e12 * internal::random(); + VectorXf v = VectorXf::Ones(1024) * y; + +// return 0; + int s = 10000; + double basef_ok = 1.1345743233455785456788e15; + double based_ok = 1.1345743233455785456788e95; + + double basef_under = 1.1345743233455785456788e-27; + double based_under = 1.1345743233455785456788e-303; + + double basef_over = 1.1345743233455785456788e+27; + double based_over = 1.1345743233455785456788e+302; + + std::cout.precision(20); + + std::cerr << "\nNo under/overflow:\n"; + check_accuracy(basef_ok, based_ok, s); + + std::cerr << "\nUnderflow:\n"; + check_accuracy(basef_under, based_under, s); + + std::cerr << "\nOverflow:\n"; + check_accuracy(basef_over, based_over, s); + + std::cerr << "\nVarying (over):\n"; + for (int k=0; k<1; ++k) + { + check_accuracy_var(20,27,190,302,s); + std::cout << "\n"; + } + + std::cerr << "\nVarying (under):\n"; + for (int k=0; k<1; ++k) + { + check_accuracy_var(-27,20,-302,-190,s); + std::cout << "\n"; + } + + y = 1; + std::cout.precision(4); + int s1 = 1024*1024*32; + std::cerr << "Performance (out of cache, " << s1 << "):\n"; + { + int iters = 1; + VectorXf vf = VectorXf::Random(s1) * y; + VectorXd vd = VectorXd::Random(s1) * y; + VectorXcf vcf = VectorXcf::Random(s1) * y; + BENCH_PERF(sqsumNorm); + BENCH_PERF(stableNorm); + BENCH_PERF(blueNorm); + BENCH_PERF(pblueNorm); + BENCH_PERF(lapackNorm); + BENCH_PERF(hypotNorm); + BENCH_PERF(twopassNorm); + BENCH_PERF(bl2passNorm); + } + + std::cerr << "\nPerformance (in cache, " << 512 << "):\n"; + { + int iters = 100000; + VectorXf vf = VectorXf::Random(512) * y; + VectorXd vd = VectorXd::Random(512) * y; + VectorXcf vcf = VectorXcf::Random(512) * y; + BENCH_PERF(sqsumNorm); + BENCH_PERF(stableNorm); + BENCH_PERF(blueNorm); + BENCH_PERF(pblueNorm); + BENCH_PERF(lapackNorm); + BENCH_PERF(hypotNorm); + BENCH_PERF(twopassNorm); + BENCH_PERF(bl2passNorm); + } +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_reverse.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_reverse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e69ca1b29c89ad291119da5878cbcebd983216b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_reverse.cpp @@ -0,0 +1,84 @@ + +#include +#include +#include +using namespace Eigen; + +#ifndef REPEAT +#define REPEAT 100000 +#endif + +#ifndef TRIES +#define TRIES 20 +#endif + +typedef double Scalar; + +template +__attribute__ ((noinline)) void bench_reverse(const MatrixType& m) +{ + int rows = m.rows(); + int cols = m.cols(); + int size = m.size(); + + int repeats = (REPEAT*1000)/size; + MatrixType a = MatrixType::Random(rows,cols); + MatrixType b = MatrixType::Random(rows,cols); + + BenchTimer timerB, timerH, timerV; + + Scalar acc = 0; + int r = internal::random(0,rows-1); + int c = internal::random(0,cols-1); + for (int t=0; t0; ++i) + { + bench_reverse(Matrix(dynsizes[i],dynsizes[i])); + bench_reverse(Matrix(dynsizes[i]*dynsizes[i])); + } +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); +// bench_reverse(Matrix()); + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_sum.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_sum.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3d925e4fc7f78b16996d7025fefc72cc75869ed --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_sum.cpp @@ -0,0 +1,18 @@ +#include +#include +using namespace Eigen; +using namespace std; + +int main() +{ + typedef Matrix Vec; + Vec v(SIZE); + v.setZero(); + v[0] = 1; + v[1] = 2; + for(int i = 0; i < 1000000; i++) + { + v.coeffRef(0) += v.sum() * SCALAR(1e-20); + } + cout << v.sum() << endl; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_unrolling b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_unrolling new file mode 100644 index 0000000000000000000000000000000000000000..826443845b7be258f8931b5a63cc1f9dd98354b7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/bench_unrolling @@ -0,0 +1,12 @@ +#!/bin/bash + +# gcc : CXX="g++ -finline-limit=10000 -ftemplate-depth-2000 --param max-inline-recursive-depth=2000" +# icc : CXX="icpc -fast -no-inline-max-size -fno-exceptions" +CXX=${CXX-g++ -finline-limit=10000 -ftemplate-depth-2000 --param max-inline-recursive-depth=2000} # default value + +for ((i=1; i<16; ++i)); do + echo "Matrix size: $i x $i :" + $CXX -O3 -I.. -DNDEBUG benchmark.cpp -DMATSIZE=$i -DEIGEN_UNROLLING_LIMIT=400 -o benchmark && time ./benchmark >/dev/null + $CXX -O3 -I.. -DNDEBUG -finline-limit=10000 benchmark.cpp -DMATSIZE=$i -DEIGEN_DONT_USE_UNROLLED_LOOPS=1 -o benchmark && time ./benchmark >/dev/null + echo " " +done diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark-blocking-sizes.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark-blocking-sizes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..827be2880294bfa395a20b51f151d0d8387655eb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark-blocking-sizes.cpp @@ -0,0 +1,677 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2015 Benoit Jacob +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include +#include +#include +#include +#include +#include +#include + +bool eigen_use_specific_block_size; +int eigen_block_size_k, eigen_block_size_m, eigen_block_size_n; +#define EIGEN_TEST_SPECIFIC_BLOCKING_SIZES eigen_use_specific_block_size +#define EIGEN_TEST_SPECIFIC_BLOCKING_SIZE_K eigen_block_size_k +#define EIGEN_TEST_SPECIFIC_BLOCKING_SIZE_M eigen_block_size_m +#define EIGEN_TEST_SPECIFIC_BLOCKING_SIZE_N eigen_block_size_n +#include + +#include + +using namespace Eigen; +using namespace std; + +static BenchTimer timer; + +// how many times we repeat each measurement. +// measurements are randomly shuffled - we're not doing +// all N identical measurements in a row. +const int measurement_repetitions = 3; + +// Timings below this value are too short to be accurate, +// we'll repeat measurements with more iterations until +// we get a timing above that threshold. +const float min_accurate_time = 1e-2f; + +// See --min-working-set-size command line parameter. +size_t min_working_set_size = 0; + +float max_clock_speed = 0.0f; + +// range of sizes that we will benchmark (in all 3 K,M,N dimensions) +const size_t maxsize = 2048; +const size_t minsize = 16; + +typedef MatrixXf MatrixType; +typedef MatrixType::Scalar Scalar; +typedef internal::packet_traits::type Packet; + +static_assert((maxsize & (maxsize - 1)) == 0, "maxsize must be a power of two"); +static_assert((minsize & (minsize - 1)) == 0, "minsize must be a power of two"); +static_assert(maxsize > minsize, "maxsize must be larger than minsize"); +static_assert(maxsize < (minsize << 16), "maxsize must be less than (minsize<<16)"); + +// just a helper to store a triple of K,M,N sizes for matrix product +struct size_triple_t +{ + size_t k, m, n; + size_triple_t() : k(0), m(0), n(0) {} + size_triple_t(size_t _k, size_t _m, size_t _n) : k(_k), m(_m), n(_n) {} + size_triple_t(const size_triple_t& o) : k(o.k), m(o.m), n(o.n) {} + size_triple_t(uint16_t compact) + { + k = 1 << ((compact & 0xf00) >> 8); + m = 1 << ((compact & 0x0f0) >> 4); + n = 1 << ((compact & 0x00f) >> 0); + } +}; + +uint8_t log2_pot(size_t x) { + size_t l = 0; + while (x >>= 1) l++; + return l; +} + +// Convert between size tripes and a compact form fitting in 12 bits +// where each size, which must be a POT, is encoded as its log2, on 4 bits +// so the largest representable size is 2^15 == 32k ... big enough. +uint16_t compact_size_triple(size_t k, size_t m, size_t n) +{ + return (log2_pot(k) << 8) | (log2_pot(m) << 4) | log2_pot(n); +} + +uint16_t compact_size_triple(const size_triple_t& t) +{ + return compact_size_triple(t.k, t.m, t.n); +} + +// A single benchmark. Initially only contains benchmark params. +// Then call run(), which stores the result in the gflops field. +struct benchmark_t +{ + uint16_t compact_product_size; + uint16_t compact_block_size; + bool use_default_block_size; + float gflops; + benchmark_t() + : compact_product_size(0) + , compact_block_size(0) + , use_default_block_size(false) + , gflops(0) + { + } + benchmark_t(size_t pk, size_t pm, size_t pn, + size_t bk, size_t bm, size_t bn) + : compact_product_size(compact_size_triple(pk, pm, pn)) + , compact_block_size(compact_size_triple(bk, bm, bn)) + , use_default_block_size(false) + , gflops(0) + {} + benchmark_t(size_t pk, size_t pm, size_t pn) + : compact_product_size(compact_size_triple(pk, pm, pn)) + , compact_block_size(0) + , use_default_block_size(true) + , gflops(0) + {} + + void run(); +}; + +ostream& operator<<(ostream& s, const benchmark_t& b) +{ + s << hex << b.compact_product_size << dec; + if (b.use_default_block_size) { + size_triple_t t(b.compact_product_size); + Index k = t.k, m = t.m, n = t.n; + internal::computeProductBlockingSizes(k, m, n); + s << " default(" << k << ", " << m << ", " << n << ")"; + } else { + s << " " << hex << b.compact_block_size << dec; + } + s << " " << b.gflops; + return s; +} + +// We sort first by increasing benchmark parameters, +// then by decreasing performance. +bool operator<(const benchmark_t& b1, const benchmark_t& b2) +{ + return b1.compact_product_size < b2.compact_product_size || + (b1.compact_product_size == b2.compact_product_size && ( + (b1.compact_block_size < b2.compact_block_size || ( + b1.compact_block_size == b2.compact_block_size && + b1.gflops > b2.gflops)))); +} + +void benchmark_t::run() +{ + size_triple_t productsizes(compact_product_size); + + if (use_default_block_size) { + eigen_use_specific_block_size = false; + } else { + // feed eigen with our custom blocking params + eigen_use_specific_block_size = true; + size_triple_t blocksizes(compact_block_size); + eigen_block_size_k = blocksizes.k; + eigen_block_size_m = blocksizes.m; + eigen_block_size_n = blocksizes.n; + } + + // set up the matrix pool + + const size_t combined_three_matrices_sizes = + sizeof(Scalar) * + (productsizes.k * productsizes.m + + productsizes.k * productsizes.n + + productsizes.m * productsizes.n); + + // 64 M is large enough that nobody has a cache bigger than that, + // while still being small enough that everybody has this much RAM, + // so conveniently we don't need to special-case platforms here. + const size_t unlikely_large_cache_size = 64 << 20; + + const size_t working_set_size = + min_working_set_size ? min_working_set_size : unlikely_large_cache_size; + + const size_t matrix_pool_size = + 1 + working_set_size / combined_three_matrices_sizes; + + MatrixType *lhs = new MatrixType[matrix_pool_size]; + MatrixType *rhs = new MatrixType[matrix_pool_size]; + MatrixType *dst = new MatrixType[matrix_pool_size]; + + for (size_t i = 0; i < matrix_pool_size; i++) { + lhs[i] = MatrixType::Zero(productsizes.m, productsizes.k); + rhs[i] = MatrixType::Zero(productsizes.k, productsizes.n); + dst[i] = MatrixType::Zero(productsizes.m, productsizes.n); + } + + // main benchmark loop + + int iters_at_a_time = 1; + float time_per_iter = 0.0f; + size_t matrix_index = 0; + while (true) { + + double starttime = timer.getCpuTime(); + for (int i = 0; i < iters_at_a_time; i++) { + dst[matrix_index].noalias() = lhs[matrix_index] * rhs[matrix_index]; + matrix_index++; + if (matrix_index == matrix_pool_size) { + matrix_index = 0; + } + } + double endtime = timer.getCpuTime(); + + const float timing = float(endtime - starttime); + + if (timing >= min_accurate_time) { + time_per_iter = timing / iters_at_a_time; + break; + } + + iters_at_a_time *= 2; + } + + delete[] lhs; + delete[] rhs; + delete[] dst; + + gflops = 2e-9 * productsizes.k * productsizes.m * productsizes.n / time_per_iter; +} + +void print_cpuinfo() +{ +#ifdef __linux__ + cout << "contents of /proc/cpuinfo:" << endl; + string line; + ifstream cpuinfo("/proc/cpuinfo"); + if (cpuinfo.is_open()) { + while (getline(cpuinfo, line)) { + cout << line << endl; + } + cpuinfo.close(); + } + cout << endl; +#elif defined __APPLE__ + cout << "output of sysctl hw:" << endl; + system("sysctl hw"); + cout << endl; +#endif +} + +template +string type_name() +{ + return "unknown"; +} + +template<> +string type_name() +{ + return "float"; +} + +template<> +string type_name() +{ + return "double"; +} + +struct action_t +{ + virtual const char* invokation_name() const { abort(); return nullptr; } + virtual void run() const { abort(); } + virtual ~action_t() {} +}; + +void show_usage_and_exit(int /*argc*/, char* argv[], + const vector>& available_actions) +{ + cerr << "usage: " << argv[0] << " [options...]" << endl << endl; + cerr << "available actions:" << endl << endl; + for (auto it = available_actions.begin(); it != available_actions.end(); ++it) { + cerr << " " << (*it)->invokation_name() << endl; + } + cerr << endl; + cerr << "options:" << endl << endl; + cerr << " --min-working-set-size=N:" << endl; + cerr << " Set the minimum working set size to N bytes." << endl; + cerr << " This is rounded up as needed to a multiple of matrix size." << endl; + cerr << " A larger working set lowers the chance of a warm cache." << endl; + cerr << " The default value 0 means use a large enough working" << endl; + cerr << " set to likely outsize caches." << endl; + cerr << " A value of 1 (that is, 1 byte) would mean don't do anything to" << endl; + cerr << " avoid warm caches." << endl; + exit(1); +} + +float measure_clock_speed() +{ + cerr << "Measuring clock speed... \r" << flush; + + vector all_gflops; + for (int i = 0; i < 8; i++) { + benchmark_t b(1024, 1024, 1024); + b.run(); + all_gflops.push_back(b.gflops); + } + + sort(all_gflops.begin(), all_gflops.end()); + float stable_estimate = all_gflops[2] + all_gflops[3] + all_gflops[4] + all_gflops[5]; + + // multiply by an arbitrary constant to discourage trying doing anything with the + // returned values besides just comparing them with each other. + float result = stable_estimate * 123.456f; + + return result; +} + +struct human_duration_t +{ + int seconds; + human_duration_t(int s) : seconds(s) {} +}; + +ostream& operator<<(ostream& s, const human_duration_t& d) +{ + int remainder = d.seconds; + if (remainder > 3600) { + int hours = remainder / 3600; + s << hours << " h "; + remainder -= hours * 3600; + } + if (remainder > 60) { + int minutes = remainder / 60; + s << minutes << " min "; + remainder -= minutes * 60; + } + if (d.seconds < 600) { + s << remainder << " s"; + } + return s; +} + +const char session_filename[] = "/data/local/tmp/benchmark-blocking-sizes-session.data"; + +void serialize_benchmarks(const char* filename, const vector& benchmarks, size_t first_benchmark_to_run) +{ + FILE* file = fopen(filename, "w"); + if (!file) { + cerr << "Could not open file " << filename << " for writing." << endl; + cerr << "Do you have write permissions on the current working directory?" << endl; + exit(1); + } + size_t benchmarks_vector_size = benchmarks.size(); + fwrite(&max_clock_speed, sizeof(max_clock_speed), 1, file); + fwrite(&benchmarks_vector_size, sizeof(benchmarks_vector_size), 1, file); + fwrite(&first_benchmark_to_run, sizeof(first_benchmark_to_run), 1, file); + fwrite(benchmarks.data(), sizeof(benchmark_t), benchmarks.size(), file); + fclose(file); +} + +bool deserialize_benchmarks(const char* filename, vector& benchmarks, size_t& first_benchmark_to_run) +{ + FILE* file = fopen(filename, "r"); + if (!file) { + return false; + } + if (1 != fread(&max_clock_speed, sizeof(max_clock_speed), 1, file)) { + return false; + } + size_t benchmarks_vector_size = 0; + if (1 != fread(&benchmarks_vector_size, sizeof(benchmarks_vector_size), 1, file)) { + return false; + } + if (1 != fread(&first_benchmark_to_run, sizeof(first_benchmark_to_run), 1, file)) { + return false; + } + benchmarks.resize(benchmarks_vector_size); + if (benchmarks.size() != fread(benchmarks.data(), sizeof(benchmark_t), benchmarks.size(), file)) { + return false; + } + unlink(filename); + return true; +} + +void try_run_some_benchmarks( + vector& benchmarks, + double time_start, + size_t& first_benchmark_to_run) +{ + if (first_benchmark_to_run == benchmarks.size()) { + return; + } + + double time_last_progress_update = 0; + double time_last_clock_speed_measurement = 0; + double time_now = 0; + + size_t benchmark_index = first_benchmark_to_run; + + while (true) { + float ratio_done = float(benchmark_index) / benchmarks.size(); + time_now = timer.getRealTime(); + + // We check clock speed every minute and at the end. + if (benchmark_index == benchmarks.size() || + time_now > time_last_clock_speed_measurement + 60.0f) + { + time_last_clock_speed_measurement = time_now; + + // Ensure that clock speed is as expected + float current_clock_speed = measure_clock_speed(); + + // The tolerance needs to be smaller than the relative difference between + // clock speeds that a device could operate under. + // It seems unlikely that a device would be throttling clock speeds by + // amounts smaller than 2%. + // With a value of 1%, I was getting within noise on a Sandy Bridge. + const float clock_speed_tolerance = 0.02f; + + if (current_clock_speed > (1 + clock_speed_tolerance) * max_clock_speed) { + // Clock speed is now higher than we previously measured. + // Either our initial measurement was inaccurate, which won't happen + // too many times as we are keeping the best clock speed value and + // and allowing some tolerance; or something really weird happened, + // which invalidates all benchmark results collected so far. + // Either way, we better restart all over again now. + if (benchmark_index) { + cerr << "Restarting at " << 100.0f * ratio_done + << " % because clock speed increased. " << endl; + } + max_clock_speed = current_clock_speed; + first_benchmark_to_run = 0; + return; + } + + bool rerun_last_tests = false; + + if (current_clock_speed < (1 - clock_speed_tolerance) * max_clock_speed) { + cerr << "Measurements completed so far: " + << 100.0f * ratio_done + << " % " << endl; + cerr << "Clock speed seems to be only " + << current_clock_speed/max_clock_speed + << " times what it used to be." << endl; + + unsigned int seconds_to_sleep_if_lower_clock_speed = 1; + + while (current_clock_speed < (1 - clock_speed_tolerance) * max_clock_speed) { + if (seconds_to_sleep_if_lower_clock_speed > 32) { + cerr << "Sleeping longer probably won't make a difference." << endl; + cerr << "Serializing benchmarks to " << session_filename << endl; + serialize_benchmarks(session_filename, benchmarks, first_benchmark_to_run); + cerr << "Now restart this benchmark, and it should pick up where we left." << endl; + exit(2); + } + rerun_last_tests = true; + cerr << "Sleeping " + << seconds_to_sleep_if_lower_clock_speed + << " s... \r" << endl; + sleep(seconds_to_sleep_if_lower_clock_speed); + current_clock_speed = measure_clock_speed(); + seconds_to_sleep_if_lower_clock_speed *= 2; + } + } + + if (rerun_last_tests) { + cerr << "Redoing the last " + << 100.0f * float(benchmark_index - first_benchmark_to_run) / benchmarks.size() + << " % because clock speed had been low. " << endl; + return; + } + + // nothing wrong with the clock speed so far, so there won't be a need to rerun + // benchmarks run so far in case we later encounter a lower clock speed. + first_benchmark_to_run = benchmark_index; + } + + if (benchmark_index == benchmarks.size()) { + // We're done! + first_benchmark_to_run = benchmarks.size(); + // Erase progress info + cerr << " " << endl; + return; + } + + // Display progress info on stderr + if (time_now > time_last_progress_update + 1.0f) { + time_last_progress_update = time_now; + cerr << "Measurements... " << 100.0f * ratio_done + << " %, ETA " + << human_duration_t(float(time_now - time_start) * (1.0f - ratio_done) / ratio_done) + << " \r" << flush; + } + + // This is where we actually run a benchmark! + benchmarks[benchmark_index].run(); + benchmark_index++; + } +} + +void run_benchmarks(vector& benchmarks) +{ + size_t first_benchmark_to_run; + vector deserialized_benchmarks; + bool use_deserialized_benchmarks = false; + if (deserialize_benchmarks(session_filename, deserialized_benchmarks, first_benchmark_to_run)) { + cerr << "Found serialized session with " + << 100.0f * first_benchmark_to_run / deserialized_benchmarks.size() + << " % already done" << endl; + if (deserialized_benchmarks.size() == benchmarks.size() && + first_benchmark_to_run > 0 && + first_benchmark_to_run < benchmarks.size()) + { + use_deserialized_benchmarks = true; + } + } + + if (use_deserialized_benchmarks) { + benchmarks = deserialized_benchmarks; + } else { + // not using deserialized benchmarks, starting from scratch + first_benchmark_to_run = 0; + + // Randomly shuffling benchmarks allows us to get accurate enough progress info, + // as now the cheap/expensive benchmarks are randomly mixed so they average out. + // It also means that if data is corrupted for some time span, the odds are that + // not all repetitions of a given benchmark will be corrupted. + random_shuffle(benchmarks.begin(), benchmarks.end()); + } + + for (int i = 0; i < 4; i++) { + max_clock_speed = max(max_clock_speed, measure_clock_speed()); + } + + double time_start = 0.0; + while (first_benchmark_to_run < benchmarks.size()) { + if (first_benchmark_to_run == 0) { + time_start = timer.getRealTime(); + } + try_run_some_benchmarks(benchmarks, + time_start, + first_benchmark_to_run); + } + + // Sort timings by increasing benchmark parameters, and decreasing gflops. + // The latter is very important. It means that we can ignore all but the first + // benchmark with given parameters. + sort(benchmarks.begin(), benchmarks.end()); + + // Collect best (i.e. now first) results for each parameter values. + vector best_benchmarks; + for (auto it = benchmarks.begin(); it != benchmarks.end(); ++it) { + if (best_benchmarks.empty() || + best_benchmarks.back().compact_product_size != it->compact_product_size || + best_benchmarks.back().compact_block_size != it->compact_block_size) + { + best_benchmarks.push_back(*it); + } + } + + // keep and return only the best benchmarks + benchmarks = best_benchmarks; +} + +struct measure_all_pot_sizes_action_t : action_t +{ + virtual const char* invokation_name() const { return "all-pot-sizes"; } + virtual void run() const + { + vector benchmarks; + for (int repetition = 0; repetition < measurement_repetitions; repetition++) { + for (size_t ksize = minsize; ksize <= maxsize; ksize *= 2) { + for (size_t msize = minsize; msize <= maxsize; msize *= 2) { + for (size_t nsize = minsize; nsize <= maxsize; nsize *= 2) { + for (size_t kblock = minsize; kblock <= ksize; kblock *= 2) { + for (size_t mblock = minsize; mblock <= msize; mblock *= 2) { + for (size_t nblock = minsize; nblock <= nsize; nblock *= 2) { + benchmarks.emplace_back(ksize, msize, nsize, kblock, mblock, nblock); + } + } + } + } + } + } + } + + run_benchmarks(benchmarks); + + cout << "BEGIN MEASUREMENTS ALL POT SIZES" << endl; + for (auto it = benchmarks.begin(); it != benchmarks.end(); ++it) { + cout << *it << endl; + } + } +}; + +struct measure_default_sizes_action_t : action_t +{ + virtual const char* invokation_name() const { return "default-sizes"; } + virtual void run() const + { + vector benchmarks; + for (int repetition = 0; repetition < measurement_repetitions; repetition++) { + for (size_t ksize = minsize; ksize <= maxsize; ksize *= 2) { + for (size_t msize = minsize; msize <= maxsize; msize *= 2) { + for (size_t nsize = minsize; nsize <= maxsize; nsize *= 2) { + benchmarks.emplace_back(ksize, msize, nsize); + } + } + } + } + + run_benchmarks(benchmarks); + + cout << "BEGIN MEASUREMENTS DEFAULT SIZES" << endl; + for (auto it = benchmarks.begin(); it != benchmarks.end(); ++it) { + cout << *it << endl; + } + } +}; + +int main(int argc, char* argv[]) +{ + double time_start = timer.getRealTime(); + cout.precision(4); + cerr.precision(4); + + vector> available_actions; + available_actions.emplace_back(new measure_all_pot_sizes_action_t); + available_actions.emplace_back(new measure_default_sizes_action_t); + + auto action = available_actions.end(); + + if (argc <= 1) { + show_usage_and_exit(argc, argv, available_actions); + } + for (auto it = available_actions.begin(); it != available_actions.end(); ++it) { + if (!strcmp(argv[1], (*it)->invokation_name())) { + action = it; + break; + } + } + + if (action == available_actions.end()) { + show_usage_and_exit(argc, argv, available_actions); + } + + for (int i = 2; i < argc; i++) { + if (argv[i] == strstr(argv[i], "--min-working-set-size=")) { + const char* equals_sign = strchr(argv[i], '='); + min_working_set_size = strtoul(equals_sign+1, nullptr, 10); + } else { + cerr << "unrecognized option: " << argv[i] << endl << endl; + show_usage_and_exit(argc, argv, available_actions); + } + } + + print_cpuinfo(); + + cout << "benchmark parameters:" << endl; + cout << "pointer size: " << 8*sizeof(void*) << " bits" << endl; + cout << "scalar type: " << type_name() << endl; + cout << "packet size: " << internal::packet_traits::size << endl; + cout << "minsize = " << minsize << endl; + cout << "maxsize = " << maxsize << endl; + cout << "measurement_repetitions = " << measurement_repetitions << endl; + cout << "min_accurate_time = " << min_accurate_time << endl; + cout << "min_working_set_size = " << min_working_set_size; + if (min_working_set_size == 0) { + cout << " (try to outsize caches)"; + } + cout << endl << endl; + + (*action)->run(); + + double time_end = timer.getRealTime(); + cerr << "Finished in " << human_duration_t(time_end - time_start) << endl; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c721b908179ede86f57c56563b5dfb252aff4d2a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark.cpp @@ -0,0 +1,39 @@ +// g++ -O3 -DNDEBUG -DMATSIZE= benchmark.cpp -o benchmark && time ./benchmark + +#include + +#include + +#ifndef MATSIZE +#define MATSIZE 3 +#endif + +using namespace std; +using namespace Eigen; + +#ifndef REPEAT +#define REPEAT 40000000 +#endif + +#ifndef SCALAR +#define SCALAR double +#endif + +int main(int argc, char *argv[]) +{ + Matrix I = Matrix::Ones(); + Matrix m; + for(int i = 0; i < MATSIZE; i++) + for(int j = 0; j < MATSIZE; j++) + { + m(i,j) = (i+MATSIZE*j); + } + asm("#begin"); + for(int a = 0; a < REPEAT; a++) + { + m = Matrix::Ones() + 0.00005 * (m + (m*m)); + } + asm("#end"); + cout << m << endl; + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkSlice.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkSlice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5b89c545572c77e285e30231fed1c5f4330b693 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkSlice.cpp @@ -0,0 +1,38 @@ +// g++ -O3 -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX + +#include + +#include + +using namespace std; +using namespace Eigen; + +#ifndef REPEAT +#define REPEAT 10000 +#endif + +#ifndef SCALAR +#define SCALAR float +#endif + +int main(int argc, char *argv[]) +{ + typedef Matrix Mat; + Mat m(100, 100); + m.setRandom(); + + for(int a = 0; a < REPEAT; a++) + { + int r, c, nr, nc; + r = Eigen::internal::random(0,10); + c = Eigen::internal::random(0,10); + nr = Eigen::internal::random(50,80); + nc = Eigen::internal::random(50,80); + m.block(r,c,nr,nc) += Mat::Ones(nr,nc); + m.block(r,c,nr,nc) *= SCALAR(10); + m.block(r,c,nr,nc) -= Mat::constant(nr,nc,10); + m.block(r,c,nr,nc) /= SCALAR(10); + } + cout << m[0] << endl; + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkX.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkX.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e4b60c2b7dd5718655a00317c3edba30014fd29 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkX.cpp @@ -0,0 +1,36 @@ +// g++ -fopenmp -I .. -O3 -DNDEBUG -finline-limit=1000 benchmarkX.cpp -o b && time ./b + +#include + +#include + +using namespace std; +using namespace Eigen; + +#ifndef MATTYPE +#define MATTYPE MatrixXLd +#endif + +#ifndef MATSIZE +#define MATSIZE 400 +#endif + +#ifndef REPEAT +#define REPEAT 100 +#endif + +int main(int argc, char *argv[]) +{ + MATTYPE I = MATTYPE::Ones(MATSIZE,MATSIZE); + MATTYPE m(MATSIZE,MATSIZE); + for(int i = 0; i < MATSIZE; i++) for(int j = 0; j < MATSIZE; j++) + { + m(i,j) = (i+j+1)/(MATSIZE*MATSIZE); + } + for(int a = 0; a < REPEAT; a++) + { + m = I + 0.0001 * (m + m*m); + } + cout << m(0,0) << endl; + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkXcwise.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkXcwise.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62437435efc25a090809b3caeb147e51aa0080ab --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmarkXcwise.cpp @@ -0,0 +1,35 @@ +// g++ -O3 -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX + +#include +#include + +using namespace std; +using namespace Eigen; + +#ifndef VECTYPE +#define VECTYPE VectorXLd +#endif + +#ifndef VECSIZE +#define VECSIZE 1000000 +#endif + +#ifndef REPEAT +#define REPEAT 1000 +#endif + +int main(int argc, char *argv[]) +{ + VECTYPE I = VECTYPE::Ones(VECSIZE); + VECTYPE m(VECSIZE,1); + for(int i = 0; i < VECSIZE; i++) + { + m[i] = 0.1 * i/VECSIZE; + } + for(int a = 0; a < REPEAT; a++) + { + m = VECTYPE::Ones(VECSIZE) + 0.00005 * (m.cwise().square() + m/4); + } + cout << m[0] << endl; + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark_suite b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark_suite new file mode 100644 index 0000000000000000000000000000000000000000..3f21d366178817a790340049dd3fcdab0f42b5a5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/benchmark_suite @@ -0,0 +1,18 @@ +#!/bin/bash +CXX=${CXX-g++} # default value unless caller has defined CXX +echo "Fixed size 3x3, column-major, -DNDEBUG" +$CXX -O3 -I .. -DNDEBUG benchmark.cpp -o benchmark && time ./benchmark >/dev/null +echo "Fixed size 3x3, column-major, with asserts" +$CXX -O3 -I .. benchmark.cpp -o benchmark && time ./benchmark >/dev/null +echo "Fixed size 3x3, row-major, -DNDEBUG" +$CXX -O3 -I .. -DEIGEN_DEFAULT_TO_ROW_MAJOR -DNDEBUG benchmark.cpp -o benchmark && time ./benchmark >/dev/null +echo "Fixed size 3x3, row-major, with asserts" +$CXX -O3 -I .. -DEIGEN_DEFAULT_TO_ROW_MAJOR benchmark.cpp -o benchmark && time ./benchmark >/dev/null +echo "Dynamic size 20x20, column-major, -DNDEBUG" +$CXX -O3 -I .. -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX >/dev/null +echo "Dynamic size 20x20, column-major, with asserts" +$CXX -O3 -I .. benchmarkX.cpp -o benchmarkX && time ./benchmarkX >/dev/null +echo "Dynamic size 20x20, row-major, -DNDEBUG" +$CXX -O3 -I .. -DEIGEN_DEFAULT_TO_ROW_MAJOR -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX >/dev/null +echo "Dynamic size 20x20, row-major, with asserts" +$CXX -O3 -I .. -DEIGEN_DEFAULT_TO_ROW_MAJOR benchmarkX.cpp -o benchmarkX && time ./benchmarkX >/dev/null diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..38ff9f483284b1749b0adba445e82f99612c515c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/CMakeLists.txt @@ -0,0 +1,107 @@ +PROJECT(BTL) + +CMAKE_MINIMUM_REQUIRED(VERSION 2.6.2) + +set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake ${Eigen_SOURCE_DIR}/cmake) +include(MacroOptionalAddSubdirectory) + +OPTION(BTL_NOVEC "Disable SSE/Altivec optimizations when possible" OFF) + +SET(CMAKE_INCLUDE_CURRENT_DIR ON) + +string(REGEX MATCH icpc IS_ICPC ${CMAKE_CXX_COMPILER}) +IF(CMAKE_COMPILER_IS_GNUCXX OR IS_ICPC) + SET(CMAKE_CXX_FLAGS "-g0 -O3 -DNDEBUG ${CMAKE_CXX_FLAGS}") + SET(CMAKE_Fortran_FLAGS "-g0 -O3 -DNDEBUG ${CMAKE_Fortran_FLAGS}") + IF(BTL_NOVEC) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DEIGEN_DONT_VECTORIZE") + ENDIF(BTL_NOVEC) +ENDIF(CMAKE_COMPILER_IS_GNUCXX OR IS_ICPC) + +IF(MSVC) + SET(CMAKE_CXX_FLAGS " /O2 /Ot /GL /fp:fast -DNDEBUG") +# SET(CMAKE_Fortran_FLAGS "-g0 -O3 -DNDEBUG") + IF(BTL_NOVEC) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DEIGEN_DONT_VECTORIZE") + ENDIF(BTL_NOVEC) +ENDIF(MSVC) + +if(IS_ICPC) + set(CMAKE_CXX_FLAGS "-fast ${CMAKE_CXX_FLAGS}") + set(CMAKE_Fortran_FLAGS "-fast ${CMAKE_Fortran_FLAGS}") +endif(IS_ICPC) + +include_directories( + ${PROJECT_SOURCE_DIR}/actions + ${PROJECT_SOURCE_DIR}/generic_bench + ${PROJECT_SOURCE_DIR}/generic_bench/utils + ${PROJECT_SOURCE_DIR}/libs/STL) + +# find_package(MKL) +# if (MKL_FOUND) +# add_definitions(-DHAVE_MKL) +# set(DEFAULT_LIBRARIES ${MKL_LIBRARIES}) +# endif (MKL_FOUND) + +find_library(EIGEN_BTL_RT_LIBRARY rt) +# if we cannot find it easily, then we don't need it! +if(NOT EIGEN_BTL_RT_LIBRARY) + set(EIGEN_BTL_RT_LIBRARY "") +endif() + +MACRO(BTL_ADD_BENCH targetname) + + foreach(_current_var ${ARGN}) + set(_last_var ${_current_var}) + endforeach(_current_var) + + set(_sources ${ARGN}) + list(LENGTH _sources _argn_length) + + list(REMOVE_ITEM _sources ON OFF TRUE FALSE) + + list(LENGTH _sources _src_length) + + if (${_argn_length} EQUAL ${_src_length}) + set(_last_var ON) + endif (${_argn_length} EQUAL ${_src_length}) + + OPTION(BUILD_${targetname} "Build benchmark ${targetname}" ${_last_var}) + + IF(BUILD_${targetname}) + ADD_EXECUTABLE(${targetname} ${_sources}) + ADD_TEST(${targetname} "${targetname}") + target_link_libraries(${targetname} ${DEFAULT_LIBRARIES} ${EIGEN_BTL_RT_LIBRARY}) + ENDIF(BUILD_${targetname}) + +ENDMACRO(BTL_ADD_BENCH) + +macro(btl_add_target_property target prop value) + + if(BUILD_${target}) + get_target_property(previous ${target} ${prop}) + if(NOT previous) + set(previous "") + endif() + set_target_properties(${target} PROPERTIES ${prop} "${previous} ${value}") + endif() + +endmacro(btl_add_target_property) + +ENABLE_TESTING() + +add_subdirectory(libs/eigen3) +add_subdirectory(libs/eigen2) +add_subdirectory(libs/tensors) +add_subdirectory(libs/BLAS) +add_subdirectory(libs/ublas) +add_subdirectory(libs/gmm) +add_subdirectory(libs/mtl4) +add_subdirectory(libs/blitz) +add_subdirectory(libs/tvmet) +add_subdirectory(libs/STL) +add_subdirectory(libs/blaze) + +add_subdirectory(data) + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/COPYING b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..486449cc3a4ea92893622b41c5a24ee0b6c96499 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/COPYING @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/README b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/README new file mode 100644 index 0000000000000000000000000000000000000000..f3f5fb36f783e2edbe76453ab274eafc04f07beb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/README @@ -0,0 +1,154 @@ +Bench Template Library + +**************************************** +Introduction : + +The aim of this project is to compare the performance +of available numerical libraries. The code is designed +as generic and modular as possible. Thus, adding new +numerical libraries or new numerical tests should +require minimal effort. + + +***************************************** + +Installation : + +BTL uses cmake / ctest: + +1 - create a build directory: + + $ mkdir build + $ cd build + +2 - configure: + + $ ccmake .. + +3 - run the bench using ctest: + + $ ctest -V + +You can run the benchmarks only on libraries matching a given regular expression: + ctest -V -R +For instance: + ctest -V -R eigen2 + +You can also select a given set of actions defining the environment variable BTL_CONFIG this way: + BTL_CONFIG="-a action1{:action2}*" ctest -V +An exemple: + BTL_CONFIG="-a axpy:vector_matrix:trisolve:ata" ctest -V -R eigen2 + +Finally, if bench results already exist (the bench*.dat files) then they merges by keeping the best for each matrix size. If you want to overwrite the previous ones you can simply add the "--overwrite" option: + BTL_CONFIG="-a axpy:vector_matrix:trisolve:ata --overwrite" ctest -V -R eigen2 + +4 : Analyze the result. different data files (.dat) are produced in each libs directories. + If gnuplot is available, choose a directory name in the data directory to store the results and type: + $ cd data + $ mkdir my_directory + $ cp ../libs/*/*.dat my_directory + Build the data utilities in this (data) directory + make + Then you can look the raw data, + go_mean my_directory + or smooth the data first : + smooth_all.sh my_directory + go_mean my_directory_smooth + + +************************************************* + +Files and directories : + + generic_bench : all the bench sources common to all libraries + + actions : sources for different action wrappers (axpy, matrix-matrix product) to be tested. + + libs/* : bench sources specific to each tested libraries. + + machine_dep : directory used to store machine specific Makefile.in + + data : directory used to store gnuplot scripts and data analysis utilities + +************************************************** + +Principles : the code modularity is achieved by defining two concepts : + + ****** Action concept : This is a class defining which kind + of test must be performed (e.g. a matrix_vector_product). + An Action should define the following methods : + + *** Ctor using the size of the problem (matrix or vector size) as an argument + Action action(size); + *** initialize : this method initialize the calculation (e.g. initialize the matrices and vectors arguments) + action.initialize(); + *** calculate : this method actually launch the calculation to be benchmarked + action.calculate; + *** nb_op_base() : this method returns the complexity of the calculate method (allowing the mflops evaluation) + *** name() : this method returns the name of the action (std::string) + + ****** Interface concept : This is a class or namespace defining how to use a given library and + its specific containers (matrix and vector). Up to now an interface should following types + + *** real_type : kind of float to be used (float or double) + *** stl_vector : must correspond to std::vector + *** stl_matrix : must correspond to std::vector + *** gene_vector : the vector type for this interface --> e.g. (real_type *) for the C_interface + *** gene_matrix : the matrix type for this interface --> e.g. (gene_vector *) for the C_interface + + + the following common methods + + *** free_matrix(gene_matrix & A, int N) dealocation of a N sized gene_matrix A + *** free_vector(gene_vector & B) dealocation of a N sized gene_vector B + *** matrix_from_stl(gene_matrix & A, stl_matrix & A_stl) copy the content of an stl_matrix A_stl into a gene_matrix A. + The allocation of A is done in this function. + *** vector_to_stl(gene_vector & B, stl_vector & B_stl) copy the content of an stl_vector B_stl into a gene_vector B. + The allocation of B is done in this function. + *** matrix_to_stl(gene_matrix & A, stl_matrix & A_stl) copy the content of an gene_matrix A into an stl_matrix A_stl. + The size of A_STL must corresponds to the size of A. + *** vector_to_stl(gene_vector & A, stl_vector & A_stl) copy the content of an gene_vector A into an stl_vector A_stl. + The size of B_STL must corresponds to the size of B. + *** copy_matrix(gene_matrix & source, gene_matrix & cible, int N) : copy the content of source in cible. Both source + and cible must be sized NxN. + *** copy_vector(gene_vector & source, gene_vector & cible, int N) : copy the content of source in cible. Both source + and cible must be sized N. + + and the following method corresponding to the action one wants to be benchmarked : + + *** matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int N) + *** matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N) + *** ata_product(const gene_matrix & A, gene_matrix & X, int N) + *** aat_product(const gene_matrix & A, gene_matrix & X, int N) + *** axpy(real coef, const gene_vector & X, gene_vector & Y, int N) + + The bench algorithm (generic_bench/bench.hh) is templated with an action itself templated with + an interface. A typical main.cpp source stored in a given library directory libs/A_LIB + looks like : + + bench< AN_ACTION < AN_INTERFACE > >( 10 , 1000 , 50 ) ; + + this function will produce XY data file containing measured mflops as a function of the size for 50 + sizes between 10 and 10000. + + This algorithm can be adapted by providing a given Perf_Analyzer object which determines how the time + measurements must be done. For example, the X86_Perf_Analyzer use the asm rdtsc function and provides + a very fast and accurate (but less portable) timing method. The default is the Portable_Perf_Analyzer + so + + bench< AN_ACTION < AN_INTERFACE > >( 10 , 1000 , 50 ) ; + + is equivalent to + + bench< Portable_Perf_Analyzer,AN_ACTION < AN_INTERFACE > >( 10 , 1000 , 50 ) ; + + If your system supports it we suggest to use a mixed implementation (X86_perf_Analyzer+Portable_Perf_Analyzer). + replace + bench(size_min,size_max,nb_point); + with + bench(size_min,size_max,nb_point); + in generic/bench.hh + +. + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_aat_product.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_aat_product.hh new file mode 100644 index 0000000000000000000000000000000000000000..aa5b35c94f298eb7775f49ddf93836135e6829ce --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_aat_product.hh @@ -0,0 +1,145 @@ +//===================================================== +// File : action_aat_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_AAT_PRODUCT +#define ACTION_AAT_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_aat_product { + +public : + + // Ctor + + Action_aat_product( int size ):_size(size) + { + MESSAGE("Action_aat_product Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_matrix(X_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(X_ref,X_stl); + + Interface::matrix_from_stl(A,A_stl); + Interface::matrix_from_stl(X,X_stl); + + } + + // invalidate copy ctor + + Action_aat_product( const Action_aat_product & ) + { + INFOS("illegal call to Action_aat_product Copy Ctor"); + exit(0); + } + + // Dtor + + ~Action_aat_product( void ){ + + MESSAGE("Action_aat_product Dtor"); + + // deallocation + + Interface::free_matrix(A,_size); + Interface::free_matrix(X,_size); + + Interface::free_matrix(A_ref,_size); + Interface::free_matrix(X_ref,_size); + + } + + // action name + + static inline std::string name( void ) + { + return "aat_"+Interface::name(); + } + + double nb_op_base( void ){ + return double(_size)*double(_size)*double(_size); + } + + inline void initialize( void ){ + + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_matrix(X_ref,X,_size); + + } + + inline void calculate( void ) { + + Interface::aat_product(A,X,_size); + + } + + void check_result( void ){ + if (_size>128) return; + // calculation check + + Interface::matrix_to_stl(X,resu_stl); + + STL_interface::aat_product(A_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(1); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix X; + + + int _size; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ata_product.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ata_product.hh new file mode 100644 index 0000000000000000000000000000000000000000..04364fe6756e071477f8dd19d975168ad5a904a2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ata_product.hh @@ -0,0 +1,145 @@ +//===================================================== +// File : action_ata_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_ATA_PRODUCT +#define ACTION_ATA_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_ata_product { + +public : + + // Ctor + + Action_ata_product( int size ):_size(size) + { + MESSAGE("Action_ata_product Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_matrix(X_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(X_ref,X_stl); + + Interface::matrix_from_stl(A,A_stl); + Interface::matrix_from_stl(X,X_stl); + + } + + // invalidate copy ctor + + Action_ata_product( const Action_ata_product & ) + { + INFOS("illegal call to Action_ata_product Copy Ctor"); + exit(0); + } + + // Dtor + + ~Action_ata_product( void ){ + + MESSAGE("Action_ata_product Dtor"); + + // deallocation + + Interface::free_matrix(A,_size); + Interface::free_matrix(X,_size); + + Interface::free_matrix(A_ref,_size); + Interface::free_matrix(X_ref,_size); + + } + + // action name + + static inline std::string name( void ) + { + return "ata_"+Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size*_size; + } + + inline void initialize( void ){ + + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_matrix(X_ref,X,_size); + + } + + inline void calculate( void ) { + + Interface::ata_product(A,X,_size); + + } + + void check_result( void ){ + if (_size>128) return; + // calculation check + + Interface::matrix_to_stl(X,resu_stl); + + STL_interface::ata_product(A_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(1); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix X; + + + int _size; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_atv_product.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_atv_product.hh new file mode 100644 index 0000000000000000000000000000000000000000..a8234514bff380873d82f181e866db67b42918b2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_atv_product.hh @@ -0,0 +1,134 @@ +//===================================================== +// File : action_atv_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_ATV_PRODUCT +#define ACTION_ATV_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_atv_product { + +public : + + Action_atv_product( int size ) : _size(size) + { + MESSAGE("Action_atv_product Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(X_ref,X_stl); + + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X,X_stl); + } + + // invalidate copy ctor + Action_atv_product( const Action_atv_product & ) + { + INFOS("illegal call to Action_atv_product Copy Ctor"); + exit(1); + } + + ~Action_atv_product( void ) + { + MESSAGE("Action_atv_product Dtor"); + + Interface::free_matrix(A,_size); + Interface::free_vector(B); + Interface::free_vector(X); + + Interface::free_matrix(A_ref,_size); + Interface::free_vector(B_ref); + Interface::free_vector(X_ref); + } + + static inline std::string name() { return "atv_" + Interface::name(); } + + double nb_op_base( void ) { return 2.0*_size*_size; } + + inline void initialize( void ){ + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + Interface::copy_vector(X_ref,X,_size); + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("begin atv"); + Interface::atv_product(A,B,X,_size); + BTL_ASM_COMMENT("end atv"); + } + + void check_result( void ) + { + if (_size>128) return; + Interface::vector_to_stl(X,resu_stl); + + STL_interface::atv_product(A_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(1); + } + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_vector B_ref; + typename Interface::gene_vector X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + + int _size; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpby.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpby.hh new file mode 100644 index 0000000000000000000000000000000000000000..dadd0ccf3ca0340f8643a7d373d689245b9c819c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpby.hh @@ -0,0 +1,127 @@ +//===================================================== +// File : action_axpby.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_AXPBY +#define ACTION_AXPBY +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_axpby { + +public : + + // Ctor + Action_axpby( int size ):_alpha(0.5),_beta(0.95),_size(size) + { + MESSAGE("Action_axpby Ctor"); + + // STL vector initialization + init_vector(X_stl,_size); + init_vector(Y_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(Y_ref,Y_stl); + + Interface::vector_from_stl(X,X_stl); + Interface::vector_from_stl(Y,Y_stl); + } + + // invalidate copy ctor + Action_axpby( const Action_axpby & ) + { + INFOS("illegal call to Action_axpby Copy Ctor"); + exit(1); + } + + // Dtor + ~Action_axpby( void ){ + MESSAGE("Action_axpby Dtor"); + + // deallocation + Interface::free_vector(X_ref); + Interface::free_vector(Y_ref); + + Interface::free_vector(X); + Interface::free_vector(Y); + } + + // action name + static inline std::string name( void ) + { + return "axpby_"+Interface::name(); + } + + double nb_op_base( void ){ + return 3.0*_size; + } + + inline void initialize( void ){ + Interface::copy_vector(X_ref,X,_size); + Interface::copy_vector(Y_ref,Y,_size); + } + + inline void calculate( void ) { + BTL_ASM_COMMENT("mybegin axpby"); + Interface::axpby(_alpha,X,_beta,Y,_size); + BTL_ASM_COMMENT("myend axpby"); + } + + void check_result( void ){ + if (_size>128) return; + // calculation check + Interface::vector_to_stl(Y,resu_stl); + + STL_interface::axpby(_alpha,X_stl,_beta,Y_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(Y_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(2); + } + } + +private : + + typename Interface::stl_vector X_stl; + typename Interface::stl_vector Y_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_vector X_ref; + typename Interface::gene_vector Y_ref; + + typename Interface::gene_vector X; + typename Interface::gene_vector Y; + + typename Interface::real_type _alpha; + typename Interface::real_type _beta; + + int _size; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpy.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpy.hh new file mode 100644 index 0000000000000000000000000000000000000000..261be4cb8eb9dca0b673852330ab40291ee07d29 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_axpy.hh @@ -0,0 +1,139 @@ +//===================================================== +// File : action_axpy.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_AXPY +#define ACTION_AXPY +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_axpy { + +public : + + // Ctor + + Action_axpy( int size ):_coef(1.0),_size(size) + { + MESSAGE("Action_axpy Ctor"); + + // STL vector initialization + + init_vector(X_stl,_size); + init_vector(Y_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(Y_ref,Y_stl); + + Interface::vector_from_stl(X,X_stl); + Interface::vector_from_stl(Y,Y_stl); + + + } + + // invalidate copy ctor + + Action_axpy( const Action_axpy & ) + { + INFOS("illegal call to Action_axpy Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_axpy( void ){ + + MESSAGE("Action_axpy Dtor"); + + // deallocation + + Interface::free_vector(X_ref); + Interface::free_vector(Y_ref); + + Interface::free_vector(X); + Interface::free_vector(Y); + } + + // action name + + static inline std::string name( void ) + { + return "axpy_"+Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size; + } + + inline void initialize( void ){ + Interface::copy_vector(X_ref,X,_size); + Interface::copy_vector(Y_ref,Y,_size); + } + + inline void calculate( void ) { + BTL_ASM_COMMENT("mybegin axpy"); + Interface::axpy(_coef,X,Y,_size); + BTL_ASM_COMMENT("myend axpy"); + } + + void check_result( void ){ + if (_size>128) return; + // calculation check + + Interface::vector_to_stl(Y,resu_stl); + + STL_interface::axpy(_coef,X_stl,Y_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(Y_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(0); + } + + } + +private : + + typename Interface::stl_vector X_stl; + typename Interface::stl_vector Y_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_vector X_ref; + typename Interface::gene_vector Y_ref; + + typename Interface::gene_vector X; + typename Interface::gene_vector Y; + + typename Interface::real_type _coef; + + int _size; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_cholesky.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_cholesky.hh new file mode 100644 index 0000000000000000000000000000000000000000..5f66d113afe0d721a9a3d048db5c3f27275fed64 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_cholesky.hh @@ -0,0 +1,128 @@ +//===================================================== +// File : action_cholesky.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_CHOLESKY +#define ACTION_CHOLESKY +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_cholesky { + +public : + + // Ctor + + Action_cholesky( int size ):_size(size) + { + MESSAGE("Action_cholesky Ctor"); + + // STL mat/vec initialization + init_matrix_symm(X_stl,_size); + init_matrix(C_stl,_size); + + // make sure X is invertible + for (int i=0; i<_size; ++i) + X_stl[i][i] = std::abs(X_stl[i][i]) * 1e2 + 100; + + // generic matrix and vector initialization + Interface::matrix_from_stl(X_ref,X_stl); + Interface::matrix_from_stl(X,X_stl); + Interface::matrix_from_stl(C,C_stl); + + _cost = 0; + for (int j=0; j<_size; ++j) + { + double r = std::max(_size - j -1,0); + _cost += 2*(r*j+r+j); + } + } + + // invalidate copy ctor + + Action_cholesky( const Action_cholesky & ) + { + INFOS("illegal call to Action_cholesky Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_cholesky( void ){ + + MESSAGE("Action_cholesky Dtor"); + + // deallocation + Interface::free_matrix(X_ref,_size); + Interface::free_matrix(X,_size); + Interface::free_matrix(C,_size); + } + + // action name + + static inline std::string name( void ) + { + return "cholesky_"+Interface::name(); + } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + Interface::copy_matrix(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::cholesky(X,C,_size); + } + + void check_result( void ){ + // calculation check +// STL_interface::cholesky(X_stl,C_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(C_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix C_stl; + + typename Interface::gene_matrix X_ref; + typename Interface::gene_matrix X; + typename Interface::gene_matrix C; + + int _size; + double _cost; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ger.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ger.hh new file mode 100644 index 0000000000000000000000000000000000000000..dc766efc597ff184a46672c09157a12b10d57d03 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_ger.hh @@ -0,0 +1,128 @@ + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_GER +#define ACTION_GER +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_ger { + +public : + + // Ctor + BTL_DONT_INLINE Action_ger( int size ):_size(size) + { + MESSAGE("Action_ger Ctor"); + + // STL matrix and vector initialization + typename Interface::stl_matrix tmp; + init_matrix(A_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(X,X_stl); + } + + // invalidate copy ctor + Action_ger( const Action_ger & ) + { + INFOS("illegal call to Action_ger Copy Ctor"); + exit(1); + } + + // Dtor + BTL_DONT_INLINE ~Action_ger( void ){ + MESSAGE("Action_ger Dtor"); + Interface::free_matrix(A,_size); + Interface::free_vector(B); + Interface::free_vector(X); + Interface::free_matrix(A_ref,_size); + Interface::free_vector(B_ref); + Interface::free_vector(X_ref); + + } + + // action name + static inline std::string name( void ) + { + return "ger_" + Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size; + } + + BTL_DONT_INLINE void initialize( void ){ + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + Interface::copy_vector(X_ref,X,_size); + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("#begin ger"); + Interface::ger(A,B,X,_size); + BTL_ASM_COMMENT("end ger"); + } + + BTL_DONT_INLINE void check_result( void ){ + // calculation check + Interface::vector_to_stl(X,resu_stl); + + STL_interface::ger(A_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-3){ + INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_vector B_ref; + typename Interface::gene_vector X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + int _size; +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_hessenberg.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_hessenberg.hh new file mode 100644 index 0000000000000000000000000000000000000000..2100ebd89053072ffc9341ffa49d0c875cdb9138 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_hessenberg.hh @@ -0,0 +1,233 @@ +//===================================================== +// File : action_hessenberg.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_HESSENBERG +#define ACTION_HESSENBERG +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_hessenberg { + +public : + + // Ctor + + Action_hessenberg( int size ):_size(size) + { + MESSAGE("Action_hessenberg Ctor"); + + // STL vector initialization + init_matrix(X_stl,_size); + + init_matrix(C_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(X_ref,X_stl); + Interface::matrix_from_stl(X,X_stl); + Interface::matrix_from_stl(C,C_stl); + + _cost = 0; + for (int j=0; j<_size-2; ++j) + { + double r = std::max(0,_size-j-1); + double b = std::max(0,_size-j-2); + _cost += 6 + 3*b + r*r*4 + r*_size*4; + } + } + + // invalidate copy ctor + + Action_hessenberg( const Action_hessenberg & ) + { + INFOS("illegal call to Action_hessenberg Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_hessenberg( void ){ + + MESSAGE("Action_hessenberg Dtor"); + + // deallocation + Interface::free_matrix(X_ref,_size); + Interface::free_matrix(X,_size); + Interface::free_matrix(C,_size); + } + + // action name + + static inline std::string name( void ) + { + return "hessenberg_"+Interface::name(); + } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + Interface::copy_matrix(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::hessenberg(X,C,_size); + } + + void check_result( void ){ + // calculation check + Interface::matrix_to_stl(C,resu_stl); + +// STL_interface::hessenberg(X_stl,C_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(C_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix C_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix X_ref; + typename Interface::gene_matrix X; + typename Interface::gene_matrix C; + + int _size; + double _cost; +}; + +template +class Action_tridiagonalization { + +public : + + // Ctor + + Action_tridiagonalization( int size ):_size(size) + { + MESSAGE("Action_tridiagonalization Ctor"); + + // STL vector initialization + init_matrix(X_stl,_size); + + for(int i=0; i<_size; ++i) + { + for(int j=0; j(C_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(X_ref,X_stl); + Interface::matrix_from_stl(X,X_stl); + Interface::matrix_from_stl(C,C_stl); + + _cost = 0; + for (int j=0; j<_size-2; ++j) + { + double r = std::max(0,_size-j-1); + double b = std::max(0,_size-j-2); + _cost += 6. + 3.*b + r*r*8.; + } + } + + // invalidate copy ctor + + Action_tridiagonalization( const Action_tridiagonalization & ) + { + INFOS("illegal call to Action_tridiagonalization Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_tridiagonalization( void ){ + + MESSAGE("Action_tridiagonalization Dtor"); + + // deallocation + Interface::free_matrix(X_ref,_size); + Interface::free_matrix(X,_size); + Interface::free_matrix(C,_size); + } + + // action name + + static inline std::string name( void ) { return "tridiagonalization_"+Interface::name(); } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + Interface::copy_matrix(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::tridiagonalization(X,C,_size); + } + + void check_result( void ){ + // calculation check + Interface::matrix_to_stl(C,resu_stl); + +// STL_interface::tridiagonalization(X_stl,C_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(C_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix C_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix X_ref; + typename Interface::gene_matrix X; + typename Interface::gene_matrix C; + + int _size; + double _cost; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_decomp.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_decomp.hh new file mode 100644 index 0000000000000000000000000000000000000000..2448e82c42bddfecbe25d070c0c5df061bf70579 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_decomp.hh @@ -0,0 +1,124 @@ +//===================================================== +// File : action_lu_decomp.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_LU_DECOMP +#define ACTION_LU_DECOMP +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_lu_decomp { + +public : + + // Ctor + + Action_lu_decomp( int size ):_size(size) + { + MESSAGE("Action_lu_decomp Ctor"); + + // STL vector initialization + init_matrix(X_stl,_size); + + init_matrix(C_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(X_ref,X_stl); + Interface::matrix_from_stl(X,X_stl); + Interface::matrix_from_stl(C,C_stl); + + _cost = 2.0*size*size*size/3.0 + size*size; + } + + // invalidate copy ctor + + Action_lu_decomp( const Action_lu_decomp & ) + { + INFOS("illegal call to Action_lu_decomp Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_lu_decomp( void ){ + + MESSAGE("Action_lu_decomp Dtor"); + + // deallocation + Interface::free_matrix(X_ref,_size); + Interface::free_matrix(X,_size); + Interface::free_matrix(C,_size); + } + + // action name + + static inline std::string name( void ) + { + return "complete_lu_decomp_"+Interface::name(); + } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + Interface::copy_matrix(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::lu_decomp(X,C,_size); + } + + void check_result( void ){ + // calculation check + Interface::matrix_to_stl(C,resu_stl); + +// STL_interface::lu_decomp(X_stl,C_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(C_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix C_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix X_ref; + typename Interface::gene_matrix X; + typename Interface::gene_matrix C; + + int _size; + double _cost; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_solve.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_solve.hh new file mode 100644 index 0000000000000000000000000000000000000000..5a81e6341ea4e4247cd91228b365b63033944139 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_lu_solve.hh @@ -0,0 +1,136 @@ +//===================================================== +// File : action_lu_solve.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_LU_SOLVE +#define ACTION_LU_SOLVE +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_lu_solve +{ + +public : + + static inline std::string name( void ) + { + return "lu_solve_"+Interface::name(); + } + + static double nb_op_base(int size){ + return 2.0*size*size*size/3.0; // questionable but not really important + } + + + static double calculate( int nb_calc, int size ) { + + // STL matrix and vector initialization + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + + init_matrix(A_stl,size); + init_vector(B_stl,size); + init_vector(X_stl,size); + + // generic matrix and vector initialization + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + typename Interface::gene_matrix LU; + + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X,X_stl); + Interface::matrix_from_stl(LU,A_stl); + + // local variable : + + typename Interface::Pivot_Vector pivot; // pivot vector + Interface::new_Pivot_Vector(pivot,size); + + // timer utilities + + Portable_Timer chronos; + + // time measurement + + chronos.start(); + + for (int ii=0;ii::matrix_vector_product(A_stl,X_stl,B_new_stl,size); + + typename Interface::real_type error= + STL_interface::norm_diff(B_stl,B_new_stl); + + if (error>1.e-5){ + INFOS("WRONG CALCULATION...residual=" << error); + STL_interface::display_vector(B_stl); + STL_interface::display_vector(B_new_stl); + exit(0); + } + + // deallocation and return time + + Interface::free_matrix(A,size); + Interface::free_vector(B); + Interface::free_vector(X); + Interface::free_Pivot_Vector(pivot); + + return time; + } + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product.hh new file mode 100644 index 0000000000000000000000000000000000000000..f65ee0529090b77efe326bb2c6b13d8a0b913dd2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product.hh @@ -0,0 +1,150 @@ +//===================================================== +// File : action_matrix_matrix_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_MATRIX_MATRIX_PRODUCT +#define ACTION_MATRIX_MATRIX_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_matrix_matrix_product { + +public : + + // Ctor + + Action_matrix_matrix_product( int size ):_size(size) + { + MESSAGE("Action_matrix_matrix_product Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_matrix(B_stl,_size); + init_matrix(X_stl,_size); + init_matrix(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(B_ref,B_stl); + Interface::matrix_from_stl(X_ref,X_stl); + + Interface::matrix_from_stl(A,A_stl); + Interface::matrix_from_stl(B,B_stl); + Interface::matrix_from_stl(X,X_stl); + + } + + // invalidate copy ctor + + Action_matrix_matrix_product( const Action_matrix_matrix_product & ) + { + INFOS("illegal call to Action_matrix_matrix_product Copy Ctor"); + exit(0); + } + + // Dtor + + ~Action_matrix_matrix_product( void ){ + + MESSAGE("Action_matrix_matrix_product Dtor"); + + // deallocation + + Interface::free_matrix(A,_size); + Interface::free_matrix(B,_size); + Interface::free_matrix(X,_size); + + Interface::free_matrix(A_ref,_size); + Interface::free_matrix(B_ref,_size); + Interface::free_matrix(X_ref,_size); + + } + + // action name + + static inline std::string name( void ) + { + return "matrix_matrix_"+Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size*_size; + } + + inline void initialize( void ){ + + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_matrix(B_ref,B,_size); + Interface::copy_matrix(X_ref,X,_size); + + } + + inline void calculate( void ) { + Interface::matrix_matrix_product(A,B,X,_size); + } + + void check_result( void ){ + + // calculation check + if (_size<200) + { + Interface::matrix_to_stl(X,resu_stl); + STL_interface::matrix_matrix_product(A_stl,B_stl,X_stl,_size); + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(1); + } + } + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix B_stl; + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix B_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix B; + typename Interface::gene_matrix X; + + + int _size; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product_bis.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product_bis.hh new file mode 100644 index 0000000000000000000000000000000000000000..29c10a6e2742d278fb6384d59832f0fc297f1b81 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_matrix_product_bis.hh @@ -0,0 +1,152 @@ +//===================================================== +// File : action_matrix_matrix_product_bis.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_MATRIX_MATRIX_PRODUCT_BIS +#define ACTION_MATRIX_MATRIX_PRODUCT_BIS +#include "utilities.h" +#include "STL_interface.hh" +#include "STL_timer.hh" +#include +#include "init_function.hh" +#include "init_vector.hh" +#include "init_matrix.hh" + +using namespace std; + +template +class Action_matrix_matrix_product_bis { + +public : + + static inline std::string name( void ) + { + return "matrix_matrix_"+Interface::name(); + } + + static double nb_op_base(int size){ + return 2.0*size*size*size; + } + + static double calculate( int nb_calc, int size ) { + + // STL matrix and vector initialization + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix B_stl; + typename Interface::stl_matrix X_stl; + + init_matrix(A_stl,size); + init_matrix(B_stl,size); + init_matrix(X_stl,size); + + // generic matrix and vector initialization + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix B_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix B; + typename Interface::gene_matrix X; + + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(B_ref,B_stl); + Interface::matrix_from_stl(X_ref,X_stl); + + Interface::matrix_from_stl(A,A_stl); + Interface::matrix_from_stl(B,B_stl); + Interface::matrix_from_stl(X,X_stl); + + + // STL_timer utilities + + STL_timer chronos; + + // Baseline evaluation + + chronos.start_baseline(nb_calc); + + do { + + Interface::copy_matrix(A_ref,A,size); + Interface::copy_matrix(B_ref,B,size); + Interface::copy_matrix(X_ref,X,size); + + + // Interface::matrix_matrix_product(A,B,X,size); This line must be commented !!!! + } + while(chronos.check()); + + chronos.report(true); + + // Time measurement + + chronos.start(nb_calc); + + do { + + Interface::copy_matrix(A_ref,A,size); + Interface::copy_matrix(B_ref,B,size); + Interface::copy_matrix(X_ref,X,size); + + Interface::matrix_matrix_product(A,B,X,size); // here it is not commented !!!! + } + while(chronos.check()); + + chronos.report(true); + + double time=chronos.calculated_time/2000.0; + + // calculation check + + typename Interface::stl_matrix resu_stl(size); + + Interface::matrix_to_stl(X,resu_stl); + + STL_interface::matrix_matrix_product(A_stl,B_stl,X_stl,size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-6){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(1); + } + + // deallocation and return time + + Interface::free_matrix(A,size); + Interface::free_matrix(B,size); + Interface::free_matrix(X,size); + + Interface::free_matrix(A_ref,size); + Interface::free_matrix(B_ref,size); + Interface::free_matrix(X_ref,size); + + return time; + } + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_vector_product.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_vector_product.hh new file mode 100644 index 0000000000000000000000000000000000000000..8bab79d18b4e614a56fb8f389658ca7e318121e1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_matrix_vector_product.hh @@ -0,0 +1,153 @@ +//===================================================== +// File : action_matrix_vector_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_MATRIX_VECTOR_PRODUCT +#define ACTION_MATRIX_VECTOR_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_matrix_vector_product { + +public : + + // Ctor + + BTL_DONT_INLINE Action_matrix_vector_product( int size ):_size(size) + { + MESSAGE("Action_matrix_vector_product Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(X,X_stl); + + } + + // invalidate copy ctor + + Action_matrix_vector_product( const Action_matrix_vector_product & ) + { + INFOS("illegal call to Action_matrix_vector_product Copy Ctor"); + exit(1); + } + + // Dtor + + BTL_DONT_INLINE ~Action_matrix_vector_product( void ){ + + MESSAGE("Action_matrix_vector_product Dtor"); + + // deallocation + + Interface::free_matrix(A,_size); + Interface::free_vector(B); + Interface::free_vector(X); + + Interface::free_matrix(A_ref,_size); + Interface::free_vector(B_ref); + Interface::free_vector(X_ref); + + } + + // action name + + static inline std::string name( void ) + { + return "matrix_vector_" + Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size; + } + + BTL_DONT_INLINE void initialize( void ){ + + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + Interface::copy_vector(X_ref,X,_size); + + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("#begin matrix_vector_product"); + Interface::matrix_vector_product(A,B,X,_size); + BTL_ASM_COMMENT("end matrix_vector_product"); + } + + BTL_DONT_INLINE void check_result( void ){ + + // calculation check + + Interface::vector_to_stl(X,resu_stl); + + STL_interface::matrix_vector_product(A_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-5){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(0); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_vector B_ref; + typename Interface::gene_vector X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + + int _size; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_partial_lu.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_partial_lu.hh new file mode 100644 index 0000000000000000000000000000000000000000..770ea1d1e74331748fbd605269c320f6c195057f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_partial_lu.hh @@ -0,0 +1,125 @@ +//===================================================== +// File : action_lu_decomp.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_PARTIAL_LU +#define ACTION_PARTIAL_LU +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_partial_lu { + +public : + + // Ctor + + Action_partial_lu( int size ):_size(size) + { + MESSAGE("Action_partial_lu Ctor"); + + // STL vector initialization + init_matrix(X_stl,_size); + init_matrix(C_stl,_size); + + // make sure X is invertible + for (int i=0; i<_size; ++i) + X_stl[i][i] = X_stl[i][i] * 1e2 + 1; + + // generic matrix and vector initialization + Interface::matrix_from_stl(X_ref,X_stl); + Interface::matrix_from_stl(X,X_stl); + Interface::matrix_from_stl(C,C_stl); + + _cost = 2.0*size*size*size/3.0 + size*size; + } + + // invalidate copy ctor + + Action_partial_lu( const Action_partial_lu & ) + { + INFOS("illegal call to Action_partial_lu Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_partial_lu( void ){ + + MESSAGE("Action_partial_lu Dtor"); + + // deallocation + Interface::free_matrix(X_ref,_size); + Interface::free_matrix(X,_size); + Interface::free_matrix(C,_size); + } + + // action name + + static inline std::string name( void ) + { + return "partial_lu_decomp_"+Interface::name(); + } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + Interface::copy_matrix(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::partial_lu_decomp(X,C,_size); + } + + void check_result( void ){ + // calculation check +// Interface::matrix_to_stl(C,resu_stl); + +// STL_interface::lu_decomp(X_stl,C_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(C_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix C_stl; + + typename Interface::gene_matrix X_ref; + typename Interface::gene_matrix X; + typename Interface::gene_matrix C; + + int _size; + double _cost; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_rot.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_rot.hh new file mode 100644 index 0000000000000000000000000000000000000000..df822a6d610f8d0bcd20e8528b7670e256b433b6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_rot.hh @@ -0,0 +1,116 @@ + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_ROT +#define ACTION_ROT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_rot { + +public : + + // Ctor + BTL_DONT_INLINE Action_rot( int size ):_size(size) + { + MESSAGE("Action_rot Ctor"); + + // STL matrix and vector initialization + typename Interface::stl_matrix tmp; + init_vector(A_stl,_size); + init_vector(B_stl,_size); + + // generic matrix and vector initialization + Interface::vector_from_stl(A_ref,A_stl); + Interface::vector_from_stl(A,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(B,B_stl); + } + + // invalidate copy ctor + Action_rot( const Action_rot & ) + { + INFOS("illegal call to Action_rot Copy Ctor"); + exit(1); + } + + // Dtor + BTL_DONT_INLINE ~Action_rot( void ){ + MESSAGE("Action_rot Dtor"); + Interface::free_vector(A); + Interface::free_vector(B); + Interface::free_vector(A_ref); + Interface::free_vector(B_ref); + } + + // action name + static inline std::string name( void ) + { + return "rot_" + Interface::name(); + } + + double nb_op_base( void ){ + return 6.0*_size; + } + + BTL_DONT_INLINE void initialize( void ){ + Interface::copy_vector(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("#begin rot"); + Interface::rot(A,B,0.5,0.6,_size); + BTL_ASM_COMMENT("end rot"); + } + + BTL_DONT_INLINE void check_result( void ){ + // calculation check +// Interface::vector_to_stl(X,resu_stl); + +// STL_interface::rot(A_stl,B_stl,X_stl,_size); + +// typename Interface::real_type error= +// STL_interface::norm_diff(X_stl,resu_stl); + +// if (error>1.e-3){ +// INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); +// } + + } + +private : + + typename Interface::stl_vector A_stl; + typename Interface::stl_vector B_stl; + + typename Interface::gene_vector A_ref; + typename Interface::gene_vector B_ref; + + typename Interface::gene_vector A; + typename Interface::gene_vector B; + + int _size; +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_symv.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_symv.hh new file mode 100644 index 0000000000000000000000000000000000000000..a32b9dfa0648a75856717b1b4433b948c15c0f57 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_symv.hh @@ -0,0 +1,139 @@ +//===================================================== +// File : action_symv.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_SYMV +#define ACTION_SYMV +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_symv { + +public : + + // Ctor + + BTL_DONT_INLINE Action_symv( int size ):_size(size) + { + MESSAGE("Action_symv Ctor"); + + // STL matrix and vector initialization + init_matrix_symm(A_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(X,X_stl); + + } + + // invalidate copy ctor + + Action_symv( const Action_symv & ) + { + INFOS("illegal call to Action_symv Copy Ctor"); + exit(1); + } + + // Dtor + BTL_DONT_INLINE ~Action_symv( void ){ + Interface::free_matrix(A,_size); + Interface::free_vector(B); + Interface::free_vector(X); + Interface::free_matrix(A_ref,_size); + Interface::free_vector(B_ref); + Interface::free_vector(X_ref); + } + + // action name + + static inline std::string name( void ) + { + return "symv_" + Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size; + } + + BTL_DONT_INLINE void initialize( void ){ + + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + Interface::copy_vector(X_ref,X,_size); + + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("#begin symv"); + Interface::symv(A,B,X,_size); + BTL_ASM_COMMENT("end symv"); + } + + BTL_DONT_INLINE void check_result( void ){ + if (_size>128) return; + // calculation check + Interface::vector_to_stl(X,resu_stl); + + STL_interface::symv(A_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-5){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(0); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_vector B_ref; + typename Interface::gene_vector X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + + int _size; + +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_syr2.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_syr2.hh new file mode 100644 index 0000000000000000000000000000000000000000..7c6712b131f57089ad3d97c4c4eb09a43f2a45af --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_syr2.hh @@ -0,0 +1,133 @@ +//===================================================== +// File : action_syr2.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_SYR2 +#define ACTION_SYR2 +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_syr2 { + +public : + + // Ctor + + BTL_DONT_INLINE Action_syr2( int size ):_size(size) + { + // STL matrix and vector initialization + typename Interface::stl_matrix tmp; + init_matrix(A_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + init_vector(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(A_ref,A_stl); + Interface::matrix_from_stl(A,A_stl); + Interface::vector_from_stl(B_ref,B_stl); + Interface::vector_from_stl(B,B_stl); + Interface::vector_from_stl(X_ref,X_stl); + Interface::vector_from_stl(X,X_stl); + } + + // invalidate copy ctor + Action_syr2( const Action_syr2 & ) + { + INFOS("illegal call to Action_syr2 Copy Ctor"); + exit(1); + } + + // Dtor + BTL_DONT_INLINE ~Action_syr2( void ){ + Interface::free_matrix(A,_size); + Interface::free_vector(B); + Interface::free_vector(X); + Interface::free_matrix(A_ref,_size); + Interface::free_vector(B_ref); + Interface::free_vector(X_ref); + } + + // action name + + static inline std::string name( void ) + { + return "syr2_" + Interface::name(); + } + + double nb_op_base( void ){ + return 2.0*_size*_size; + } + + BTL_DONT_INLINE void initialize( void ){ + Interface::copy_matrix(A_ref,A,_size); + Interface::copy_vector(B_ref,B,_size); + Interface::copy_vector(X_ref,X,_size); + } + + BTL_DONT_INLINE void calculate( void ) { + BTL_ASM_COMMENT("#begin syr2"); + Interface::syr2(A,B,X,_size); + BTL_ASM_COMMENT("end syr2"); + } + + BTL_DONT_INLINE void check_result( void ){ + // calculation check + Interface::vector_to_stl(X,resu_stl); + + STL_interface::syr2(A_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-3){ + INFOS("WRONG CALCULATION...residual=" << error); +// exit(0); + } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_vector B_ref; + typename Interface::gene_vector X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_vector B; + typename Interface::gene_vector X; + + + int _size; + +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve.hh new file mode 100644 index 0000000000000000000000000000000000000000..d6f0b477eec0f11a671fdea6cfb37f753b395059 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve.hh @@ -0,0 +1,137 @@ +//===================================================== +// File : action_trisolve.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_TRISOLVE +#define ACTION_TRISOLVE +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_trisolve { + +public : + + // Ctor + + Action_trisolve( int size ):_size(size) + { + MESSAGE("Action_trisolve Ctor"); + + // STL vector initialization + init_matrix(L_stl,_size); + init_vector(B_stl,_size); + init_vector(X_stl,_size); + for (int j=0; j<_size; ++j) + { + for (int i=0; i(resu_stl,_size); + + // generic matrix and vector initialization + Interface::matrix_from_stl(L,L_stl); + Interface::vector_from_stl(X,X_stl); + Interface::vector_from_stl(B,B_stl); + + _cost = 0; + for (int j=0; j<_size; ++j) + { + _cost += 2*j + 1; + } + } + + // invalidate copy ctor + + Action_trisolve( const Action_trisolve & ) + { + INFOS("illegal call to Action_trisolve Copy Ctor"); + exit(1); + } + + // Dtor + + ~Action_trisolve( void ){ + + MESSAGE("Action_trisolve Dtor"); + + // deallocation + Interface::free_matrix(L,_size); + Interface::free_vector(B); + Interface::free_vector(X); + } + + // action name + + static inline std::string name( void ) + { + return "trisolve_vector_"+Interface::name(); + } + + double nb_op_base( void ){ + return _cost; + } + + inline void initialize( void ){ + //Interface::copy_vector(X_ref,X,_size); + } + + inline void calculate( void ) { + Interface::trisolve_lower(L,B,X,_size); + } + + void check_result(){ + if (_size>128) return; + // calculation check + Interface::vector_to_stl(X,resu_stl); + + STL_interface::trisolve_lower(L_stl,B_stl,X_stl,_size); + + typename Interface::real_type error= + STL_interface::norm_diff(X_stl,resu_stl); + + if (error>1.e-4){ + INFOS("WRONG CALCULATION...residual=" << error); + exit(2); + } //else INFOS("CALCULATION OK...residual=" << error); + + } + +private : + + typename Interface::stl_matrix L_stl; + typename Interface::stl_vector X_stl; + typename Interface::stl_vector B_stl; + typename Interface::stl_vector resu_stl; + + typename Interface::gene_matrix L; + typename Interface::gene_vector X; + typename Interface::gene_vector B; + + int _size; + double _cost; +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve_matrix.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve_matrix.hh new file mode 100644 index 0000000000000000000000000000000000000000..0fc2bb9effb6625af165d9b774cce809e3ed19d5 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trisolve_matrix.hh @@ -0,0 +1,165 @@ +//===================================================== +// File : action_matrix_matrix_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_TRISOLVE_MATRIX_PRODUCT +#define ACTION_TRISOLVE_MATRIX_PRODUCT +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_trisolve_matrix { + +public : + + // Ctor + + Action_trisolve_matrix( int size ):_size(size) + { + MESSAGE("Action_trisolve_matrix Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_matrix(B_stl,_size); + init_matrix(X_stl,_size); + init_matrix(resu_stl,_size); + + for (int j=0; j<_size; ++j) + { + for (int i=0; i::matrix_matrix_product(A_stl,B_stl,X_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(X_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// // exit(1); +// } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix B_stl; + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix B_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix B; + typename Interface::gene_matrix X; + + int _size; + double _cost; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trmm.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trmm.hh new file mode 100644 index 0000000000000000000000000000000000000000..8f7813818424216f71027235a7255efe20e7d2b4 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/action_trmm.hh @@ -0,0 +1,165 @@ +//===================================================== +// File : action_matrix_matrix_product.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef ACTION_TRMM +#define ACTION_TRMM +#include "utilities.h" +#include "STL_interface.hh" +#include +#include "init/init_function.hh" +#include "init/init_vector.hh" +#include "init/init_matrix.hh" + +using namespace std; + +template +class Action_trmm { + +public : + + // Ctor + + Action_trmm( int size ):_size(size) + { + MESSAGE("Action_trmm Ctor"); + + // STL matrix and vector initialization + + init_matrix(A_stl,_size); + init_matrix(B_stl,_size); + init_matrix(X_stl,_size); + init_matrix(resu_stl,_size); + + for (int j=0; j<_size; ++j) + { + for (int i=0; i::matrix_matrix_product(A_stl,B_stl,X_stl,_size); +// +// typename Interface::real_type error= +// STL_interface::norm_diff(X_stl,resu_stl); +// +// if (error>1.e-6){ +// INFOS("WRONG CALCULATION...residual=" << error); +// // exit(1); +// } + + } + +private : + + typename Interface::stl_matrix A_stl; + typename Interface::stl_matrix B_stl; + typename Interface::stl_matrix X_stl; + typename Interface::stl_matrix resu_stl; + + typename Interface::gene_matrix A_ref; + typename Interface::gene_matrix B_ref; + typename Interface::gene_matrix X_ref; + + typename Interface::gene_matrix A; + typename Interface::gene_matrix B; + typename Interface::gene_matrix X; + + int _size; + double _cost; + +}; + + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/basic_actions.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/basic_actions.hh new file mode 100644 index 0000000000000000000000000000000000000000..a3333ea26f6b8e29344e53ff37a2ef6c05ed3f90 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/actions/basic_actions.hh @@ -0,0 +1,21 @@ + +#include "action_axpy.hh" +#include "action_axpby.hh" + +#include "action_matrix_vector_product.hh" +#include "action_atv_product.hh" + +#include "action_matrix_matrix_product.hh" +// #include "action_ata_product.hh" +#include "action_aat_product.hh" + +#include "action_trisolve.hh" +#include "action_trmm.hh" +#include "action_symv.hh" +// #include "action_symm.hh" +#include "action_syr2.hh" +#include "action_ger.hh" +#include "action_rot.hh" + +// #include "action_lu_solve.hh" + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindACML.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindACML.cmake new file mode 100644 index 0000000000000000000000000000000000000000..4989fa2f4c60a2c4afe2242b32c02f1c4e9dd705 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindACML.cmake @@ -0,0 +1,51 @@ + +if (ACML_LIBRARIES) + set(ACML_FIND_QUIETLY TRUE) +endif (ACML_LIBRARIES) + +find_library(ACML_LIBRARIES + NAMES + acml_mp acml_mv + PATHS + $ENV{ACMLDIR}/lib + $ENV{ACML_DIR}/lib + ${LIB_INSTALL_DIR} +) + +find_file(ACML_LIBRARIES + NAMES + libacml_mp.so + PATHS + /usr/lib + /usr/lib64 + $ENV{ACMLDIR}/lib + ${LIB_INSTALL_DIR} +) + +if(NOT ACML_LIBRARIES) + message(STATUS "Multi-threaded library not found, looking for single-threaded") + find_library(ACML_LIBRARIES + NAMES + acml acml_mv + PATHS + $ENV{ACMLDIR}/lib + $ENV{ACML_DIR}/lib + ${LIB_INSTALL_DIR} + ) + find_file(ACML_LIBRARIES + libacml.so libacml_mv.so + PATHS + /usr/lib + /usr/lib64 + $ENV{ACMLDIR}/lib + ${LIB_INSTALL_DIR} + ) +endif() + + + + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(ACML DEFAULT_MSG ACML_LIBRARIES) + +mark_as_advanced(ACML_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindATLAS.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindATLAS.cmake new file mode 100644 index 0000000000000000000000000000000000000000..4136a989d61565965f03cd1704f9284a83e8c8b0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindATLAS.cmake @@ -0,0 +1,31 @@ + +if (ATLAS_LIBRARIES) + set(ATLAS_FIND_QUIETLY TRUE) +endif (ATLAS_LIBRARIES) + +find_file(ATLAS_LIB libatlas.so.3 PATHS /usr/lib /usr/lib/atlas /usr/lib64 /usr/lib64/atlas $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) +find_library(ATLAS_LIB satlas PATHS $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) + +find_file(ATLAS_LAPACK NAMES liblapack_atlas.so.3 liblapack.so.3 PATHS /usr/lib /usr/lib/atlas /usr/lib64 /usr/lib64/atlas $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) +find_library(ATLAS_LAPACK NAMES lapack_atlas lapack PATHS $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) + +find_file(ATLAS_F77BLAS libf77blas.so.3 PATHS /usr/lib /usr/lib/atlas /usr/lib64 /usr/lib64/atlas $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) +find_library(ATLAS_F77BLAS f77blas PATHS $ENV{ATLASDIR} ${LIB_INSTALL_DIR}) + +if(ATLAS_LIB AND ATLAS_CBLAS AND ATLAS_LAPACK AND ATLAS_F77BLAS) + + set(ATLAS_LIBRARIES ${ATLAS_LAPACK} ${ATLAS_LIB}) + + # search the default lapack lib link to it + find_file(ATLAS_REFERENCE_LAPACK liblapack.so.3 PATHS /usr/lib /usr/lib64) + find_library(ATLAS_REFERENCE_LAPACK NAMES lapack) +# if(ATLAS_REFERENCE_LAPACK) +# set(ATLAS_LIBRARIES ${ATLAS_LIBRARIES} ${ATLAS_REFERENCE_LAPACK}) +# endif() + +endif(ATLAS_LIB AND ATLAS_CBLAS AND ATLAS_LAPACK AND ATLAS_F77BLAS) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(ATLAS DEFAULT_MSG ATLAS_LIBRARIES) + +mark_as_advanced(ATLAS_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBLAZE.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBLAZE.cmake new file mode 100644 index 0000000000000000000000000000000000000000..dba4c89f2de55e394a148388cf594babc8cbf11f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBLAZE.cmake @@ -0,0 +1,31 @@ +# - Try to find eigen2 headers +# Once done this will define +# +# BLAZE_FOUND - system has blaze lib +# BLAZE_INCLUDE_DIR - the blaze include directory +# +# Copyright (C) 2008 Gael Guennebaud +# Adapted from FindEigen.cmake: +# Copyright (c) 2006, 2007 Montel Laurent, +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +if (BLAZE_INCLUDE_DIR) + + # in cache already + set(BLAZE_FOUND TRUE) + +else (BLAZE_INCLUDE_DIR) + +find_path(BLAZE_INCLUDE_DIR NAMES blaze/Blaze.h + PATHS + ${INCLUDE_INSTALL_DIR} + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(BLAZE DEFAULT_MSG BLAZE_INCLUDE_DIR) + +mark_as_advanced(BLAZE_INCLUDE_DIR) + +endif(BLAZE_INCLUDE_DIR) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBlitz.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBlitz.cmake new file mode 100644 index 0000000000000000000000000000000000000000..92880bbed7cc687dee65ba2419e236e383c26479 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindBlitz.cmake @@ -0,0 +1,40 @@ +# - Try to find blitz lib +# Once done this will define +# +# BLITZ_FOUND - system has blitz lib +# BLITZ_INCLUDES - the blitz include directory +# BLITZ_LIBRARIES - The libraries needed to use blitz + +# Copyright (c) 2006, Montel Laurent, +# Copyright (c) 2007, Allen Winter, +# Copyright (C) 2008 Gael Guennebaud +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +# include(FindLibraryWithDebug) + +if (BLITZ_INCLUDES AND BLITZ_LIBRARIES) + set(Blitz_FIND_QUIETLY TRUE) +endif (BLITZ_INCLUDES AND BLITZ_LIBRARIES) + +find_path(BLITZ_INCLUDES + NAMES + blitz/array.h + PATH_SUFFIXES blitz* + PATHS + $ENV{BLITZDIR}/include + ${INCLUDE_INSTALL_DIR} +) + +find_library(BLITZ_LIBRARIES + blitz + PATHS + $ENV{BLITZDIR}/lib + ${LIB_INSTALL_DIR} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Blitz DEFAULT_MSG + BLITZ_INCLUDES BLITZ_LIBRARIES) + +mark_as_advanced(BLITZ_INCLUDES BLITZ_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindCBLAS.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindCBLAS.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ce0f2f2b2d2d09973e45e8169a39d9f3cb738a50 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindCBLAS.cmake @@ -0,0 +1,35 @@ +# include(FindLibraryWithDebug) + +if (CBLAS_INCLUDES AND CBLAS_LIBRARIES) + set(CBLAS_FIND_QUIETLY TRUE) +endif (CBLAS_INCLUDES AND CBLAS_LIBRARIES) + +find_path(CBLAS_INCLUDES + NAMES + cblas.h + PATHS + $ENV{CBLASDIR}/include + ${INCLUDE_INSTALL_DIR} +) + +find_library(CBLAS_LIBRARIES + cblas + PATHS + $ENV{CBLASDIR}/lib + ${LIB_INSTALL_DIR} +) + +find_file(CBLAS_LIBRARIES + libcblas.so.3 + PATHS + /usr/lib + /usr/lib64 + $ENV{CBLASDIR}/lib + ${LIB_INSTALL_DIR} +) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(CBLAS DEFAULT_MSG + CBLAS_INCLUDES CBLAS_LIBRARIES) + +mark_as_advanced(CBLAS_INCLUDES CBLAS_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindGMM.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindGMM.cmake new file mode 100644 index 0000000000000000000000000000000000000000..5049c64edcea43027c7875c9efa328a849cdb53f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindGMM.cmake @@ -0,0 +1,17 @@ +if (GMM_INCLUDE_DIR) + # in cache already + set(GMM_FOUND TRUE) +else (GMM_INCLUDE_DIR) + +find_path(GMM_INCLUDE_DIR NAMES gmm/gmm.h + PATHS + ${INCLUDE_INSTALL_DIR} + ${GMM_INCLUDE_PATH} + ) + +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(GMM DEFAULT_MSG GMM_INCLUDE_DIR ) + +mark_as_advanced(GMM_INCLUDE_DIR) + +endif(GMM_INCLUDE_DIR) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMKL.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMKL.cmake new file mode 100644 index 0000000000000000000000000000000000000000..f4d7c6ebe7dd629d20b7579ee6efa4dad989edcf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMKL.cmake @@ -0,0 +1,65 @@ + +if (MKL_LIBRARIES) + set(MKL_FIND_QUIETLY TRUE) +endif (MKL_LIBRARIES) + +if(CMAKE_MINOR_VERSION GREATER 4) + +if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64") + +find_library(MKL_LIBRARIES + mkl_core + PATHS + $ENV{MKLLIB} + /opt/intel/mkl/*/lib/em64t + /opt/intel/Compiler/*/*/mkl/lib/em64t + ${LIB_INSTALL_DIR} +) + +find_library(MKL_GUIDE + guide + PATHS + $ENV{MKLLIB} + /opt/intel/mkl/*/lib/em64t + /opt/intel/Compiler/*/*/mkl/lib/em64t + /opt/intel/Compiler/*/*/lib/intel64 + ${LIB_INSTALL_DIR} +) + +if(MKL_LIBRARIES AND MKL_GUIDE) + set(MKL_LIBRARIES ${MKL_LIBRARIES} mkl_intel_lp64 mkl_sequential ${MKL_GUIDE} pthread) +endif() + +else(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64") + +find_library(MKL_LIBRARIES + mkl_core + PATHS + $ENV{MKLLIB} + /opt/intel/mkl/*/lib/32 + /opt/intel/Compiler/*/*/mkl/lib/32 + ${LIB_INSTALL_DIR} +) + +find_library(MKL_GUIDE + guide + PATHS + $ENV{MKLLIB} + /opt/intel/mkl/*/lib/32 + /opt/intel/Compiler/*/*/mkl/lib/32 + /opt/intel/Compiler/*/*/lib/intel32 + ${LIB_INSTALL_DIR} +) + +if(MKL_LIBRARIES AND MKL_GUIDE) + set(MKL_LIBRARIES ${MKL_LIBRARIES} mkl_intel mkl_sequential ${MKL_GUIDE} pthread) +endif() + +endif(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64") + +endif(CMAKE_MINOR_VERSION GREATER 4) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(MKL DEFAULT_MSG MKL_LIBRARIES) + +mark_as_advanced(MKL_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMTL4.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMTL4.cmake new file mode 100644 index 0000000000000000000000000000000000000000..3de4909802be09039c847931d323a81b8998fa50 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindMTL4.cmake @@ -0,0 +1,31 @@ +# - Try to find eigen2 headers +# Once done this will define +# +# MTL4_FOUND - system has eigen2 lib +# MTL4_INCLUDE_DIR - the eigen2 include directory +# +# Copyright (C) 2008 Gael Guennebaud +# Adapted from FindEigen.cmake: +# Copyright (c) 2006, 2007 Montel Laurent, +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +if (MTL4_INCLUDE_DIR) + + # in cache already + set(MTL4_FOUND TRUE) + +else (MTL4_INCLUDE_DIR) + +find_path(MTL4_INCLUDE_DIR NAMES boost/numeric/mtl/mtl.hpp + PATHS + ${INCLUDE_INSTALL_DIR} + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(MTL4 DEFAULT_MSG MTL4_INCLUDE_DIR) + +mark_as_advanced(MTL4_INCLUDE_DIR) + +endif(MTL4_INCLUDE_DIR) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindOPENBLAS.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindOPENBLAS.cmake new file mode 100644 index 0000000000000000000000000000000000000000..2a091943645d64c86dcae8b01211dbec129167da --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindOPENBLAS.cmake @@ -0,0 +1,17 @@ + +if (OPENBLAS_LIBRARIES) + set(OPENBLAS_FIND_QUIETLY TRUE) +endif (OPENBLAS_LIBRARIES) + +find_file(OPENBLAS_LIBRARIES NAMES libopenblas.so libopenblas.so.0 PATHS /usr/lib /usr/lib64 $ENV{OPENBLASDIR} ${LIB_INSTALL_DIR}) +find_library(OPENBLAS_LIBRARIES openblas PATHS $ENV{OPENBLASDIR} ${LIB_INSTALL_DIR}) + +if(OPENBLAS_LIBRARIES AND CMAKE_COMPILER_IS_GNUCXX) + set(OPENBLAS_LIBRARIES ${OPENBLAS_LIBRARIES} "-lpthread -lgfortran") +endif() + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(OPENBLAS DEFAULT_MSG + OPENBLAS_LIBRARIES) + +mark_as_advanced(OPENBLAS_LIBRARIES) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindPackageHandleStandardArgs.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindPackageHandleStandardArgs.cmake new file mode 100644 index 0000000000000000000000000000000000000000..7f122edcddd304b99fc1fd67ab1ca023a46edcb2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindPackageHandleStandardArgs.cmake @@ -0,0 +1,60 @@ +# FIND_PACKAGE_HANDLE_STANDARD_ARGS(NAME (DEFAULT_MSG|"Custom failure message") VAR1 ... ) +# +# This macro is intended to be used in FindXXX.cmake modules files. +# It handles the REQUIRED and QUIET argument to FIND_PACKAGE() and +# it also sets the _FOUND variable. +# The package is found if all variables listed are TRUE. +# Example: +# +# FIND_PACKAGE_HANDLE_STANDARD_ARGS(LibXml2 DEFAULT_MSG LIBXML2_LIBRARIES LIBXML2_INCLUDE_DIR) +# +# LibXml2 is considered to be found, if both LIBXML2_LIBRARIES and +# LIBXML2_INCLUDE_DIR are valid. Then also LIBXML2_FOUND is set to TRUE. +# If it is not found and REQUIRED was used, it fails with FATAL_ERROR, +# independent whether QUIET was used or not. +# +# If it is found, the location is reported using the VAR1 argument, so +# here a message "Found LibXml2: /usr/lib/libxml2.so" will be printed out. +# If the second argument is DEFAULT_MSG, the message in the failure case will +# be "Could NOT find LibXml2", if you don't like this message you can specify +# your own custom failure message there. + +MACRO(FIND_PACKAGE_HANDLE_STANDARD_ARGS _NAME _FAIL_MSG _VAR1 ) + + IF("${_FAIL_MSG}" STREQUAL "DEFAULT_MSG") + IF (${_NAME}_FIND_REQUIRED) + SET(_FAIL_MESSAGE "Could not find REQUIRED package ${_NAME}") + ELSE (${_NAME}_FIND_REQUIRED) + SET(_FAIL_MESSAGE "Could not find OPTIONAL package ${_NAME}") + ENDIF (${_NAME}_FIND_REQUIRED) + ELSE("${_FAIL_MSG}" STREQUAL "DEFAULT_MSG") + SET(_FAIL_MESSAGE "${_FAIL_MSG}") + ENDIF("${_FAIL_MSG}" STREQUAL "DEFAULT_MSG") + + STRING(TOUPPER ${_NAME} _NAME_UPPER) + + SET(${_NAME_UPPER}_FOUND TRUE) + IF(NOT ${_VAR1}) + SET(${_NAME_UPPER}_FOUND FALSE) + ENDIF(NOT ${_VAR1}) + + FOREACH(_CURRENT_VAR ${ARGN}) + IF(NOT ${_CURRENT_VAR}) + SET(${_NAME_UPPER}_FOUND FALSE) + ENDIF(NOT ${_CURRENT_VAR}) + ENDFOREACH(_CURRENT_VAR) + + IF (${_NAME_UPPER}_FOUND) + IF (NOT ${_NAME}_FIND_QUIETLY) + MESSAGE(STATUS "Found ${_NAME}: ${${_VAR1}}") + ENDIF (NOT ${_NAME}_FIND_QUIETLY) + ELSE (${_NAME_UPPER}_FOUND) + IF (${_NAME}_FIND_REQUIRED) + MESSAGE(FATAL_ERROR "${_FAIL_MESSAGE}") + ELSE (${_NAME}_FIND_REQUIRED) + IF (NOT ${_NAME}_FIND_QUIETLY) + MESSAGE(STATUS "${_FAIL_MESSAGE}") + ENDIF (NOT ${_NAME}_FIND_QUIETLY) + ENDIF (${_NAME}_FIND_REQUIRED) + ENDIF (${_NAME_UPPER}_FOUND) +ENDMACRO(FIND_PACKAGE_HANDLE_STANDARD_ARGS) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindTvmet.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindTvmet.cmake new file mode 100644 index 0000000000000000000000000000000000000000..26a29d965d125b34b1fff2c6bbfc2b5bf52e42df --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/FindTvmet.cmake @@ -0,0 +1,32 @@ +# - Try to find tvmet headers +# Once done this will define +# +# TVMET_FOUND - system has tvmet lib +# TVMET_INCLUDE_DIR - the tvmet include directory +# +# Copyright (C) 2008 Gael Guennebaud +# Adapted from FindEigen.cmake: +# Copyright (c) 2006, 2007 Montel Laurent, +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +if (TVMET_INCLUDE_DIR) + + # in cache already + set(TVMET_FOUND TRUE) + +else (TVMET_INCLUDE_DIR) + +find_path(TVMET_INCLUDE_DIR NAMES tvmet/tvmet.h + PATHS + ${TVMETDIR}/ + ${INCLUDE_INSTALL_DIR} + ) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(Tvmet DEFAULT_MSG TVMET_INCLUDE_DIR) + +mark_as_advanced(TVMET_INCLUDE_DIR) + +endif(TVMET_INCLUDE_DIR) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/MacroOptionalAddSubdirectory.cmake b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/MacroOptionalAddSubdirectory.cmake new file mode 100644 index 0000000000000000000000000000000000000000..545048b684371ec6b8bdab3aaee2415b15b321a0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/cmake/MacroOptionalAddSubdirectory.cmake @@ -0,0 +1,31 @@ +# - MACRO_OPTIONAL_ADD_SUBDIRECTORY() combines ADD_SUBDIRECTORY() with an OPTION() +# MACRO_OPTIONAL_ADD_SUBDIRECTORY( ) +# If you use MACRO_OPTIONAL_ADD_SUBDIRECTORY() instead of ADD_SUBDIRECTORY(), +# this will have two effects +# 1 - CMake will not complain if the directory doesn't exist +# This makes sense if you want to distribute just one of the subdirs +# in a source package, e.g. just one of the subdirs in kdeextragear. +# 2 - If the directory exists, it will offer an option to skip the +# subdirectory. +# This is useful if you want to compile only a subset of all +# directories. + +# Copyright (c) 2007, Alexander Neundorf, +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + + +MACRO (MACRO_OPTIONAL_ADD_SUBDIRECTORY _dir ) + GET_FILENAME_COMPONENT(_fullPath ${_dir} ABSOLUTE) + IF(EXISTS ${_fullPath}) + IF(${ARGC} EQUAL 2) + OPTION(BUILD_${_dir} "Build directory ${_dir}" ${ARGV1}) + ELSE(${ARGC} EQUAL 2) + OPTION(BUILD_${_dir} "Build directory ${_dir}" TRUE) + ENDIF(${ARGC} EQUAL 2) + IF(BUILD_${_dir}) + ADD_SUBDIRECTORY(${_dir}) + ENDIF(BUILD_${_dir}) + ENDIF(EXISTS ${_fullPath}) +ENDMACRO (MACRO_OPTIONAL_ADD_SUBDIRECTORY) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..6af2a366f77ac4923d84584f1e7e4d7a834123bc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/CMakeLists.txt @@ -0,0 +1,32 @@ + +ADD_CUSTOM_TARGET(copy_scripts) + +SET(script_files go_mean mk_mean_script.sh mk_new_gnuplot.sh + perlib_plot_settings.txt action_settings.txt gnuplot_common_settings.hh ) + +FOREACH(script_file ${script_files}) +ADD_CUSTOM_COMMAND( + TARGET copy_scripts + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/${script_file} ${CMAKE_CURRENT_BINARY_DIR}/ + ARGS +) +ENDFOREACH(script_file) + +ADD_CUSTOM_COMMAND( + TARGET copy_scripts + POST_BUILD + COMMAND ${CMAKE_CXX_COMPILER} --version | head -n 1 > ${CMAKE_CURRENT_BINARY_DIR}/compiler_version.txt + ARGS +) +ADD_CUSTOM_COMMAND( + TARGET copy_scripts + POST_BUILD + COMMAND echo "${Eigen_SOURCE_DIR}" > ${CMAKE_CURRENT_BINARY_DIR}/eigen_root_dir.txt + ARGS +) + +add_executable(smooth smooth.cxx) +add_executable(regularize regularize.cxx) +add_executable(main mean.cxx) +add_dependencies(main copy_scripts) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/action_settings.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/action_settings.txt new file mode 100644 index 0000000000000000000000000000000000000000..39d2b5dc48d9965c1f504d468f85be69ccaa492c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/action_settings.txt @@ -0,0 +1,19 @@ +aat ; "{/*1.5 A x A^T}" ; "matrix size" ; 4:5000 +ata ; "{/*1.5 A^T x A}" ; "matrix size" ; 4:5000 +atv ; "{/*1.5 matrix^T x vector}" ; "matrix size" ; 4:5000 +axpby ; "{/*1.5 Y = alpha X + beta Y}" ; "vector size" ; 5:1000000 +axpy ; "{/*1.5 Y += alpha X}" ; "vector size" ; 5:1000000 +matrix_matrix ; "{/*1.5 matrix matrix product}" ; "matrix size" ; 4:5000 +matrix_vector ; "{/*1.5 matrix vector product}" ; "matrix size" ; 4:5000 +trmm ; "{/*1.5 triangular matrix matrix product}" ; "matrix size" ; 4:5000 +trisolve_vector ; "{/*1.5 triangular solver - vector (X = inv(L) X)}" ; "size" ; 4:5000 +trisolve_matrix ; "{/*1.5 triangular solver - matrix (M = inv(L) M)}" ; "size" ; 4:5000 +cholesky ; "{/*1.5 Cholesky decomposition}" ; "matrix size" ; 4:5000 +complete_lu_decomp ; "{/*1.5 Complete LU decomposition}" ; "matrix size" ; 4:5000 +partial_lu_decomp ; "{/*1.5 Partial LU decomposition}" ; "matrix size" ; 4:5000 +tridiagonalization ; "{/*1.5 Tridiagonalization}" ; "matrix size" ; 4:5000 +hessenberg ; "{/*1.5 Hessenberg decomposition}" ; "matrix size" ; 4:5000 +symv ; "{/*1.5 symmetric matrix vector product}" ; "matrix size" ; 4:5000 +syr2 ; "{/*1.5 symmretric rank-2 update (A += u^T v + u v^T)}" ; "matrix size" ; 4:5000 +ger ; "{/*1.5 general rank-1 update (A += u v^T)}" ; "matrix size" ; 4:5000 +rot ; "{/*1.5 apply rotation in the plane}" ; "vector size" ; 4:1000000 diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/gnuplot_common_settings.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/gnuplot_common_settings.hh new file mode 100644 index 0000000000000000000000000000000000000000..6f677df60a33a62150055e7ae84282a69a12e254 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/gnuplot_common_settings.hh @@ -0,0 +1,87 @@ +set noclip points +set clip one +set noclip two +set bar 1.000000 +set border 31 lt -1 lw 1.000 +set xdata +set ydata +set zdata +set x2data +set y2data +set boxwidth +set dummy x,y +set format x "%g" +set format y "%g" +set format x2 "%g" +set format y2 "%g" +set format z "%g" +set angles radians +set nogrid +set key title "" +set key left top Right noreverse box linetype -2 linewidth 1.000 samplen 4 spacing 1 width 0 +set nolabel +set noarrow +# set nolinestyle # deprecated +set nologscale +set logscale x 10 +set offsets 0, 0, 0, 0 +set pointsize 1 +set encoding default +set nopolar +set noparametric +set view 60, 30, 1, 1 +set samples 100, 100 +set isosamples 10, 10 +set surface +set nocontour +set clabel '%8.3g' +set mapping cartesian +set nohidden3d +set cntrparam order 4 +set cntrparam linear +set cntrparam levels auto 5 +set cntrparam points 5 +set size ratio 0 1,1 +set origin 0,0 +# set data style lines +# set function style lines +set xzeroaxis lt -2 lw 1.000 +set x2zeroaxis lt -2 lw 1.000 +set yzeroaxis lt -2 lw 1.000 +set y2zeroaxis lt -2 lw 1.000 +set tics in +set ticslevel 0.5 +set tics scale 1, 0.5 +set mxtics default +set mytics default +set mx2tics default +set my2tics default +set xtics border mirror norotate autofreq +set ytics border mirror norotate autofreq +set ztics border nomirror norotate autofreq +set nox2tics +set noy2tics +set timestamp "" bottom norotate offset 0,0 +set rrange [ * : * ] noreverse nowriteback # (currently [-0:10] ) +set trange [ * : * ] noreverse nowriteback # (currently [-5:5] ) +set urange [ * : * ] noreverse nowriteback # (currently [-5:5] ) +set vrange [ * : * ] noreverse nowriteback # (currently [-5:5] ) +set xlabel "matrix size" offset 0,0 +set x2label "" offset 0,0 +set timefmt "%d/%m/%y\n%H:%M" +set xrange [ 10 : 1000 ] noreverse nowriteback +set x2range [ * : * ] noreverse nowriteback # (currently [-10:10] ) +set ylabel "MFLOPS" offset 0,0 +set y2label "" offset 0,0 +set yrange [ * : * ] noreverse nowriteback # (currently [-10:10] ) +set y2range [ * : * ] noreverse nowriteback # (currently [-10:10] ) +set zlabel "" offset 0,0 +set zrange [ * : * ] noreverse nowriteback # (currently [-10:10] ) +set zero 1e-08 +set lmargin -1 +set bmargin -1 +set rmargin -1 +set tmargin -1 +set locale "C" +set xrange [4:1024] + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/go_mean b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/go_mean new file mode 100644 index 0000000000000000000000000000000000000000..42338ca27811906c948b0ea2ba0f28f7957b00c2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/go_mean @@ -0,0 +1,58 @@ +#!/bin/bash + +if [ $# < 1 ]; then + echo "Usage: $0 working_directory [tiny|large [prefix]]" +else + +mkdir -p $1 +##cp ../libs/*/*.dat $1 + +mode=large +if [ $# > 2 ]; then + mode=$2 +fi +if [ $# > 3 ]; then + prefix=$3 +fi + +EIGENDIR=`cat eigen_root_dir.txt` + +webpagefilename=$1/index.html +meanstatsfilename=$1/mean.html + +echo '' > $meanstatsfilename +echo '' > $webpagefilename +echo '

Configuration' >> $webpagefilename +echo '

    '\ + '
  • ' `cat /proc/cpuinfo | grep "model name" | head -n 1`\ + ' (' `uname -m` ')
  • '\ + '
  • compiler: ' `cat compiler_version.txt` '
  • '\ + '
  • eigen3: ' `hg identify -i $EIGENDIR` '
  • '\ + '
' \ + '

' >> $webpagefilename + +source mk_mean_script.sh axpy $1 11 2500 100000 250000 $mode $prefix +source mk_mean_script.sh axpby $1 11 2500 100000 250000 $mode $prefix +source mk_mean_script.sh matrix_vector $1 11 50 300 1000 $mode $prefix +source mk_mean_script.sh atv $1 11 50 300 1000 $mode $prefix +source mk_mean_script.sh matrix_matrix $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh aat $1 11 100 300 1000 $mode $prefix +# source mk_mean_script.sh ata $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh trmm $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh trisolve_vector $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh trisolve_matrix $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh cholesky $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh partial_lu_decomp $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh tridiagonalization $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh hessenberg $1 11 100 300 1000 $mode $prefix +source mk_mean_script.sh symv $1 11 50 300 1000 $mode $prefix +source mk_mean_script.sh syr2 $1 11 50 300 1000 $mode $prefix +source mk_mean_script.sh ger $1 11 50 300 1000 $mode $prefix +source mk_mean_script.sh rot $1 11 2500 100000 250000 $mode $prefix +source mk_mean_script.sh complete_lu_decomp $1 11 100 300 1000 $mode $prefix + +fi + +## compile the web page ## + +#echo `cat footer.html` >> $webpagefilename \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mean.cxx b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mean.cxx new file mode 100644 index 0000000000000000000000000000000000000000..c567ef33e7c81406b15001d4b5462cd85cc0f0e7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mean.cxx @@ -0,0 +1,182 @@ +//===================================================== +// File : mean.cxx +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:15 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include +#include +#include +#include +#include "bench_parameter.hh" +#include "utils/xy_file.hh" +#include + +using namespace std; + +double mean_calc(const vector & tab_sizes, const vector & tab_mflops, const int size_min, const int size_max); + +class Lib_Mean{ + +public: + Lib_Mean( void ):_lib_name(),_mean_in_cache(),_mean_out_of_cache(){ + MESSAGE("Lib_mean Default Ctor"); + MESSAGE("!!! should not be used"); + exit(0); + } + Lib_Mean(const string & name, const double & mic, const double & moc):_lib_name(name),_mean_in_cache(mic),_mean_out_of_cache(moc){ + MESSAGE("Lib_mean Ctor"); + } + Lib_Mean(const Lib_Mean & lm):_lib_name(lm._lib_name),_mean_in_cache(lm._mean_in_cache),_mean_out_of_cache(lm._mean_out_of_cache){ + MESSAGE("Lib_mean Copy Ctor"); + } + ~Lib_Mean( void ){ + MESSAGE("Lib_mean Dtor"); + } + + double _mean_in_cache; + double _mean_out_of_cache; + string _lib_name; + + bool operator < ( const Lib_Mean &right) const + { + //return ( this->_mean_out_of_cache > right._mean_out_of_cache) ; + return ( this->_mean_in_cache > right._mean_in_cache) ; + } + +}; + + +int main( int argc , char *argv[] ) +{ + + if (argc<6){ + INFOS("!!! Error ... usage : main what mic Mic moc Moc filename1 finename2..."); + exit(0); + } + INFOS(argc); + + int min_in_cache=atoi(argv[2]); + int max_in_cache=atoi(argv[3]); + int min_out_of_cache=atoi(argv[4]); + int max_out_of_cache=atoi(argv[5]); + + + multiset s_lib_mean ; + + for (int i=6;i tab_sizes; + vector tab_mflops; + + read_xy_file(filename,tab_sizes,tab_mflops); + + mic=mean_calc(tab_sizes,tab_mflops,min_in_cache,max_in_cache); + moc=mean_calc(tab_sizes,tab_mflops,min_out_of_cache,max_out_of_cache); + + Lib_Mean cur_lib_mean(filename,mic,moc); + + s_lib_mean.insert(cur_lib_mean); + + } + + } + + + cout << "" << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + + multiset::iterator is = s_lib_mean.begin(); + Lib_Mean best(*is); + + + for (is=s_lib_mean.begin(); is!=s_lib_mean.end() ; is++){ + + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + cout << " " << endl ; + + } + + cout << "
" << argv[1] << " in cache
mean perf
Mflops
in cache
% best
out of cache
mean perf
Mflops
out of cache
% best
details comments
" << is->_lib_name << " " << is->_mean_in_cache << " " << 100*(is->_mean_in_cache/best._mean_in_cache) << " " << is->_mean_out_of_cache << " " << 100*(is->_mean_out_of_cache/best._mean_out_of_cache) << " " << + "_lib_name<<"_"<snippet/" + "_lib_name<<"_flags\">flags " << + "_lib_name<<"_comments\">click here
" << endl ; + + ofstream output_file ("../order_lib",ios::out) ; + + for (is=s_lib_mean.begin(); is!=s_lib_mean.end() ; is++){ + output_file << is->_lib_name << endl ; + } + + output_file.close(); + +} + +double mean_calc(const vector & tab_sizes, const vector & tab_mflops, const int size_min, const int size_max){ + + int size=tab_sizes.size(); + int nb_sample=0; + double mean=0.0; + + for (int i=0;i=size_min)&&(tab_sizes[i]<=size_max)){ + + nb_sample++; + mean+=tab_mflops[i]; + + } + + + } + + if (nb_sample==0){ + INFOS("no data for mean calculation"); + return 0.0; + } + + return mean/nb_sample; +} + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_gnuplot_script.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_gnuplot_script.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ca7b5cb5e1684aa79dc1a483ac96922e8c6293d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_gnuplot_script.sh @@ -0,0 +1,68 @@ +#! /bin/bash +WHAT=$1 +DIR=$2 +echo $WHAT script generation +cat $WHAT.hh > $WHAT.gnuplot + +DATA_FILE=`find $DIR -name "*.dat" | grep $WHAT` + +echo plot \\ >> $WHAT.gnuplot + +for FILE in $DATA_FILE +do + LAST=$FILE +done + +echo LAST=$LAST + +for FILE in $DATA_FILE +do + if [ $FILE != $LAST ] + then + BASE=${FILE##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} + echo "'"$FILE"'" title "'"$TITLE"'" ",\\" >> $WHAT.gnuplot + fi +done +BASE=${LAST##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} +echo "'"$LAST"'" title "'"$TITLE"'" >> $WHAT.gnuplot + +#echo set term postscript color >> $WHAT.gnuplot +#echo set output "'"$WHAT.ps"'" >> $WHAT.gnuplot +echo set term pbm small color >> $WHAT.gnuplot +echo set output "'"$WHAT.ppm"'" >> $WHAT.gnuplot +echo plot \\ >> $WHAT.gnuplot + +for FILE in $DATA_FILE +do + if [ $FILE != $LAST ] + then + BASE=${FILE##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} + echo "'"$FILE"'" title "'"$TITLE"'" ",\\" >> $WHAT.gnuplot + fi +done +BASE=${LAST##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} +echo "'"$LAST"'" title "'"$TITLE"'" >> $WHAT.gnuplot + +echo set term jpeg large >> $WHAT.gnuplot +echo set output "'"$WHAT.jpg"'" >> $WHAT.gnuplot +echo plot \\ >> $WHAT.gnuplot + +for FILE in $DATA_FILE +do + if [ $FILE != $LAST ] + then + BASE=${FILE##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} + echo "'"$FILE"'" title "'"$TITLE"'" ",\\" >> $WHAT.gnuplot + fi +done +BASE=${LAST##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} +echo "'"$LAST"'" title "'"$TITLE"'" >> $WHAT.gnuplot + + +gnuplot -persist < $WHAT.gnuplot + +rm $WHAT.gnuplot + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_mean_script.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_mean_script.sh new file mode 100644 index 0000000000000000000000000000000000000000..b10df0240a524e5f600cf03330a260c455a96fc8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_mean_script.sh @@ -0,0 +1,52 @@ +#! /bin/bash +WHAT=$1 +DIR=$2 +MINIC=$3 +MAXIC=$4 +MINOC=$5 +MAXOC=$6 +prefix=$8 + +meanstatsfilename=$2/mean.html + +WORK_DIR=tmp +mkdir $WORK_DIR + +DATA_FILE=`find $DIR -name "*.dat" | grep _${WHAT}` + +if [ -n "$DATA_FILE" ]; then + + echo "" + echo "$1..." + for FILE in $DATA_FILE + do + ##echo hello world + ##echo "mk_mean_script1" ${FILE} + BASE=${FILE##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} + + ##echo "mk_mean_script1" ${TITLE} + cp $FILE ${WORK_DIR}/${TITLE} + + done + + cd $WORK_DIR + ../main $1 $3 $4 $5 $6 * >> ../$meanstatsfilename + ../mk_new_gnuplot.sh $1 $2 $7 + rm -f *.gnuplot + cd .. + + echo '
' >> $meanstatsfilename + + webpagefilename=$2/index.html + # echo '

'${WHAT}'

' >> $webpagefilename + echo '
'${WHAT}'
' >> $webpagefilename + +fi + +rm -R $WORK_DIR + + + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_new_gnuplot.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_new_gnuplot.sh new file mode 100644 index 0000000000000000000000000000000000000000..fad3b23a46dc0e6d6a24f78dff7a9d5785c3e1d2 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/mk_new_gnuplot.sh @@ -0,0 +1,54 @@ +#!/bin/bash +WHAT=$1 +DIR=$2 + +cat ../gnuplot_common_settings.hh > ${WHAT}.gnuplot + +echo "set title " `grep ${WHAT} ../action_settings.txt | head -n 1 | cut -d ";" -f 2` >> $WHAT.gnuplot +echo "set xlabel " `grep ${WHAT} ../action_settings.txt | head -n 1 | cut -d ";" -f 3` " offset 0,0" >> $WHAT.gnuplot +echo "set xrange [" `grep ${WHAT} ../action_settings.txt | head -n 1 | cut -d ";" -f 4` "]" >> $WHAT.gnuplot + +if [ $# > 3 ]; then + if [ "$3" == "tiny" ]; then + echo "set xrange [2:16]" >> $WHAT.gnuplot + echo "set nologscale" >> $WHAT.gnuplot + fi +fi + + + +DATA_FILE=`cat ../order_lib` +echo set term postscript color rounded enhanced >> $WHAT.gnuplot +echo set output "'"../${DIR}/$WHAT.ps"'" >> $WHAT.gnuplot + +# echo set term svg color rounded enhanced >> $WHAT.gnuplot +# echo "set terminal svg enhanced size 1000 1000 fname \"Times\" fsize 36" >> $WHAT.gnuplot +# echo set output "'"../${DIR}/$WHAT.svg"'" >> $WHAT.gnuplot + +echo plot \\ >> $WHAT.gnuplot + +for FILE in $DATA_FILE +do + LAST=$FILE +done + +for FILE in $DATA_FILE +do + BASE=${FILE##*/} ; BASE=${FILE##*/} ; AVANT=bench_${WHAT}_ ; REDUC=${BASE##*$AVANT} ; TITLE=${REDUC%.dat} + + echo "'"$FILE"'" `grep $TITLE ../perlib_plot_settings.txt | head -n 1 | cut -d ";" -f 2` "\\" >> $WHAT.gnuplot + if [ $FILE != $LAST ] + then + echo ", \\" >> $WHAT.gnuplot + fi +done +echo " " >> $WHAT.gnuplot + +gnuplot -persist < $WHAT.gnuplot + +rm $WHAT.gnuplot + +ps2pdf ../${DIR}/$WHAT.ps ../${DIR}/$WHAT.pdf +convert -background white -density 120 -rotate 90 -resize 800 +dither -colors 256 -quality 0 ../${DIR}/$WHAT.ps -background white -flatten ../${DIR}/$WHAT.png + +# pstoedit -rotate -90 -xscale 0.8 -yscale 0.8 -centered -yshift -50 -xshift -100 -f plot-svg aat.ps aat2.svg diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/perlib_plot_settings.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/perlib_plot_settings.txt new file mode 100644 index 0000000000000000000000000000000000000000..f023cfe02f82ef2d3bd5fb68884df03907691205 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/perlib_plot_settings.txt @@ -0,0 +1,16 @@ +eigen3 ; with lines lw 4 lt 1 lc rgbcolor "black" +eigen2 ; with lines lw 3 lt 1 lc rgbcolor "#999999" +EigenBLAS ; with lines lw 3 lt 3 lc rgbcolor "#999999" +eigen3_novec ; with lines lw 2 lt 1 lc rgbcolor "#999999" +eigen3_nogccvec ; with lines lw 2 lt 2 lc rgbcolor "#991010" +INTEL_MKL ; with lines lw 3 lt 1 lc rgbcolor "#ff0000" +ATLAS ; with lines lw 3 lt 1 lc rgbcolor "#008000" +gmm ; with lines lw 3 lt 1 lc rgbcolor "#0000ff" +ublas ; with lines lw 3 lt 1 lc rgbcolor "#00b7ff" +mtl4 ; with lines lw 3 lt 1 lc rgbcolor "#d18847" +blitz ; with lines lw 3 lt 1 lc rgbcolor "#ff00ff" +F77 ; with lines lw 3 lt 3 lc rgbcolor "#e6e64c" +OPENBLAS ; with lines lw 3 lt 1 lc rgbcolor "#C05600" +C ; with lines lw 3 lt 3 lc rgbcolor "#e6bd96" +ACML ; with lines lw 2 lt 3 lc rgbcolor "#e6e64c" +blaze ; with lines lw 3 lt 1 lc rgbcolor "#ff00ff" diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/regularize.cxx b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/regularize.cxx new file mode 100644 index 0000000000000000000000000000000000000000..eea2b8b85f2f50863dd1e1d53d00cf45c34cc49b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/regularize.cxx @@ -0,0 +1,131 @@ +//===================================================== +// File : regularize.cxx +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:15 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include +#include +#include +#include +#include "bench_parameter.hh" +#include + +using namespace std; + +void read_xy_file(const string & filename, vector & tab_sizes, vector & tab_mflops); +void regularize_curve(const string & filename, + const vector & tab_mflops, + const vector & tab_sizes, + int start_cut_size, int stop_cut_size); +///////////////////////////////////////////////////////////////////////////////////////////////// + +int main( int argc , char *argv[] ) +{ + + // input data + + if (argc<4){ + INFOS("!!! Error ... usage : main filename start_cut_size stop_cut_size regularize_filename"); + exit(0); + } + INFOS(argc); + + int start_cut_size=atoi(argv[2]); + int stop_cut_size=atoi(argv[3]); + + string filename=argv[1]; + string regularize_filename=argv[4]; + + INFOS(filename); + INFOS("start_cut_size="< tab_sizes; + vector tab_mflops; + + read_xy_file(filename,tab_sizes,tab_mflops); + + // regularizeing + + regularize_curve(regularize_filename,tab_mflops,tab_sizes,start_cut_size,stop_cut_size); + + +} + +////////////////////////////////////////////////////////////////////////////////////// + +void regularize_curve(const string & filename, + const vector & tab_mflops, + const vector & tab_sizes, + int start_cut_size, int stop_cut_size) +{ + int size=tab_mflops.size(); + ofstream output_file (filename.c_str(),ios::out) ; + + int i=0; + + while(tab_sizes[i] & tab_sizes, vector & tab_mflops){ + + ifstream input_file (filename.c_str(),ios::in) ; + + if (!input_file){ + INFOS("!!! Error opening "<> size >> mflops ){ + nb_point++; + tab_sizes.push_back(size); + tab_mflops.push_back(mflops); + } + SCRUTE(nb_point); + + input_file.close(); +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth.cxx b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth.cxx new file mode 100644 index 0000000000000000000000000000000000000000..e5270cc3295a4e43d7d1cf6ed30bfb4dac874c0a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth.cxx @@ -0,0 +1,198 @@ +//===================================================== +// File : smooth.cxx +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:15 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include +#include +#include +#include +#include +#include "bench_parameter.hh" +#include + +using namespace std; + +void read_xy_file(const string & filename, vector & tab_sizes, vector & tab_mflops); +void write_xy_file(const string & filename, vector & tab_sizes, vector & tab_mflops); +void smooth_curve(const vector & tab_mflops, vector & smooth_tab_mflops,int window_half_width); +void centered_smooth_curve(const vector & tab_mflops, vector & smooth_tab_mflops,int window_half_width); + +///////////////////////////////////////////////////////////////////////////////////////////////// + +int main( int argc , char *argv[] ) +{ + + // input data + + if (argc<3){ + INFOS("!!! Error ... usage : main filename window_half_width smooth_filename"); + exit(0); + } + INFOS(argc); + + int window_half_width=atoi(argv[2]); + + string filename=argv[1]; + string smooth_filename=argv[3]; + + INFOS(filename); + INFOS("window_half_width="< tab_sizes; + vector tab_mflops; + + read_xy_file(filename,tab_sizes,tab_mflops); + + // smoothing + + vector smooth_tab_mflops; + + //smooth_curve(tab_mflops,smooth_tab_mflops,window_half_width); + centered_smooth_curve(tab_mflops,smooth_tab_mflops,window_half_width); + + // output result + + write_xy_file(smooth_filename,tab_sizes,smooth_tab_mflops); + + +} + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +template +double weighted_mean(const VECTOR & data) +{ + + double mean=0.0; + + for (int i=0 ; i & tab_mflops, vector & smooth_tab_mflops,int window_half_width){ + + int window_width=2*window_half_width+1; + + int size=tab_mflops.size(); + + vector sample(window_width); + + for (int i=0 ; i < size ; i++){ + + for ( int j=0 ; j < window_width ; j++ ){ + + int shifted_index=i+j-window_half_width; + if (shifted_index<0) shifted_index=0; + if (shifted_index>size-1) shifted_index=size-1; + sample[j]=tab_mflops[shifted_index]; + + } + + smooth_tab_mflops.push_back(weighted_mean(sample)); + + } + +} + +void centered_smooth_curve(const vector & tab_mflops, vector & smooth_tab_mflops,int window_half_width){ + + int max_window_width=2*window_half_width+1; + + int size=tab_mflops.size(); + + + for (int i=0 ; i < size ; i++){ + + deque sample; + + + sample.push_back(tab_mflops[i]); + + for ( int j=1 ; j <= window_half_width ; j++ ){ + + int before=i-j; + int after=i+j; + + if ((before>=0)&&(after & tab_sizes, vector & tab_mflops){ + + ofstream output_file (filename.c_str(),ios::out) ; + + for (int i=0 ; i < tab_sizes.size() ; i++) + { + output_file << tab_sizes[i] << " " << tab_mflops[i] << endl ; + } + + output_file.close(); + +} + + +/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void read_xy_file(const string & filename, vector & tab_sizes, vector & tab_mflops){ + + ifstream input_file (filename.c_str(),ios::in) ; + + if (!input_file){ + INFOS("!!! Error opening "<> size >> mflops ){ + nb_point++; + tab_sizes.push_back(size); + tab_mflops.push_back(mflops); + } + SCRUTE(nb_point); + + input_file.close(); +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth_all.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..3e5bfdf47f6b6ecce273307f126d3fb75e97eb5a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/data/smooth_all.sh @@ -0,0 +1,68 @@ +#! /bin/bash +ORIG_DIR=$1 +SMOOTH_DIR=${ORIG_DIR}_smooth +mkdir ${SMOOTH_DIR} + +AXPY_FILE=`find ${ORIG_DIR} -name "*.dat" | grep axpy` +for FILE in ${AXPY_FILE} +do + echo $FILE + BASE=${FILE##*/} + ./smooth ${ORIG_DIR}/${BASE} 4 ${SMOOTH_DIR}/${BASE}_tmp + ./regularize ${SMOOTH_DIR}/${BASE}_tmp 2500 15000 ${SMOOTH_DIR}/${BASE} + rm -f ${SMOOTH_DIR}/${BASE}_tmp +done + + +MATRIX_VECTOR_FILE=`find ${ORIG_DIR} -name "*.dat" | grep matrix_vector` +for FILE in ${MATRIX_VECTOR_FILE} +do + echo $FILE + BASE=${FILE##*/} + ./smooth ${ORIG_DIR}/${BASE} 4 ${SMOOTH_DIR}/${BASE}_tmp + ./regularize ${SMOOTH_DIR}/${BASE}_tmp 50 180 ${SMOOTH_DIR}/${BASE} + rm -f ${SMOOTH_DIR}/${BASE}_tmp +done + +MATRIX_MATRIX_FILE=`find ${ORIG_DIR} -name "*.dat" | grep matrix_matrix` +for FILE in ${MATRIX_MATRIX_FILE} +do + echo $FILE + BASE=${FILE##*/} + ./smooth ${ORIG_DIR}/${BASE} 4 ${SMOOTH_DIR}/${BASE} +done + +AAT_FILE=`find ${ORIG_DIR} -name "*.dat" | grep _aat` +for FILE in ${AAT_FILE} +do + echo $FILE + BASE=${FILE##*/} + ./smooth ${ORIG_DIR}/${BASE} 4 ${SMOOTH_DIR}/${BASE} +done + + +ATA_FILE=`find ${ORIG_DIR} -name "*.dat" | grep _ata` +for FILE in ${ATA_FILE} +do + echo $FILE + BASE=${FILE##*/} + ./smooth ${ORIG_DIR}/${BASE} 4 ${SMOOTH_DIR}/${BASE} +done + +### no smoothing for tinyvector and matrices libs + +TINY_BLITZ_FILE=`find ${ORIG_DIR} -name "*.dat" | grep tiny_blitz` +for FILE in ${TINY_BLITZ_FILE} +do + echo $FILE + BASE=${FILE##*/} + cp ${ORIG_DIR}/${BASE} ${SMOOTH_DIR}/${BASE} +done + +TVMET_FILE=`find ${ORIG_DIR} -name "*.dat" | grep tvmet` +for FILE in ${TVMET_FILE} +do + echo $FILE + BASE=${FILE##*/} + cp ${ORIG_DIR}/${BASE} ${SMOOTH_DIR}/${BASE} +done diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench.hh new file mode 100644 index 0000000000000000000000000000000000000000..7b7b951b509e7e75e9251ca35433c1a2cfe5150d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench.hh @@ -0,0 +1,168 @@ +//===================================================== +// File : bench.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:16 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BENCH_HH +#define BENCH_HH + +#include "btl.hh" +#include "bench_parameter.hh" +#include +#include "utilities.h" +#include "size_lin_log.hh" +#include "xy_file.hh" +#include +#include +#include "timers/portable_perf_analyzer.hh" +// #include "timers/mixed_perf_analyzer.hh" +// #include "timers/x86_perf_analyzer.hh" +// #include "timers/STL_perf_analyzer.hh" +#ifdef HAVE_MKL +extern "C" void cblas_saxpy(const int, const float, const float*, const int, float *, const int); +#endif +using namespace std; + +template class Perf_Analyzer, class Action> +BTL_DONT_INLINE void bench( int size_min, int size_max, int nb_point ) +{ + if (BtlConfig::skipAction(Action::name())) + return; + + string filename="bench_"+Action::name()+".dat"; + + INFOS("starting " < tab_mflops(nb_point); + std::vector tab_sizes(nb_point); + + // matrices and vector size calculations + size_lin_log(nb_point,size_min,size_max,tab_sizes); + + std::vector oldSizes; + std::vector oldFlops; + bool hasOldResults = read_xy_file(filename, oldSizes, oldFlops, true); + int oldi = oldSizes.size() - 1; + + // loop on matrix size + Perf_Analyzer perf_action; + for (int i=nb_point-1;i>=0;i--) + { + //INFOS("size=" <=0 && oldSizes[oldi]>tab_sizes[i]) + --oldi; + if (oldi>=0 && oldSizes[oldi]==tab_sizes[i]) + { + if (oldFlops[oldi] "; + else + std::cout << "\t < "; + std::cout << oldFlops[oldi]; + } + --oldi; + } + std::cout << " MFlops (" << nb_point-i << "/" << nb_point << ")" << std::endl; + } + + if (!BtlConfig::Instance.overwriteResults) + { + if (hasOldResults) + { + // merge the two data + std::vector newSizes; + std::vector newFlops; + unsigned int i=0; + unsigned int j=0; + while (i +BTL_DONT_INLINE void bench( int size_min, int size_max, int nb_point ){ + + // if the rdtsc is not available : + bench(size_min,size_max,nb_point); + // if the rdtsc is available : +// bench(size_min,size_max,nb_point); + + + // Only for small problem size. Otherwize it will be too long +// bench(size_min,size_max,nb_point); +// bench(size_min,size_max,nb_point); + +} + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench_parameter.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench_parameter.hh new file mode 100644 index 0000000000000000000000000000000000000000..2b01149f914433f2f4cf79e3080409badf734037 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/bench_parameter.hh @@ -0,0 +1,53 @@ +//===================================================== +// File : bench_parameter.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:16 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BENCH_PARAMETER_HH +#define BENCH_PARAMETER_HH + +// minimal time for each measurement +#define REAL_TYPE float +// minimal time for each measurement +#define MIN_TIME 0.2 +// nb of point on bench curves +#define NB_POINT 100 +// min vector size for axpy bench +#define MIN_AXPY 5 +// max vector size for axpy bench +#define MAX_AXPY 3000000 +// min matrix size for matrix vector product bench +#define MIN_MV 5 +// max matrix size for matrix vector product bench +#define MAX_MV 5000 +// min matrix size for matrix matrix product bench +#define MIN_MM 5 +// max matrix size for matrix matrix product bench +#define MAX_MM MAX_MV +// min matrix size for LU bench +#define MIN_LU 5 +// max matrix size for LU bench +#define MAX_LU 3000 +// max size for tiny vector and matrix +#define TINY_MV_MAX_SIZE 16 +// default nb_sample for x86 timer +#define DEFAULT_NB_SAMPLE 1000 + +// how many times we run a single bench (keep the best perf) +#define DEFAULT_NB_TRIES 3 + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/btl.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/btl.hh new file mode 100644 index 0000000000000000000000000000000000000000..706b00fb05f1109852a8537f01618031ab792de7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/btl.hh @@ -0,0 +1,242 @@ +//===================================================== +// File : btl.hh +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BTL_HH +#define BTL_HH + +#include "bench_parameter.hh" +#include +#include +#include +#include +#include "utilities.h" + +#if (defined __GNUC__) +#define BTL_ALWAYS_INLINE __attribute__((always_inline)) inline +#else +#define BTL_ALWAYS_INLINE inline +#endif + +#if (defined __GNUC__) +#define BTL_DONT_INLINE __attribute__((noinline)) +#else +#define BTL_DONT_INLINE +#endif + +#if (defined __GNUC__) +#define BTL_ASM_COMMENT(X) asm("#" X) +#else +#define BTL_ASM_COMMENT(X) +#endif + +#ifdef __SSE__ +#include "xmmintrin.h" +// This enables flush to zero (FTZ) and denormals are zero (DAZ) modes: +#define BTL_DISABLE_SSE_EXCEPTIONS() { _mm_setcsr(_mm_getcsr() | 0x8040); } +#else +#define BTL_DISABLE_SSE_EXCEPTIONS() +#endif + +/** Enhanced std::string +*/ +class BtlString : public std::string +{ +public: + BtlString() : std::string() {} + BtlString(const BtlString& str) : std::string(static_cast(str)) {} + BtlString(const std::string& str) : std::string(str) {} + BtlString(const char* str) : std::string(str) {} + + operator const char* () const { return c_str(); } + + void trim( bool left = true, bool right = true ) + { + int lspaces, rspaces, len = length(), i; + lspaces = rspaces = 0; + + if ( left ) + for (i=0; i=0 && (at(i)==' '||at(i)=='\t'||at(i)=='\r'||at(i)=='\n'); rspaces++,i--); + + *this = substr(lspaces, len-lspaces-rspaces); + } + + std::vector split( const BtlString& delims = "\t\n ") const + { + std::vector ret; + unsigned int numSplits = 0; + size_t start, pos; + start = 0; + do + { + pos = find_first_of(delims, start); + if (pos == start) + { + ret.push_back(""); + start = pos + 1; + } + else if (pos == npos) + ret.push_back( substr(start) ); + else + { + ret.push_back( substr(start, pos - start) ); + start = pos + 1; + } + //start = find_first_not_of(delims, start); + ++numSplits; + } while (pos != npos); + return ret; + } + + bool endsWith(const BtlString& str) const + { + if(str.size()>this->size()) + return false; + return this->substr(this->size()-str.size(),str.size()) == str; + } + bool contains(const BtlString& str) const + { + return this->find(str)size(); + } + bool beginsWith(const BtlString& str) const + { + if(str.size()>this->size()) + return false; + return this->substr(0,str.size()) == str; + } + + BtlString toLowerCase( void ) + { + std::transform(begin(), end(), begin(), static_cast(::tolower) ); + return *this; + } + BtlString toUpperCase( void ) + { + std::transform(begin(), end(), begin(), static_cast(::toupper) ); + return *this; + } + + /** Case insensitive comparison. + */ + bool isEquiv(const BtlString& str) const + { + BtlString str0 = *this; + str0.toLowerCase(); + BtlString str1 = str; + str1.toLowerCase(); + return str0 == str1; + } + + /** Decompose the current string as a path and a file. + For instance: "dir1/dir2/file.ext" leads to path="dir1/dir2/" and filename="file.ext" + */ + void decomposePathAndFile(BtlString& path, BtlString& filename) const + { + std::vector elements = this->split("/\\"); + path = ""; + filename = elements.back(); + elements.pop_back(); + if (this->at(0)=='/') + path = "/"; + for (unsigned int i=0 ; i config = BtlString(_config).split(" \t\n"); + for (unsigned int i = 0; i m_selectedActionNames; +}; + +#define BTL_MAIN \ + BtlConfig BtlConfig::Instance + +#endif // BTL_HH diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_function.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_function.hh new file mode 100644 index 0000000000000000000000000000000000000000..e467cb64845c64b13b418c7873eef2f8b056ee4f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_function.hh @@ -0,0 +1,54 @@ +//===================================================== +// File : init_function.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:18 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef INIT_FUNCTION_HH +#define INIT_FUNCTION_HH + +double simple_function(int index) +{ + return index; +} + +double simple_function(int index_i, int index_j) +{ + return index_i+index_j; +} + +double pseudo_random(int /*index*/) +{ + return std::rand()/double(RAND_MAX); +} + +double pseudo_random(int /*index_i*/, int /*index_j*/) +{ + return std::rand()/double(RAND_MAX); +} + + +double null_function(int /*index*/) +{ + return 0.0; +} + +double null_function(int /*index_i*/, int /*index_j*/) +{ + return 0.0; +} + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_matrix.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_matrix.hh new file mode 100644 index 0000000000000000000000000000000000000000..6382d30c830caa346fd17f88be35c3d2470544fb --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/init/init_matrix.hh @@ -0,0 +1,64 @@ +//===================================================== +// File : init_matrix.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:19 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef INIT_MATRIX_HH +#define INIT_MATRIX_HH + +// The Vector class must satisfy the following part of STL vector concept : +// resize() method +// [] operator for setting element +// value_type defined +template +BTL_DONT_INLINE void init_row(Vector & X, int size, int row){ + + X.resize(size); + + for (unsigned int j=0;j +BTL_DONT_INLINE void init_matrix(Vector & A, int size){ + A.resize(size); + for (unsigned int row=0; row(A[row],size,row); + } +} + +template +BTL_DONT_INLINE void init_matrix_symm(Matrix& A, int size){ + A.resize(size); + for (unsigned int row=0; row +// Copyright (C) EDF R&D, lun sep 30 14:23:18 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef INIT_VECTOR_HH +#define INIT_VECTOR_HH + +// The Vector class must satisfy the following part of STL vector concept : +// resize() method +// [] operator for setting element +// value_type defined +template +void init_vector(Vector & X, int size){ + + X.resize(size); + + for (unsigned int i=0;i +// Copyright (C) EDF R&D, lun sep 30 14:23:16 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BENCH_STATIC_HH +#define BENCH_STATIC_HH + +#include "btl.hh" +#include "bench_parameter.hh" +#include +#include "utilities.h" +#include "xy_file.hh" +#include "static/static_size_generator.hh" +#include "timers/portable_perf_analyzer.hh" +// #include "timers/mixed_perf_analyzer.hh" +// #include "timers/x86_perf_analyzer.hh" + +using namespace std; + + +template class Perf_Analyzer, template class Action, template class Interface> +BTL_DONT_INLINE void bench_static(void) +{ + if (BtlConfig::skipAction(Action >::name())) + return; + + string filename = "bench_" + Action >::name() + ".dat"; + + INFOS("starting " << filename); + + const int max_size = TINY_MV_MAX_SIZE; + + std::vector tab_mflops; + std::vector tab_sizes; + + static_size_generator::go(tab_sizes,tab_mflops); + + dump_xy_file(tab_sizes,tab_mflops,filename); +} + +// default Perf Analyzer +template class Action, template class Interface> +BTL_DONT_INLINE void bench_static(void) +{ + bench_static(); + //bench_static(); + //bench_static(); +} + +#endif + + + + + + + + + + + + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/static/intel_bench_fixed_size.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/static/intel_bench_fixed_size.hh new file mode 100644 index 0000000000000000000000000000000000000000..b4edcbc46b88b41885becf1d9761201d744f120b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/static/intel_bench_fixed_size.hh @@ -0,0 +1,66 @@ +//===================================================== +// File : intel_bench_fixed_size.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar dc 3 18:59:37 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _BENCH_FIXED_SIZE_HH_ +#define _BENCH_FIXED_SIZE_HH_ + +#include "utilities.h" +#include "function_time.hh" + +template +double bench_fixed_size(int size, unsigned long long & nb_calc,unsigned long long & nb_init) +{ + + Action action(size); + + double time_baseline=time_init(nb_init,action); + + while (time_baseline < MIN_TIME) { + + //INFOS("nb_init="< > > perf_action; + tab_mflops.push_back(perf_action.eval_mflops(SIZE)); + std::cout << tab_mflops.back() << " MFlops" << std::endl; + static_size_generator::go(tab_sizes,tab_mflops); + }; +}; + +//recursion end + +template class Perf_Analyzer, template class Action, template class Interface> +struct static_size_generator<1,Perf_Analyzer,Action,Interface>{ + static void go(vector & tab_sizes, vector & tab_mflops) + { + tab_sizes.push_back(1); + Perf_Analyzer > > perf_action; + tab_mflops.push_back(perf_action.eval_mflops(1)); + }; +}; + +#endif + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/STL_perf_analyzer.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/STL_perf_analyzer.hh new file mode 100644 index 0000000000000000000000000000000000000000..c9f894b1ffed96e630f1c54eb7972a51a77bf3cc --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/STL_perf_analyzer.hh @@ -0,0 +1,82 @@ +//===================================================== +// File : STL_perf_analyzer.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar dc 3 18:59:35 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _STL_PERF_ANALYSER_HH +#define _STL_PERF_ANALYSER_HH + +#include "STL_timer.hh" +#include "bench_parameter.hh" + +template +class STL_Perf_Analyzer{ +public: + STL_Perf_Analyzer(unsigned long long nb_sample=DEFAULT_NB_SAMPLE):_nb_sample(nb_sample),_chronos() + { + MESSAGE("STL_Perf_Analyzer Ctor"); + }; + STL_Perf_Analyzer( const STL_Perf_Analyzer & ){ + INFOS("Copy Ctor not implemented"); + exit(0); + }; + ~STL_Perf_Analyzer( void ){ + MESSAGE("STL_Perf_Analyzer Dtor"); + }; + + + inline double eval_mflops(int size) + { + + ACTION action(size); + + _chronos.start_baseline(_nb_sample); + + do { + + action.initialize(); + } while (_chronos.check()); + + double baseline_time=_chronos.get_time(); + + _chronos.start(_nb_sample); + do { + action.initialize(); + action.calculate(); + } while (_chronos.check()); + + double calculate_time=_chronos.get_time(); + + double corrected_time=calculate_time-baseline_time; + + // cout << size <<" "< +// Copyright (C) EDF R&D, mar dc 3 18:59:35 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +// STL Timer Class. Adapted (L.P.) from the timer class by Musser et Al +// described int the Book : STL Tutorial and reference guide. +// Define a timer class for analyzing algorithm performance. +#include +#include +#include +#include +#include +using namespace std; + +class STL_Timer { +public: + STL_Timer(){ baseline = false; }; // Default constructor + // Start a series of r trials: + void start(unsigned int r){ + reps = r; + count = 0; + iterations.clear(); + iterations.reserve(reps); + initial = time(0); + }; + // Start a series of r trials to determine baseline time: + void start_baseline(unsigned int r) + { + baseline = true; + start(r); + } + // Returns true if the trials have been completed, else false + bool check() + { + ++count; + final = time(0); + if (initial < final) { + iterations.push_back(count); + initial = final; + count = 0; + } + return (iterations.size() < reps); + }; + // Returns the results for external use + double get_time( void ) + { + sort(iterations.begin(), iterations.end()); + return 1.0/iterations[reps/2]; + }; +private: + unsigned int reps; // Number of trials + // For storing loop iterations of a trial + vector iterations; + // For saving initial and final times of a trial + time_t initial, final; + // For counting loop iterations of a trial + unsigned long count; + // true if this is a baseline computation, false otherwise + bool baseline; + // For recording the baseline time + double baseline_time; +}; + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/mixed_perf_analyzer.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/mixed_perf_analyzer.hh new file mode 100644 index 0000000000000000000000000000000000000000..e190236e0a6b7208c18698170bd234a5fd63c9c8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/mixed_perf_analyzer.hh @@ -0,0 +1,73 @@ +//===================================================== +// File : mixed_perf_analyzer.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar dc 3 18:59:36 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _MIXED_PERF_ANALYSER_HH +#define _MIXED_PERF_ANALYSER_HH + +#include "x86_perf_analyzer.hh" +#include "portable_perf_analyzer.hh" + +// choose portable perf analyzer for long calculations and x86 analyser for short ones + + +template +class Mixed_Perf_Analyzer{ + +public: + Mixed_Perf_Analyzer( void ):_x86pa(),_ppa(),_use_ppa(true) + { + MESSAGE("Mixed_Perf_Analyzer Ctor"); + }; + Mixed_Perf_Analyzer( const Mixed_Perf_Analyzer & ){ + INFOS("Copy Ctor not implemented"); + exit(0); + }; + ~Mixed_Perf_Analyzer( void ){ + MESSAGE("Mixed_Perf_Analyzer Dtor"); + }; + + + inline double eval_mflops(int size) + { + + double result=0.0; + if (_use_ppa){ + result=_ppa.eval_mflops(size); + if (_ppa.get_nb_calc()>DEFAULT_NB_SAMPLE){_use_ppa=false;} + } + else{ + result=_x86pa.eval_mflops(size); + } + + return result; + } + +private: + + Portable_Perf_Analyzer _ppa; + X86_Perf_Analyzer _x86pa; + bool _use_ppa; + +}; + +#endif + + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/portable_perf_analyzer.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/portable_perf_analyzer.hh new file mode 100644 index 0000000000000000000000000000000000000000..5e579fb49afe063ff18874aa52f54fcbacda3bb9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/portable_perf_analyzer.hh @@ -0,0 +1,103 @@ +//===================================================== +// File : portable_perf_analyzer.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar d�c 3 18:59:35 CET 2002 +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _PORTABLE_PERF_ANALYZER_HH +#define _PORTABLE_PERF_ANALYZER_HH + +#include "utilities.h" +#include "timers/portable_timer.hh" + +template +class Portable_Perf_Analyzer{ +public: + Portable_Perf_Analyzer( ):_nb_calc(0), m_time_action(0), _chronos(){ + MESSAGE("Portable_Perf_Analyzer Ctor"); + }; + Portable_Perf_Analyzer( const Portable_Perf_Analyzer & ){ + INFOS("Copy Ctor not implemented"); + exit(0); + }; + ~Portable_Perf_Analyzer(){ + MESSAGE("Portable_Perf_Analyzer Dtor"); + }; + + BTL_DONT_INLINE double eval_mflops(int size) + { + Action action(size); + +// action.initialize(); +// time_action = time_calculate(action); + while (m_time_action < MIN_TIME) + { + if(_nb_calc==0) _nb_calc = 1; + else _nb_calc *= 2; + action.initialize(); + m_time_action = time_calculate(action); + } + + // optimize + for (int i=1; i +// Copyright (C) EDF R&D, mar d�c 3 18:59:35 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _PORTABLE_PERF_ANALYZER_HH +#define _PORTABLE_PERF_ANALYZER_HH + +#include "utilities.h" +#include "timers/portable_timer.hh" + +template +class Portable_Perf_Analyzer{ +public: + Portable_Perf_Analyzer( void ):_nb_calc(1),_nb_init(1),_chronos(){ + MESSAGE("Portable_Perf_Analyzer Ctor"); + }; + Portable_Perf_Analyzer( const Portable_Perf_Analyzer & ){ + INFOS("Copy Ctor not implemented"); + exit(0); + }; + ~Portable_Perf_Analyzer( void ){ + MESSAGE("Portable_Perf_Analyzer Dtor"); + }; + + + + inline double eval_mflops(int size) + { + + Action action(size); + +// double time_baseline = time_init(action); +// while (time_baseline < MIN_TIME_INIT) +// { +// _nb_init *= 2; +// time_baseline = time_init(action); +// } +// +// // optimize +// for (int i=1; i +#include + + +class Portable_Timer +{ + public: + + Portable_Timer() + { + } + + void start() + { + m_start_time = double(mach_absolute_time())*1e-9;; + + } + + void stop() + { + m_stop_time = double(mach_absolute_time())*1e-9;; + + } + + double elapsed() + { + return user_time(); + } + + double user_time() + { + return m_stop_time - m_start_time; + } + + +private: + + double m_stop_time, m_start_time; + +}; // Portable_Timer (Apple) + +#else + +#include +#include +#include +#include + +class Portable_Timer +{ + public: + + Portable_Timer() + { + m_clkid = BtlConfig::Instance.realclock ? CLOCK_REALTIME : CLOCK_PROCESS_CPUTIME_ID; + } + + Portable_Timer(int clkid) : m_clkid(clkid) + {} + + void start() + { + timespec ts; + clock_gettime(m_clkid, &ts); + m_start_time = double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec); + + } + + void stop() + { + timespec ts; + clock_gettime(m_clkid, &ts); + m_stop_time = double(ts.tv_sec) + 1e-9 * double(ts.tv_nsec); + + } + + double elapsed() + { + return user_time(); + } + + double user_time() + { + return m_stop_time - m_start_time; + } + + +private: + + int m_clkid; + double m_stop_time, m_start_time; + +}; // Portable_Timer (Linux) + +#endif + +#endif // PORTABLE_TIMER_HPP diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/x86_perf_analyzer.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/x86_perf_analyzer.hh new file mode 100644 index 0000000000000000000000000000000000000000..37ea21dcc81750813a059af0addc4a5eaaaee750 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/timers/x86_perf_analyzer.hh @@ -0,0 +1,108 @@ +//===================================================== +// File : x86_perf_analyzer.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar d�c 3 18:59:35 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _X86_PERF_ANALYSER_HH +#define _X86_PERF_ANALYSER_HH + +#include "x86_timer.hh" +#include "bench_parameter.hh" + +template +class X86_Perf_Analyzer{ +public: + X86_Perf_Analyzer( unsigned long long nb_sample=DEFAULT_NB_SAMPLE):_nb_sample(nb_sample),_chronos() + { + MESSAGE("X86_Perf_Analyzer Ctor"); + _chronos.find_frequency(); + }; + X86_Perf_Analyzer( const X86_Perf_Analyzer & ){ + INFOS("Copy Ctor not implemented"); + exit(0); + }; + ~X86_Perf_Analyzer( void ){ + MESSAGE("X86_Perf_Analyzer Dtor"); + }; + + + inline double eval_mflops(int size) + { + + ACTION action(size); + + int nb_loop=5; + double calculate_time=0.0; + double baseline_time=0.0; + + for (int j=0 ; j < nb_loop ; j++){ + + _chronos.clear(); + + for(int i=0 ; i < _nb_sample ; i++) + { + _chronos.start(); + action.initialize(); + action.calculate(); + _chronos.stop(); + _chronos.add_get_click(); + } + + calculate_time += double(_chronos.get_shortest_clicks())/_chronos.frequency(); + + if (j==0) action.check_result(); + + _chronos.clear(); + + for(int i=0 ; i < _nb_sample ; i++) + { + _chronos.start(); + action.initialize(); + _chronos.stop(); + _chronos.add_get_click(); + + } + + baseline_time+=double(_chronos.get_shortest_clicks())/_chronos.frequency(); + + } + + double corrected_time = (calculate_time-baseline_time)/double(nb_loop); + + +// INFOS("_nb_sample="<<_nb_sample); +// INFOS("baseline_time="< +// Copyright (C) EDF R&D, mar d�c 3 18:59:35 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef _X86_TIMER_HH +#define _X86_TIMER_HH + +#include +#include +#include +#include +//#include "system_time.h" +#define u32 unsigned int +#include +#include "utilities.h" +#include +#include +#include +#include + +// frequence de la becanne en Hz +//#define FREQUENCY 648000000 +//#define FREQUENCY 1400000000 +#define FREQUENCY 1695000000 + +using namespace std; + + +class X86_Timer { + +public : + + X86_Timer( void ):_frequency(FREQUENCY),_nb_sample(0) + { + MESSAGE("X86_Timer Default Ctor"); + } + + inline void start( void ){ + + rdtsc(_click_start.n32[0],_click_start.n32[1]); + + } + + + inline void stop( void ){ + + rdtsc(_click_stop.n32[0],_click_stop.n32[1]); + + } + + + inline double frequency( void ){ + return _frequency; + } + + double get_elapsed_time_in_second( void ){ + + return (_click_stop.n64-_click_start.n64)/double(FREQUENCY); + + + } + + unsigned long long get_click( void ){ + + return (_click_stop.n64-_click_start.n64); + + } + + inline void find_frequency( void ){ + + time_t initial, final; + int dummy=2; + + initial = time(0); + start(); + do { + dummy+=2; + } + while(time(0)==initial); + // On est au debut d'un cycle d'une seconde !!! + initial = time(0); + start(); + do { + dummy+=2; + } + while(time(0)==initial); + final=time(0); + stop(); + // INFOS("fine grained time : "<< get_elapsed_time_in_second()); + // INFOS("coarse grained time : "<< final-initial); + _frequency=_frequency*get_elapsed_time_in_second()/double(final-initial); + /// INFOS("CPU frequency : "<< _frequency); + + } + + void add_get_click( void ){ + + _nb_sample++; + _counted_clicks[get_click()]++; + fill_history_clicks(); + + } + + void dump_statistics(string filemane){ + + ofstream outfile (filemane.c_str(),ios::out) ; + + std::map::iterator itr; + for(itr=_counted_clicks.begin() ; itr!=_counted_clicks.end() ; itr++) + { + outfile << (*itr).first << " " << (*itr).second << endl ; + } + + outfile.close(); + + } + + void dump_history(string filemane){ + + ofstream outfile (filemane.c_str(),ios::out) ; + + + + for(int i=0 ; i<_history_mean_clicks.size() ; i++) + { + outfile << i << " " + << _history_mean_clicks[i] << " " + << _history_shortest_clicks[i] << " " + << _history_most_occured_clicks[i] << endl ; + } + + outfile.close(); + + } + + + + double get_mean_clicks( void ){ + + std::map::iterator itr; + + unsigned long long mean_clicks=0; + + for(itr=_counted_clicks.begin() ; itr!=_counted_clicks.end() ; itr++) + { + + mean_clicks+=(*itr).second*(*itr).first; + } + + return mean_clicks/double(_nb_sample); + + } + + double get_shortest_clicks( void ){ + + return double((*_counted_clicks.begin()).first); + + } + + void fill_history_clicks( void ){ + + _history_mean_clicks.push_back(get_mean_clicks()); + _history_shortest_clicks.push_back(get_shortest_clicks()); + _history_most_occured_clicks.push_back(get_most_occured_clicks()); + + } + + + double get_most_occured_clicks( void ){ + + unsigned long long moc=0; + unsigned long long max_occurence=0; + + std::map::iterator itr; + + for(itr=_counted_clicks.begin() ; itr!=_counted_clicks.end() ; itr++) + { + + if (max_occurence<=(*itr).second){ + max_occurence=(*itr).second; + moc=(*itr).first; + } + } + + return double(moc); + + } + + void clear( void ) + { + _counted_clicks.clear(); + + _history_mean_clicks.clear(); + _history_shortest_clicks.clear(); + _history_most_occured_clicks.clear(); + + _nb_sample=0; + } + + + +private : + + union + { + unsigned long int n32[2] ; + unsigned long long n64 ; + } _click_start; + + union + { + unsigned long int n32[2] ; + unsigned long long n64 ; + } _click_stop; + + double _frequency ; + + map _counted_clicks; + + vector _history_mean_clicks; + vector _history_shortest_clicks; + vector _history_most_occured_clicks; + + unsigned long long _nb_sample; + + + +}; + + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/utils/size_lin_log.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/utils/size_lin_log.hh new file mode 100644 index 0000000000000000000000000000000000000000..bbc9f543df14630d30295a505fe473e04a5a4506 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/generic_bench/utils/size_lin_log.hh @@ -0,0 +1,70 @@ +//===================================================== +// File : size_lin_log.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, mar dc 3 18:59:37 CET 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef SIZE_LIN_LOG +#define SIZE_LIN_LOG + +#include "size_log.hh" + +template +void size_lin_log(const int nb_point, const int /*size_min*/, const int size_max, Vector & X) +{ + int ten=10; + int nine=9; + + X.resize(nb_point); + + if (nb_point>ten){ + + for (int i=0;i +void size_log(const int nb_point, const int size_min, const int size_max, Vector & X) +{ + X.resize(nb_point); + + float ls_min=log(float(size_min)); + float ls_max=log(float(size_max)); + + float ls=0.0; + + float delta_ls=(ls_max-ls_min)/(float(nb_point-1)); + + int size=0; + + for (int i=0;i +//# include ok for gcc3.01 +# include + +/* --- INFOS is always defined (without _DEBUG_): to be used for warnings, with release version --- */ + +# define HEREWEARE cout< +// Copyright (C) EDF R&D, lun sep 30 14:23:20 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef XY_FILE_HH +#define XY_FILE_HH +#include +#include +#include +#include +using namespace std; + +bool read_xy_file(const std::string & filename, std::vector & tab_sizes, + std::vector & tab_mflops, bool quiet = false) +{ + + std::ifstream input_file (filename.c_str(),std::ios::in); + + if (!input_file){ + if (!quiet) { + INFOS("!!! Error opening "<> size >> mflops ){ + nb_point++; + tab_sizes.push_back(size); + tab_mflops.push_back(mflops); + } + SCRUTE(nb_point); + + input_file.close(); + return true; +} + +// The Vector class must satisfy the following part of STL vector concept : +// resize() method +// [] operator for seting element +// the vector element must have the << operator define + +using namespace std; + +template +void dump_xy_file(const Vector_A & X, const Vector_B & Y, const std::string & filename){ + + ofstream outfile (filename.c_str(),ios::out) ; + int size=X.size(); + + for (int i=0;i BLASFUNC(cdotu) (int *, float *, int *, float *, int *); +std::complex BLASFUNC(cdotc) (int *, float *, int *, float *, int *); +std::complex BLASFUNC(zdotu) (int *, double *, int *, double *, int *); +std::complex BLASFUNC(zdotc) (int *, double *, int *, double *, int *); +double BLASFUNC(xdotu) (int *, double *, int *, double *, int *); +double BLASFUNC(xdotc) (int *, double *, int *, double *, int *); +#endif + +int BLASFUNC(cdotuw) (int *, float *, int *, float *, int *, float*); +int BLASFUNC(cdotcw) (int *, float *, int *, float *, int *, float*); +int BLASFUNC(zdotuw) (int *, double *, int *, double *, int *, double*); +int BLASFUNC(zdotcw) (int *, double *, int *, double *, int *, double*); + +int BLASFUNC(saxpy) (int *, float *, float *, int *, float *, int *); +int BLASFUNC(daxpy) (int *, double *, double *, int *, double *, int *); +int BLASFUNC(qaxpy) (int *, double *, double *, int *, double *, int *); +int BLASFUNC(caxpy) (int *, float *, float *, int *, float *, int *); +int BLASFUNC(zaxpy) (int *, double *, double *, int *, double *, int *); +int BLASFUNC(xaxpy) (int *, double *, double *, int *, double *, int *); +int BLASFUNC(caxpyc)(int *, float *, float *, int *, float *, int *); +int BLASFUNC(zaxpyc)(int *, double *, double *, int *, double *, int *); +int BLASFUNC(xaxpyc)(int *, double *, double *, int *, double *, int *); + +int BLASFUNC(scopy) (int *, float *, int *, float *, int *); +int BLASFUNC(dcopy) (int *, double *, int *, double *, int *); +int BLASFUNC(qcopy) (int *, double *, int *, double *, int *); +int BLASFUNC(ccopy) (int *, float *, int *, float *, int *); +int BLASFUNC(zcopy) (int *, double *, int *, double *, int *); +int BLASFUNC(xcopy) (int *, double *, int *, double *, int *); + +int BLASFUNC(sswap) (int *, float *, int *, float *, int *); +int BLASFUNC(dswap) (int *, double *, int *, double *, int *); +int BLASFUNC(qswap) (int *, double *, int *, double *, int *); +int BLASFUNC(cswap) (int *, float *, int *, float *, int *); +int BLASFUNC(zswap) (int *, double *, int *, double *, int *); +int BLASFUNC(xswap) (int *, double *, int *, double *, int *); + +float BLASFUNC(sasum) (int *, float *, int *); +float BLASFUNC(scasum)(int *, float *, int *); +double BLASFUNC(dasum) (int *, double *, int *); +double BLASFUNC(qasum) (int *, double *, int *); +double BLASFUNC(dzasum)(int *, double *, int *); +double BLASFUNC(qxasum)(int *, double *, int *); + +int BLASFUNC(isamax)(int *, float *, int *); +int BLASFUNC(idamax)(int *, double *, int *); +int BLASFUNC(iqamax)(int *, double *, int *); +int BLASFUNC(icamax)(int *, float *, int *); +int BLASFUNC(izamax)(int *, double *, int *); +int BLASFUNC(ixamax)(int *, double *, int *); + +int BLASFUNC(ismax) (int *, float *, int *); +int BLASFUNC(idmax) (int *, double *, int *); +int BLASFUNC(iqmax) (int *, double *, int *); +int BLASFUNC(icmax) (int *, float *, int *); +int BLASFUNC(izmax) (int *, double *, int *); +int BLASFUNC(ixmax) (int *, double *, int *); + +int BLASFUNC(isamin)(int *, float *, int *); +int BLASFUNC(idamin)(int *, double *, int *); +int BLASFUNC(iqamin)(int *, double *, int *); +int BLASFUNC(icamin)(int *, float *, int *); +int BLASFUNC(izamin)(int *, double *, int *); +int BLASFUNC(ixamin)(int *, double *, int *); + +int BLASFUNC(ismin)(int *, float *, int *); +int BLASFUNC(idmin)(int *, double *, int *); +int BLASFUNC(iqmin)(int *, double *, int *); +int BLASFUNC(icmin)(int *, float *, int *); +int BLASFUNC(izmin)(int *, double *, int *); +int BLASFUNC(ixmin)(int *, double *, int *); + +float BLASFUNC(samax) (int *, float *, int *); +double BLASFUNC(damax) (int *, double *, int *); +double BLASFUNC(qamax) (int *, double *, int *); +float BLASFUNC(scamax)(int *, float *, int *); +double BLASFUNC(dzamax)(int *, double *, int *); +double BLASFUNC(qxamax)(int *, double *, int *); + +float BLASFUNC(samin) (int *, float *, int *); +double BLASFUNC(damin) (int *, double *, int *); +double BLASFUNC(qamin) (int *, double *, int *); +float BLASFUNC(scamin)(int *, float *, int *); +double BLASFUNC(dzamin)(int *, double *, int *); +double BLASFUNC(qxamin)(int *, double *, int *); + +float BLASFUNC(smax) (int *, float *, int *); +double BLASFUNC(dmax) (int *, double *, int *); +double BLASFUNC(qmax) (int *, double *, int *); +float BLASFUNC(scmax) (int *, float *, int *); +double BLASFUNC(dzmax) (int *, double *, int *); +double BLASFUNC(qxmax) (int *, double *, int *); + +float BLASFUNC(smin) (int *, float *, int *); +double BLASFUNC(dmin) (int *, double *, int *); +double BLASFUNC(qmin) (int *, double *, int *); +float BLASFUNC(scmin) (int *, float *, int *); +double BLASFUNC(dzmin) (int *, double *, int *); +double BLASFUNC(qxmin) (int *, double *, int *); + +int BLASFUNC(sscal) (int *, float *, float *, int *); +int BLASFUNC(dscal) (int *, double *, double *, int *); +int BLASFUNC(qscal) (int *, double *, double *, int *); +int BLASFUNC(cscal) (int *, float *, float *, int *); +int BLASFUNC(zscal) (int *, double *, double *, int *); +int BLASFUNC(xscal) (int *, double *, double *, int *); +int BLASFUNC(csscal)(int *, float *, float *, int *); +int BLASFUNC(zdscal)(int *, double *, double *, int *); +int BLASFUNC(xqscal)(int *, double *, double *, int *); + +float BLASFUNC(snrm2) (int *, float *, int *); +float BLASFUNC(scnrm2)(int *, float *, int *); + +double BLASFUNC(dnrm2) (int *, double *, int *); +double BLASFUNC(qnrm2) (int *, double *, int *); +double BLASFUNC(dznrm2)(int *, double *, int *); +double BLASFUNC(qxnrm2)(int *, double *, int *); + +int BLASFUNC(srot) (int *, float *, int *, float *, int *, float *, float *); +int BLASFUNC(drot) (int *, double *, int *, double *, int *, double *, double *); +int BLASFUNC(qrot) (int *, double *, int *, double *, int *, double *, double *); +int BLASFUNC(csrot) (int *, float *, int *, float *, int *, float *, float *); +int BLASFUNC(zdrot) (int *, double *, int *, double *, int *, double *, double *); +int BLASFUNC(xqrot) (int *, double *, int *, double *, int *, double *, double *); + +int BLASFUNC(srotg) (float *, float *, float *, float *); +int BLASFUNC(drotg) (double *, double *, double *, double *); +int BLASFUNC(qrotg) (double *, double *, double *, double *); +int BLASFUNC(crotg) (float *, float *, float *, float *); +int BLASFUNC(zrotg) (double *, double *, double *, double *); +int BLASFUNC(xrotg) (double *, double *, double *, double *); + +int BLASFUNC(srotmg)(float *, float *, float *, float *, float *); +int BLASFUNC(drotmg)(double *, double *, double *, double *, double *); + +int BLASFUNC(srotm) (int *, float *, int *, float *, int *, float *); +int BLASFUNC(drotm) (int *, double *, int *, double *, int *, double *); +int BLASFUNC(qrotm) (int *, double *, int *, double *, int *, double *); + +/* Level 2 routines */ + +int BLASFUNC(sger)(int *, int *, float *, float *, int *, + float *, int *, float *, int *); +int BLASFUNC(dger)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); +int BLASFUNC(qger)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); +int BLASFUNC(cgeru)(int *, int *, float *, float *, int *, + float *, int *, float *, int *); +int BLASFUNC(cgerc)(int *, int *, float *, float *, int *, + float *, int *, float *, int *); +int BLASFUNC(zgeru)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); +int BLASFUNC(zgerc)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); +int BLASFUNC(xgeru)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); +int BLASFUNC(xgerc)(int *, int *, double *, double *, int *, + double *, int *, double *, int *); + +int BLASFUNC(sgemv)(char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dgemv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(qgemv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(cgemv)(char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zgemv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xgemv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(strsv) (char *, char *, char *, int *, float *, int *, + float *, int *); +int BLASFUNC(dtrsv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(qtrsv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(ctrsv) (char *, char *, char *, int *, float *, int *, + float *, int *); +int BLASFUNC(ztrsv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(xtrsv) (char *, char *, char *, int *, double *, int *, + double *, int *); + +int BLASFUNC(stpsv) (char *, char *, char *, int *, float *, float *, int *); +int BLASFUNC(dtpsv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(qtpsv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(ctpsv) (char *, char *, char *, int *, float *, float *, int *); +int BLASFUNC(ztpsv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(xtpsv) (char *, char *, char *, int *, double *, double *, int *); + +int BLASFUNC(strmv) (char *, char *, char *, int *, float *, int *, + float *, int *); +int BLASFUNC(dtrmv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(qtrmv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(ctrmv) (char *, char *, char *, int *, float *, int *, + float *, int *); +int BLASFUNC(ztrmv) (char *, char *, char *, int *, double *, int *, + double *, int *); +int BLASFUNC(xtrmv) (char *, char *, char *, int *, double *, int *, + double *, int *); + +int BLASFUNC(stpmv) (char *, char *, char *, int *, float *, float *, int *); +int BLASFUNC(dtpmv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(qtpmv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(ctpmv) (char *, char *, char *, int *, float *, float *, int *); +int BLASFUNC(ztpmv) (char *, char *, char *, int *, double *, double *, int *); +int BLASFUNC(xtpmv) (char *, char *, char *, int *, double *, double *, int *); + +int BLASFUNC(stbmv) (char *, char *, char *, int *, int *, float *, int *, float *, int *); +int BLASFUNC(dtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(qtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(ctbmv) (char *, char *, char *, int *, int *, float *, int *, float *, int *); +int BLASFUNC(ztbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(xtbmv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); + +int BLASFUNC(stbsv) (char *, char *, char *, int *, int *, float *, int *, float *, int *); +int BLASFUNC(dtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(qtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(ctbsv) (char *, char *, char *, int *, int *, float *, int *, float *, int *); +int BLASFUNC(ztbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); +int BLASFUNC(xtbsv) (char *, char *, char *, int *, int *, double *, int *, double *, int *); + +int BLASFUNC(ssymv) (char *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dsymv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(qsymv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(csymv) (char *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zsymv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xsymv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(sspmv) (char *, int *, float *, float *, + float *, int *, float *, float *, int *); +int BLASFUNC(dspmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); +int BLASFUNC(qspmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); +int BLASFUNC(cspmv) (char *, int *, float *, float *, + float *, int *, float *, float *, int *); +int BLASFUNC(zspmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); +int BLASFUNC(xspmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); + +int BLASFUNC(ssyr) (char *, int *, float *, float *, int *, + float *, int *); +int BLASFUNC(dsyr) (char *, int *, double *, double *, int *, + double *, int *); +int BLASFUNC(qsyr) (char *, int *, double *, double *, int *, + double *, int *); +int BLASFUNC(csyr) (char *, int *, float *, float *, int *, + float *, int *); +int BLASFUNC(zsyr) (char *, int *, double *, double *, int *, + double *, int *); +int BLASFUNC(xsyr) (char *, int *, double *, double *, int *, + double *, int *); + +int BLASFUNC(ssyr2) (char *, int *, float *, + float *, int *, float *, int *, float *, int *); +int BLASFUNC(dsyr2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); +int BLASFUNC(qsyr2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); +int BLASFUNC(csyr2) (char *, int *, float *, + float *, int *, float *, int *, float *, int *); +int BLASFUNC(zsyr2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); +int BLASFUNC(xsyr2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); + +int BLASFUNC(sspr) (char *, int *, float *, float *, int *, + float *); +int BLASFUNC(dspr) (char *, int *, double *, double *, int *, + double *); +int BLASFUNC(qspr) (char *, int *, double *, double *, int *, + double *); +int BLASFUNC(cspr) (char *, int *, float *, float *, int *, + float *); +int BLASFUNC(zspr) (char *, int *, double *, double *, int *, + double *); +int BLASFUNC(xspr) (char *, int *, double *, double *, int *, + double *); + +int BLASFUNC(sspr2) (char *, int *, float *, + float *, int *, float *, int *, float *); +int BLASFUNC(dspr2) (char *, int *, double *, + double *, int *, double *, int *, double *); +int BLASFUNC(qspr2) (char *, int *, double *, + double *, int *, double *, int *, double *); +int BLASFUNC(cspr2) (char *, int *, float *, + float *, int *, float *, int *, float *); +int BLASFUNC(zspr2) (char *, int *, double *, + double *, int *, double *, int *, double *); +int BLASFUNC(xspr2) (char *, int *, double *, + double *, int *, double *, int *, double *); + +int BLASFUNC(cher) (char *, int *, float *, float *, int *, + float *, int *); +int BLASFUNC(zher) (char *, int *, double *, double *, int *, + double *, int *); +int BLASFUNC(xher) (char *, int *, double *, double *, int *, + double *, int *); + +int BLASFUNC(chpr) (char *, int *, float *, float *, int *, float *); +int BLASFUNC(zhpr) (char *, int *, double *, double *, int *, double *); +int BLASFUNC(xhpr) (char *, int *, double *, double *, int *, double *); + +int BLASFUNC(cher2) (char *, int *, float *, + float *, int *, float *, int *, float *, int *); +int BLASFUNC(zher2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); +int BLASFUNC(xher2) (char *, int *, double *, + double *, int *, double *, int *, double *, int *); + +int BLASFUNC(chpr2) (char *, int *, float *, + float *, int *, float *, int *, float *); +int BLASFUNC(zhpr2) (char *, int *, double *, + double *, int *, double *, int *, double *); +int BLASFUNC(xhpr2) (char *, int *, double *, + double *, int *, double *, int *, double *); + +int BLASFUNC(chemv) (char *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zhemv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xhemv) (char *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(chpmv) (char *, int *, float *, float *, + float *, int *, float *, float *, int *); +int BLASFUNC(zhpmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); +int BLASFUNC(xhpmv) (char *, int *, double *, double *, + double *, int *, double *, double *, int *); + +int BLASFUNC(snorm)(char *, int *, int *, float *, int *); +int BLASFUNC(dnorm)(char *, int *, int *, double *, int *); +int BLASFUNC(cnorm)(char *, int *, int *, float *, int *); +int BLASFUNC(znorm)(char *, int *, int *, double *, int *); + +int BLASFUNC(sgbmv)(char *, int *, int *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dgbmv)(char *, int *, int *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(qgbmv)(char *, int *, int *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(cgbmv)(char *, int *, int *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zgbmv)(char *, int *, int *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xgbmv)(char *, int *, int *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(ssbmv)(char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dsbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(qsbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(csbmv)(char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zsbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xsbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(chbmv)(char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zhbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xhbmv)(char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +/* Level 3 routines */ + +int BLASFUNC(sgemm)(char *, char *, int *, int *, int *, float *, + float *, int *, float *, int *, float *, float *, int *); +int BLASFUNC(dgemm)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); +int BLASFUNC(qgemm)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); +int BLASFUNC(cgemm)(char *, char *, int *, int *, int *, float *, + float *, int *, float *, int *, float *, float *, int *); +int BLASFUNC(zgemm)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); +int BLASFUNC(xgemm)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); + +int BLASFUNC(cgemm3m)(char *, char *, int *, int *, int *, float *, + float *, int *, float *, int *, float *, float *, int *); +int BLASFUNC(zgemm3m)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); +int BLASFUNC(xgemm3m)(char *, char *, int *, int *, int *, double *, + double *, int *, double *, int *, double *, double *, int *); + +int BLASFUNC(sge2mm)(char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *, + float *, float *, int *); +int BLASFUNC(dge2mm)(char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *, + double *, double *, int *); +int BLASFUNC(cge2mm)(char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *, + float *, float *, int *); +int BLASFUNC(zge2mm)(char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *, + double *, double *, int *); + +int BLASFUNC(strsm)(char *, char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *); +int BLASFUNC(dtrsm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(qtrsm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(ctrsm)(char *, char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *); +int BLASFUNC(ztrsm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(xtrsm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); + +int BLASFUNC(strmm)(char *, char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *); +int BLASFUNC(dtrmm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(qtrmm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(ctrmm)(char *, char *, char *, char *, int *, int *, + float *, float *, int *, float *, int *); +int BLASFUNC(ztrmm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); +int BLASFUNC(xtrmm)(char *, char *, char *, char *, int *, int *, + double *, double *, int *, double *, int *); + +int BLASFUNC(ssymm)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dsymm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(qsymm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(csymm)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zsymm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xsymm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(csymm3m)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zsymm3m)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xsymm3m)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(ssyrk)(char *, char *, int *, int *, float *, float *, int *, + float *, float *, int *); +int BLASFUNC(dsyrk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); +int BLASFUNC(qsyrk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); +int BLASFUNC(csyrk)(char *, char *, int *, int *, float *, float *, int *, + float *, float *, int *); +int BLASFUNC(zsyrk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); +int BLASFUNC(xsyrk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); + +int BLASFUNC(ssyr2k)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(dsyr2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(qsyr2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(csyr2k)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zsyr2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(xsyr2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); + +int BLASFUNC(chemm)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zhemm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xhemm)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(chemm3m)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zhemm3m)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); +int BLASFUNC(xhemm3m)(char *, char *, int *, int *, double *, double *, int *, + double *, int *, double *, double *, int *); + +int BLASFUNC(cherk)(char *, char *, int *, int *, float *, float *, int *, + float *, float *, int *); +int BLASFUNC(zherk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); +int BLASFUNC(xherk)(char *, char *, int *, int *, double *, double *, int *, + double *, double *, int *); + +int BLASFUNC(cher2k)(char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zher2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(xher2k)(char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(cher2m)(char *, char *, char *, int *, int *, float *, float *, int *, + float *, int *, float *, float *, int *); +int BLASFUNC(zher2m)(char *, char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); +int BLASFUNC(xher2m)(char *, char *, char *, int *, int *, double *, double *, int *, + double*, int *, double *, double *, int *); + +int BLASFUNC(sgemt)(char *, int *, int *, float *, float *, int *, + float *, int *); +int BLASFUNC(dgemt)(char *, int *, int *, double *, double *, int *, + double *, int *); +int BLASFUNC(cgemt)(char *, int *, int *, float *, float *, int *, + float *, int *); +int BLASFUNC(zgemt)(char *, int *, int *, double *, double *, int *, + double *, int *); + +int BLASFUNC(sgema)(char *, char *, int *, int *, float *, + float *, int *, float *, float *, int *, float *, int *); +int BLASFUNC(dgema)(char *, char *, int *, int *, double *, + double *, int *, double*, double *, int *, double*, int *); +int BLASFUNC(cgema)(char *, char *, int *, int *, float *, + float *, int *, float *, float *, int *, float *, int *); +int BLASFUNC(zgema)(char *, char *, int *, int *, double *, + double *, int *, double*, double *, int *, double*, int *); + +int BLASFUNC(sgems)(char *, char *, int *, int *, float *, + float *, int *, float *, float *, int *, float *, int *); +int BLASFUNC(dgems)(char *, char *, int *, int *, double *, + double *, int *, double*, double *, int *, double*, int *); +int BLASFUNC(cgems)(char *, char *, int *, int *, float *, + float *, int *, float *, float *, int *, float *, int *); +int BLASFUNC(zgems)(char *, char *, int *, int *, double *, + double *, int *, double*, double *, int *, double*, int *); + +int BLASFUNC(sgetf2)(int *, int *, float *, int *, int *, int *); +int BLASFUNC(dgetf2)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(qgetf2)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(cgetf2)(int *, int *, float *, int *, int *, int *); +int BLASFUNC(zgetf2)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(xgetf2)(int *, int *, double *, int *, int *, int *); + +int BLASFUNC(sgetrf)(int *, int *, float *, int *, int *, int *); +int BLASFUNC(dgetrf)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(qgetrf)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(cgetrf)(int *, int *, float *, int *, int *, int *); +int BLASFUNC(zgetrf)(int *, int *, double *, int *, int *, int *); +int BLASFUNC(xgetrf)(int *, int *, double *, int *, int *, int *); + +int BLASFUNC(slaswp)(int *, float *, int *, int *, int *, int *, int *); +int BLASFUNC(dlaswp)(int *, double *, int *, int *, int *, int *, int *); +int BLASFUNC(qlaswp)(int *, double *, int *, int *, int *, int *, int *); +int BLASFUNC(claswp)(int *, float *, int *, int *, int *, int *, int *); +int BLASFUNC(zlaswp)(int *, double *, int *, int *, int *, int *, int *); +int BLASFUNC(xlaswp)(int *, double *, int *, int *, int *, int *, int *); + +int BLASFUNC(sgetrs)(char *, int *, int *, float *, int *, int *, float *, int *, int *); +int BLASFUNC(dgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *); +int BLASFUNC(qgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *); +int BLASFUNC(cgetrs)(char *, int *, int *, float *, int *, int *, float *, int *, int *); +int BLASFUNC(zgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *); +int BLASFUNC(xgetrs)(char *, int *, int *, double *, int *, int *, double *, int *, int *); + +int BLASFUNC(sgesv)(int *, int *, float *, int *, int *, float *, int *, int *); +int BLASFUNC(dgesv)(int *, int *, double *, int *, int *, double*, int *, int *); +int BLASFUNC(qgesv)(int *, int *, double *, int *, int *, double*, int *, int *); +int BLASFUNC(cgesv)(int *, int *, float *, int *, int *, float *, int *, int *); +int BLASFUNC(zgesv)(int *, int *, double *, int *, int *, double*, int *, int *); +int BLASFUNC(xgesv)(int *, int *, double *, int *, int *, double*, int *, int *); + +int BLASFUNC(spotf2)(char *, int *, float *, int *, int *); +int BLASFUNC(dpotf2)(char *, int *, double *, int *, int *); +int BLASFUNC(qpotf2)(char *, int *, double *, int *, int *); +int BLASFUNC(cpotf2)(char *, int *, float *, int *, int *); +int BLASFUNC(zpotf2)(char *, int *, double *, int *, int *); +int BLASFUNC(xpotf2)(char *, int *, double *, int *, int *); + +int BLASFUNC(spotrf)(char *, int *, float *, int *, int *); +int BLASFUNC(dpotrf)(char *, int *, double *, int *, int *); +int BLASFUNC(qpotrf)(char *, int *, double *, int *, int *); +int BLASFUNC(cpotrf)(char *, int *, float *, int *, int *); +int BLASFUNC(zpotrf)(char *, int *, double *, int *, int *); +int BLASFUNC(xpotrf)(char *, int *, double *, int *, int *); + +int BLASFUNC(slauu2)(char *, int *, float *, int *, int *); +int BLASFUNC(dlauu2)(char *, int *, double *, int *, int *); +int BLASFUNC(qlauu2)(char *, int *, double *, int *, int *); +int BLASFUNC(clauu2)(char *, int *, float *, int *, int *); +int BLASFUNC(zlauu2)(char *, int *, double *, int *, int *); +int BLASFUNC(xlauu2)(char *, int *, double *, int *, int *); + +int BLASFUNC(slauum)(char *, int *, float *, int *, int *); +int BLASFUNC(dlauum)(char *, int *, double *, int *, int *); +int BLASFUNC(qlauum)(char *, int *, double *, int *, int *); +int BLASFUNC(clauum)(char *, int *, float *, int *, int *); +int BLASFUNC(zlauum)(char *, int *, double *, int *, int *); +int BLASFUNC(xlauum)(char *, int *, double *, int *, int *); + +int BLASFUNC(strti2)(char *, char *, int *, float *, int *, int *); +int BLASFUNC(dtrti2)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(qtrti2)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(ctrti2)(char *, char *, int *, float *, int *, int *); +int BLASFUNC(ztrti2)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(xtrti2)(char *, char *, int *, double *, int *, int *); + +int BLASFUNC(strtri)(char *, char *, int *, float *, int *, int *); +int BLASFUNC(dtrtri)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(qtrtri)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(ctrtri)(char *, char *, int *, float *, int *, int *); +int BLASFUNC(ztrtri)(char *, char *, int *, double *, int *, int *); +int BLASFUNC(xtrtri)(char *, char *, int *, double *, int *, int *); + +int BLASFUNC(spotri)(char *, int *, float *, int *, int *); +int BLASFUNC(dpotri)(char *, int *, double *, int *, int *); +int BLASFUNC(qpotri)(char *, int *, double *, int *, int *); +int BLASFUNC(cpotri)(char *, int *, float *, int *, int *); +int BLASFUNC(zpotri)(char *, int *, double *, int *, int *); +int BLASFUNC(xpotri)(char *, int *, double *, int *, int *); + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..6510546323266634e9302f2419e40fece91be908 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface.hh @@ -0,0 +1,83 @@ +//===================================================== +// File : blas_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:28 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef blas_PRODUIT_MATRICE_VECTEUR_HH +#define blas_PRODUIT_MATRICE_VECTEUR_HH + +#include +#include +extern "C" +{ +#include "blas.h" + + // Cholesky Factorization +// void spotrf_(const char* uplo, const int* n, float *a, const int* ld, int* info); +// void dpotrf_(const char* uplo, const int* n, double *a, const int* ld, int* info); + void ssytrd_(char *uplo, const int *n, float *a, const int *lda, float *d, float *e, float *tau, float *work, int *lwork, int *info ); + void dsytrd_(char *uplo, const int *n, double *a, const int *lda, double *d, double *e, double *tau, double *work, int *lwork, int *info ); + void sgehrd_( const int *n, int *ilo, int *ihi, float *a, const int *lda, float *tau, float *work, int *lwork, int *info ); + void dgehrd_( const int *n, int *ilo, int *ihi, double *a, const int *lda, double *tau, double *work, int *lwork, int *info ); + + // LU row pivoting +// void dgetrf_( int *m, int *n, double *a, int *lda, int *ipiv, int *info ); +// void sgetrf_(const int* m, const int* n, float *a, const int* ld, int* ipivot, int* info); + // LU full pivoting + void sgetc2_(const int* n, float *a, const int *lda, int *ipiv, int *jpiv, int*info ); + void dgetc2_(const int* n, double *a, const int *lda, int *ipiv, int *jpiv, int*info ); +#ifdef HAS_LAPACK +#endif +} + +#define MAKE_STRING2(S) #S +#define MAKE_STRING(S) MAKE_STRING2(S) + +#define CAT2(A,B) A##B +#define CAT(A,B) CAT2(A,B) + + +template class blas_interface; + + +static char notrans = 'N'; +static char trans = 'T'; +static char nonunit = 'N'; +static char lower = 'L'; +static char right = 'R'; +static char left = 'L'; +static int intone = 1; + + + +#define SCALAR float +#define SCALAR_PREFIX s +#include "blas_interface_impl.hh" +#undef SCALAR +#undef SCALAR_PREFIX + + +#define SCALAR double +#define SCALAR_PREFIX d +#include "blas_interface_impl.hh" +#undef SCALAR +#undef SCALAR_PREFIX + +#endif + + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface_impl.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface_impl.hh new file mode 100644 index 0000000000000000000000000000000000000000..fc4ba2a1f39954351cf520bafd649f118280926b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/blas_interface_impl.hh @@ -0,0 +1,147 @@ + +#define BLAS_FUNC(NAME) CAT(CAT(SCALAR_PREFIX,NAME),_) + +template<> class blas_interface : public c_interface_base +{ + +public : + + static SCALAR fone; + static SCALAR fzero; + + static inline std::string name() + { + return MAKE_STRING(CBLASNAME); + } + + static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + BLAS_FUNC(gemv)(¬rans,&N,&N,&fone,A,&N,B,&intone,&fzero,X,&intone); + } + + static inline void symv(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + BLAS_FUNC(symv)(&lower, &N,&fone,A,&N,B,&intone,&fzero,X,&intone); + } + + static inline void syr2(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + BLAS_FUNC(syr2)(&lower,&N,&fone,B,&intone,X,&intone,A,&N); + } + + static inline void ger(gene_matrix & A, gene_vector & X, gene_vector & Y, int N){ + BLAS_FUNC(ger)(&N,&N,&fone,X,&intone,Y,&intone,A,&N); + } + + static inline void rot(gene_vector & A, gene_vector & B, SCALAR c, SCALAR s, int N){ + BLAS_FUNC(rot)(&N,A,&intone,B,&intone,&c,&s); + } + + static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + BLAS_FUNC(gemv)(&trans,&N,&N,&fone,A,&N,B,&intone,&fzero,X,&intone); + } + + static inline void matrix_matrix_product(gene_matrix & A, gene_matrix & B, gene_matrix & X, int N){ + BLAS_FUNC(gemm)(¬rans,¬rans,&N,&N,&N,&fone,A,&N,B,&N,&fzero,X,&N); + } + + static inline void transposed_matrix_matrix_product(gene_matrix & A, gene_matrix & B, gene_matrix & X, int N){ + BLAS_FUNC(gemm)(¬rans,¬rans,&N,&N,&N,&fone,A,&N,B,&N,&fzero,X,&N); + } + +// static inline void ata_product(gene_matrix & A, gene_matrix & X, int N){ +// ssyrk_(&lower,&trans,&N,&N,&fone,A,&N,&fzero,X,&N); +// } + + static inline void aat_product(gene_matrix & A, gene_matrix & X, int N){ + BLAS_FUNC(syrk)(&lower,¬rans,&N,&N,&fone,A,&N,&fzero,X,&N); + } + + static inline void axpy(SCALAR coef, const gene_vector & X, gene_vector & Y, int N){ + BLAS_FUNC(axpy)(&N,&coef,X,&intone,Y,&intone); + } + + static inline void axpby(SCALAR a, const gene_vector & X, SCALAR b, gene_vector & Y, int N){ + BLAS_FUNC(scal)(&N,&b,Y,&intone); + BLAS_FUNC(axpy)(&N,&a,X,&intone,Y,&intone); + } + + static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ + int N2 = N*N; + BLAS_FUNC(copy)(&N2, X, &intone, C, &intone); + char uplo = 'L'; + int info = 0; + BLAS_FUNC(potrf)(&uplo, &N, C, &N, &info); + if(info!=0) std::cerr << "potrf_ error " << info << "\n"; + } + + static inline void partial_lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ + int N2 = N*N; + BLAS_FUNC(copy)(&N2, X, &intone, C, &intone); + int info = 0; + int * ipiv = (int*)alloca(sizeof(int)*N); + BLAS_FUNC(getrf)(&N, &N, C, &N, ipiv, &info); + if(info!=0) std::cerr << "getrf_ error " << info << "\n"; + } + + static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){ + BLAS_FUNC(copy)(&N, B, &intone, X, &intone); + BLAS_FUNC(trsv)(&lower, ¬rans, &nonunit, &N, L, &N, X, &intone); + } + + static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix & X, int N){ + BLAS_FUNC(copy)(&N, B, &intone, X, &intone); + BLAS_FUNC(trsm)(&right, &lower, ¬rans, &nonunit, &N, &N, &fone, L, &N, X, &N); + } + + static inline void trmm(gene_matrix & A, gene_matrix & B, gene_matrix & /*X*/, int N){ + BLAS_FUNC(trmm)(&left, &lower, ¬rans,&nonunit, &N,&N,&fone,A,&N,B,&N); + } + + #ifdef HAS_LAPACK + + static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ + int N2 = N*N; + BLAS_FUNC(copy)(&N2, X, &intone, C, &intone); + int info = 0; + int * ipiv = (int*)alloca(sizeof(int)*N); + int * jpiv = (int*)alloca(sizeof(int)*N); + BLAS_FUNC(getc2)(&N, C, &N, ipiv, jpiv, &info); + } + + + + static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int N){ + { + int N2 = N*N; + int inc = 1; + BLAS_FUNC(copy)(&N2, X, &inc, C, &inc); + } + int info = 0; + int ilo = 1; + int ihi = N; + int bsize = 64; + int worksize = N*bsize; + SCALAR* d = new SCALAR[N+worksize]; + BLAS_FUNC(gehrd)(&N, &ilo, &ihi, C, &N, d, d+N, &worksize, &info); + delete[] d; + } + + static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){ + { + int N2 = N*N; + int inc = 1; + BLAS_FUNC(copy)(&N2, X, &inc, C, &inc); + } + char uplo = 'U'; + int info = 0; + int bsize = 64; + int worksize = N*bsize; + SCALAR* d = new SCALAR[3*N+worksize]; + BLAS_FUNC(sytrd)(&uplo, &N, C, &N, d, d+N, d+2*N, d+3*N, &worksize, &info); + delete[] d; + } + + #endif // HAS_LAPACK + +}; + +SCALAR blas_interface::fone = SCALAR(1); +SCALAR blas_interface::fzero = SCALAR(0); diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/c_interface_base.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/c_interface_base.h new file mode 100644 index 0000000000000000000000000000000000000000..de613803b7a55beb6635768219d1125dadcefd87 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/BLAS/c_interface_base.h @@ -0,0 +1,73 @@ + +#ifndef BTL_C_INTERFACE_BASE_H +#define BTL_C_INTERFACE_BASE_H + +#include "utilities.h" +#include + +template class c_interface_base +{ + +public: + + typedef real real_type; + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef real* gene_matrix; + typedef real* gene_vector; + + static void free_matrix(gene_matrix & A, int /*N*/){ + delete[] A; + } + + static void free_vector(gene_vector & B){ + delete[] B; + } + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + int N = A_stl.size(); + A = new real[N*N]; + for (int j=0;j +// Copyright (C) EDF R&D, lun sep 30 14:23:28 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "blas_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +#include "action_cholesky.hh" +#include "action_lu_decomp.hh" +#include "action_partial_lu.hh" +#include "action_trisolve_matrix.hh" + +#ifdef HAS_LAPACK +#include "action_hessenberg.hh" +#endif + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + + #ifdef HAS_LAPACK +// bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + #endif + + //bench > >(MIN_LU,MAX_LU,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..4cfc2dcf298fbd1baba1fb0202f3b9d48bae2bd1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/CMakeLists.txt @@ -0,0 +1,2 @@ + +btl_add_bench(btl_STL main.cpp OFF) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/STL_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/STL_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..ef4cc923309fe6c7ce2e1761749cbb420c812ada --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/STL/STL_interface.hh @@ -0,0 +1,244 @@ +//===================================================== +// File : STL_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:24 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef STL_INTERFACE_HH +#define STL_INTERFACE_HH +#include +#include +#include "utilities.h" + +using namespace std; + +template +class STL_interface{ + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef stl_matrix gene_matrix; + + typedef stl_vector gene_vector; + + static inline std::string name( void ) + { + return "STL"; + } + + static void free_matrix(gene_matrix & /*A*/, int /*N*/){} + + static void free_vector(gene_vector & /*B*/){} + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A = A_stl; + } + + static inline void vector_from_stl(gene_vector & B, stl_vector & B_stl){ + B = B_stl; + } + + static inline void vector_to_stl(gene_vector & B, stl_vector & B_stl){ + B_stl = B ; + } + + + static inline void matrix_to_stl(gene_matrix & A, stl_matrix & A_stl){ + A_stl = A ; + } + + static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){ + for (int i=0;i=j) + { + for (int k=0;k > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..e99a0855c997e908ecab1044adef58eb587ec263 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/CMakeLists.txt @@ -0,0 +1,13 @@ + +find_package(BLAZE) +find_package(Boost COMPONENTS system) +if (BLAZE_FOUND AND Boost_FOUND) + include_directories(${BLAZE_INCLUDE_DIR} ${Boost_INCLUDE_DIRS}) + btl_add_bench(btl_blaze main.cpp) + # Note: The newest blaze version requires C++14. + # Ideally, we should set this depending on the version of Blaze we found + set_property(TARGET btl_blaze PROPERTY CXX_STANDARD 14) + if(BUILD_btl_blaze) + target_link_libraries(btl_blaze ${Boost_LIBRARIES}) + endif() +endif () diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/blaze_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/blaze_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..ee1523944125950a4b8d669c0dd835e52f8d3800 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/blaze_interface.hh @@ -0,0 +1,140 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BLAZE_INTERFACE_HH +#define BLAZE_INTERFACE_HH + +#include +#include +// using namespace blaze; + +#include + +template +class blaze_interface { + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef blaze::DynamicMatrix gene_matrix; + typedef blaze::DynamicVector gene_vector; + + static inline std::string name() { return "blaze"; } + + static void free_matrix(gene_matrix & A, int N){ + return ; + } + + static void free_vector(gene_vector & B){ + return ; + } + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl[0].size(), A_stl.size()); + + for (int j=0; j ipvt(N); +// lu_factor(R, ipvt); +// } + +// static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){ +// X = lower_trisolve(L, B); +// } + + static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ + cible = source; + } + + static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){ + cible = source; + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/main.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..80e8f4eaa03a91f285d61a17e09613f53a13505d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blaze/main.cpp @@ -0,0 +1,40 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "blaze_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..880ab7338564d89aaa919e7af064faf06b27e44e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/CMakeLists.txt @@ -0,0 +1,17 @@ + +find_package(Blitz) + +if (BLITZ_FOUND) + include_directories(${BLITZ_INCLUDES}) + + btl_add_bench(btl_blitz btl_blitz.cpp) + if (BUILD_btl_blitz) + target_link_libraries(btl_blitz ${BLITZ_LIBRARIES}) + endif (BUILD_btl_blitz) + + btl_add_bench(btl_tiny_blitz btl_tiny_blitz.cpp OFF) + if (BUILD_btl_tiny_blitz) + target_link_libraries(btl_tiny_blitz ${BLITZ_LIBRARIES}) + endif (BUILD_btl_tiny_blitz) + +endif (BLITZ_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_LU_solve_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_LU_solve_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..dcb9f567feb098552c8090722769ffafee67d32d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_LU_solve_interface.hh @@ -0,0 +1,192 @@ +//===================================================== +// File : blitz_LU_solve_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:31 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BLITZ_LU_SOLVE_INTERFACE_HH +#define BLITZ_LU_SOLVE_INTERFACE_HH + +#include "blitz/array.h" +#include + +BZ_USING_NAMESPACE(blitz) + +template +class blitz_LU_solve_interface : public blitz_interface +{ + +public : + + typedef typename blitz_interface::gene_matrix gene_matrix; + typedef typename blitz_interface::gene_vector gene_vector; + + typedef blitz::Array Pivot_Vector; + + inline static void new_Pivot_Vector(Pivot_Vector & pivot,int N) + { + + pivot.resize(N); + + } + + inline static void free_Pivot_Vector(Pivot_Vector & pivot) + { + + return; + + } + + + static inline real matrix_vector_product_sliced(const gene_matrix & A, gene_vector B, int row, int col_start, int col_end) + { + + real somme=0.; + + for (int j=col_start ; j=big ) big = abs( LU( i, j ) ) ; + } + if( big==0. ) { + INFOS( "blitz_LU_factor::Singular matrix" ) ; + exit( 0 ) ; + } + ImplicitScaling( i ) = 1./big ; + } + // Loop over columns of Crout's method : + for( int j=0; j=big ) { + dum = ImplicitScaling( i )*abs( theSum ) ; + big = dum ; + index_max = i ; + } + } + // Interchanging rows and the scale factor : + if( j!=index_max ) { + for( int k=0; k=0; i-- ) { + theSum = X( i ) ; + // theSum = B( i ) ; + theSum -= matrix_vector_product_sliced(LU, X, i, i+1, N) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*X( Range( i+1, toEnd ) ) ) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*B( Range( i+1, toEnd ) ) ) ; + // Store a component of the solution vector : + X( i ) = theSum/LU( i, i ) ; + // B( i ) = theSum/LU( i, i ) ; + } + + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..a67c47c759df51a89f1f041d65c41f55cd87378d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/blitz_interface.hh @@ -0,0 +1,147 @@ +//===================================================== +// File : blitz_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BLITZ_INTERFACE_HH +#define BLITZ_INTERFACE_HH + +#include +#include +#include +#include +#include +#include + +BZ_USING_NAMESPACE(blitz) + +template +class blitz_interface{ + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef blitz::Array gene_matrix; + typedef blitz::Array gene_vector; +// typedef blitz::Matrix gene_matrix; +// typedef blitz::Vector gene_vector; + + static inline std::string name() { return "blitz"; } + + static void free_matrix(gene_matrix & A, int N){} + + static void free_vector(gene_vector & B){} + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl[0].size(),A_stl.size()); + for (int j=0; j(source); +// for (int i=0;i(source); + cible = source; + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_blitz.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_blitz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16d2b59517cccceeb228df4f8b9cbb91c578462a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_blitz.cpp @@ -0,0 +1,51 @@ +//===================================================== +// File : main.cpp +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "blitz_interface.hh" +#include "blitz_LU_solve_interface.hh" +#include "bench.hh" +#include "action_matrix_vector_product.hh" +#include "action_matrix_matrix_product.hh" +#include "action_axpy.hh" +#include "action_lu_solve.hh" +#include "action_ata_product.hh" +#include "action_aat_product.hh" +#include "action_atv_product.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + //bench > >(MIN_LU,MAX_LU,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_tiny_blitz.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_tiny_blitz.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9fddde75233704ca04a0e1f253c70293d780de80 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/btl_tiny_blitz.cpp @@ -0,0 +1,38 @@ +//===================================================== +// File : main.cpp +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "tiny_blitz_interface.hh" +#include "static/bench_static.hh" +#include "action_matrix_vector_product.hh" +#include "action_matrix_matrix_product.hh" +#include "action_axpy.hh" + +BTL_MAIN; + +int main() +{ + bench_static(); + bench_static(); + bench_static(); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/tiny_blitz_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/tiny_blitz_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..6b26db72df99443d830887b6a4979582eaefdf24 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/blitz/tiny_blitz_interface.hh @@ -0,0 +1,106 @@ +//===================================================== +// File : tiny_blitz_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef TINY_BLITZ_INTERFACE_HH +#define TINY_BLITZ_INTERFACE_HH + +#include "blitz/array.h" +#include "blitz/tiny.h" +#include "blitz/tinymat.h" +#include "blitz/tinyvec.h" +#include + +#include + +BZ_USING_NAMESPACE(blitz) + +template +class tiny_blitz_interface +{ + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef TinyVector gene_vector; + typedef TinyMatrix gene_matrix; + + static inline std::string name() { return "tiny_blitz"; } + + static void free_matrix(gene_matrix & A, int N){} + + static void free_vector(gene_vector & B){} + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + for (int j=0; j +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "static/bench_static.hh" +#include "action_matrix_vector_product.hh" +#include "action_matrix_matrix_product.hh" +#include "action_axpy.hh" +#include "action_lu_solve.hh" +#include "action_ata_product.hh" +#include "action_aat_product.hh" +#include "action_atv_product.hh" +#include "action_cholesky.hh" +#include "action_trisolve.hh" + +BTL_MAIN; + +int main() +{ + + bench_static(); + bench_static(); + bench_static(); + bench_static(); + bench_static(); + bench_static(); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/eigen2_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/eigen2_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..1deabdae2177fe865aade19ae3dd14594033e336 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/eigen2_interface.hh @@ -0,0 +1,168 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef EIGEN2_INTERFACE_HH +#define EIGEN2_INTERFACE_HH +// #include +#include +#include +#include +#include +#include +#include "btl.hh" + +using namespace Eigen; + +template +class eigen2_interface +{ + +public : + + enum {IsFixedSize = (SIZE!=Dynamic)}; + + typedef real real_type; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef Eigen::Matrix gene_matrix; + typedef Eigen::Matrix gene_vector; + + static inline std::string name( void ) + { + #if defined(EIGEN_VECTORIZE_SSE) + if (SIZE==Dynamic) return "eigen2"; else return "tiny_eigen2"; + #elif defined(EIGEN_VECTORIZE_ALTIVEC) || defined(EIGEN_VECTORIZE_VSX) + if (SIZE==Dynamic) return "eigen2"; else return "tiny_eigen2"; + #else + if (SIZE==Dynamic) return "eigen2_novec"; else return "tiny_eigen2_novec"; + #endif + } + + static void free_matrix(gene_matrix & A, int N) {} + + static void free_vector(gene_vector & B) {} + + static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl[0].size(), A_stl.size()); + + for (int j=0; j().solveTriangular(B); + } + + static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int N){ + X = L.template marked().solveTriangular(B); + } + + static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ + C = X.llt().matrixL(); +// C = X; +// Cholesky::computeInPlace(C); +// Cholesky::computeInPlaceBlock(C); + } + + static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ + C = X.lu().matrixLU(); +// C = X.inverse(); + } + + static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){ + C = Tridiagonalization(X).packedMatrix(); + } + + static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int N){ + C = HessenbergDecomposition(X).packedMatrix(); + } + + + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_adv.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_adv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe336892534aa0e1a4106925eaaf74a19a265f09 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_adv.cpp @@ -0,0 +1,44 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen2_interface.hh" +#include "bench.hh" +#include "action_trisolve.hh" +#include "action_trisolve_matrix.hh" +#include "action_cholesky.hh" +#include "action_hessenberg.hh" +#include "action_lu_decomp.hh" +// #include "action_partial_lu.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_linear.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_linear.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c17d16c08c4b3666e99e6012fd4ef08728f12585 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_linear.cpp @@ -0,0 +1,34 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen2_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_matmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_matmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd9dc9cb0bbd2cbb4043ebbbb74205573163d5fa --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_matmat.cpp @@ -0,0 +1,35 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen2_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_vecmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_vecmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b66cd2d9b5088cb62f416e93bd3033b07b5c07f --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen2/main_vecmat.cpp @@ -0,0 +1,36 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen2_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); +// bench > >(MIN_MV,MAX_MV,NB_POINT); +// bench > >(MIN_MV,MAX_MV,NB_POINT); +// bench > >(MIN_MV,MAX_MV,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..00cae23d3a74f3cfe14b2ecf8335145aa185a419 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/CMakeLists.txt @@ -0,0 +1,65 @@ + + +if((NOT EIGEN3_INCLUDE_DIR) AND Eigen_SOURCE_DIR) + # unless EIGEN3_INCLUDE_DIR is defined, let's use current Eigen version + set(EIGEN3_INCLUDE_DIR ${Eigen_SOURCE_DIR}) + set(EIGEN3_FOUND TRUE) +else() + find_package(Eigen3) +endif() + +if (EIGEN3_FOUND) + + include_directories(${EIGEN3_INCLUDE_DIR}) + btl_add_bench(btl_eigen3_linear main_linear.cpp) + btl_add_bench(btl_eigen3_vecmat main_vecmat.cpp) + btl_add_bench(btl_eigen3_matmat main_matmat.cpp) + btl_add_bench(btl_eigen3_adv main_adv.cpp ) + + btl_add_target_property(btl_eigen3_linear COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=eigen3") + btl_add_target_property(btl_eigen3_vecmat COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=eigen3") + btl_add_target_property(btl_eigen3_matmat COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=eigen3") + btl_add_target_property(btl_eigen3_adv COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=eigen3") + + option(BTL_BENCH_NOGCCVEC "also bench Eigen explicit vec without GCC's auto vec" OFF) + if(CMAKE_COMPILER_IS_GNUCXX AND BTL_BENCH_NOGCCVEC) + btl_add_bench(btl_eigen3_nogccvec_linear main_linear.cpp) + btl_add_bench(btl_eigen3_nogccvec_vecmat main_vecmat.cpp) + btl_add_bench(btl_eigen3_nogccvec_matmat main_matmat.cpp) + btl_add_bench(btl_eigen3_nogccvec_adv main_adv.cpp ) + + btl_add_target_property(btl_eigen3_nogccvec_linear COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=eigen3_nogccvec") + btl_add_target_property(btl_eigen3_nogccvec_vecmat COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=eigen3_nogccvec") + btl_add_target_property(btl_eigen3_nogccvec_matmat COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=eigen3_nogccvec") + btl_add_target_property(btl_eigen3_nogccvec_adv COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=eigen3_nogccvec") + endif() + + + if(NOT BTL_NOVEC) + btl_add_bench(btl_eigen3_novec_linear main_linear.cpp OFF) + btl_add_bench(btl_eigen3_novec_vecmat main_vecmat.cpp OFF) + btl_add_bench(btl_eigen3_novec_matmat main_matmat.cpp OFF) + btl_add_bench(btl_eigen3_novec_adv main_adv.cpp OFF) + btl_add_target_property(btl_eigen3_novec_linear COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=eigen3_novec") + btl_add_target_property(btl_eigen3_novec_vecmat COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=eigen3_novec") + btl_add_target_property(btl_eigen3_novec_matmat COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=eigen3_novec") + btl_add_target_property(btl_eigen3_novec_adv COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=eigen3_novec") + +# if(BUILD_btl_eigen3_adv) +# target_link_libraries(btl_eigen3_adv ${MKL_LIBRARIES}) +# endif(BUILD_btl_eigen3_adv) + + endif(NOT BTL_NOVEC) + + btl_add_bench(btl_tiny_eigen3 btl_tiny_eigen3.cpp OFF) + + if(NOT BTL_NOVEC) + btl_add_bench(btl_tiny_eigen3_novec btl_tiny_eigen3.cpp OFF) + btl_add_target_property(btl_tiny_eigen3_novec COMPILE_FLAGS "-DBTL_PREFIX=eigen3_tiny") + + if(BUILD_btl_tiny_eigen3_novec) + btl_add_target_property(btl_tiny_eigen3_novec COMPILE_FLAGS "-DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=eigen3_tiny_novec") + endif(BUILD_btl_tiny_eigen3_novec) + endif(NOT BTL_NOVEC) + +endif (EIGEN3_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/btl_tiny_eigen3.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/btl_tiny_eigen3.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1515be846232c8d0a23b150d870c90df25cc32e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/btl_tiny_eigen3.cpp @@ -0,0 +1,46 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "static/bench_static.hh" +#include "action_matrix_vector_product.hh" +#include "action_matrix_matrix_product.hh" +#include "action_axpy.hh" +#include "action_lu_solve.hh" +#include "action_ata_product.hh" +#include "action_aat_product.hh" +#include "action_atv_product.hh" +#include "action_cholesky.hh" +#include "action_trisolve.hh" + +BTL_MAIN; + +int main() +{ + + bench_static(); + bench_static(); + bench_static(); + bench_static(); + bench_static(); + bench_static(); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/eigen3_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/eigen3_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..b821fd721174d08ecf51feeb3d604248e1c68c1c --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/eigen3_interface.hh @@ -0,0 +1,240 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef EIGEN3_INTERFACE_HH +#define EIGEN3_INTERFACE_HH + +#include +#include +#include "btl.hh" + +using namespace Eigen; + +template +class eigen3_interface +{ + +public : + + enum {IsFixedSize = (SIZE!=Dynamic)}; + + typedef real real_type; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef Eigen::Matrix gene_matrix; + typedef Eigen::Matrix gene_vector; + + static inline std::string name( void ) + { + return EIGEN_MAKESTRING(BTL_PREFIX); + } + + static void free_matrix(gene_matrix & /*A*/, int /*N*/) {} + + static void free_vector(gene_vector & /*B*/) {} + + static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl[0].size(), A_stl.size()); + + for (unsigned int j=0; j().setZero(); + X.template selfadjointView().rankUpdate(A); + } + + static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int /*N*/){ + X.noalias() = A*B; + } + + static inline void symv(const gene_matrix & A, const gene_vector & B, gene_vector & X, int /*N*/){ + X.noalias() = (A.template selfadjointView() * B); +// internal::product_selfadjoint_vector(N,A.data(),N, B.data(), 1, X.data(), 1); + } + + template static void triassign(Dest& dst, const Src& src) + { + typedef typename Dest::Scalar Scalar; + typedef typename internal::packet_traits::type Packet; + const int PacketSize = sizeof(Packet)/sizeof(Scalar); + int size = dst.cols(); + for(int j=0; j(j, index, src); + else + dst.template copyPacket(index, j, src); + } + + // do the non-vectorizable part of the assignment + for (int index = alignedEnd; index(N,A.data(),N, X.data(), 1, Y.data(), 1, -1); + for(int j=0; j(c,s)); + } + + static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int /*N*/){ + X.noalias() = (A.transpose()*B); + } + + static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int /*N*/){ + Y += coef * X; + } + + static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int /*N*/){ + Y = a*X + b*Y; + } + + static EIGEN_DONT_INLINE void copy_matrix(const gene_matrix & source, gene_matrix & cible, int /*N*/){ + cible = source; + } + + static EIGEN_DONT_INLINE void copy_vector(const gene_vector & source, gene_vector & cible, int /*N*/){ + cible = source; + } + + static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector& X, int /*N*/){ + X = L.template triangularView().solve(B); + } + + static inline void trisolve_lower_matrix(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int /*N*/){ + X = L.template triangularView().solve(B); + } + + static inline void trmm(const gene_matrix & L, const gene_matrix& B, gene_matrix& X, int /*N*/){ + X.noalias() = L.template triangularView() * B; + } + + static inline void cholesky(const gene_matrix & X, gene_matrix & C, int /*N*/){ + C = X; + internal::llt_inplace::blocked(C); + //C = X.llt().matrixL(); +// C = X; +// Cholesky::computeInPlace(C); +// Cholesky::computeInPlaceBlock(C); + } + + static inline void lu_decomp(const gene_matrix & X, gene_matrix & C, int /*N*/){ + C = X.fullPivLu().matrixLU(); + } + + static inline void partial_lu_decomp(const gene_matrix & X, gene_matrix & C, int N){ + Matrix piv(N); + DenseIndex nb; + C = X; + internal::partial_lu_inplace(C,piv,nb); +// C = X.partialPivLu().matrixLU(); + } + + static inline void tridiagonalization(const gene_matrix & X, gene_matrix & C, int N){ + typename Tridiagonalization::CoeffVectorType aux(N-1); + C = X; + internal::tridiagonalization_inplace(C, aux); + } + + static inline void hessenberg(const gene_matrix & X, gene_matrix & C, int /*N*/){ + C = HessenbergDecomposition(X).packedMatrix(); + } + + + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_adv.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_adv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95865357e0ec1bea9e0bb2f9928ff5f202d8e68e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_adv.cpp @@ -0,0 +1,44 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "bench.hh" +#include "action_trisolve.hh" +#include "action_trisolve_matrix.hh" +#include "action_cholesky.hh" +#include "action_hessenberg.hh" +#include "action_lu_decomp.hh" +#include "action_partial_lu.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); +// bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + +// bench > >(MIN_LU,MAX_LU,NB_POINT); + bench > >(MIN_LU,MAX_LU,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_linear.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_linear.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e8538b7d0fb746bc14d665709750568f2c755749 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_linear.cpp @@ -0,0 +1,35 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_matmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_matmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..926fa2b0177d92d2db61c00fb39335e1c1e4ec25 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_matmat.cpp @@ -0,0 +1,35 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_vecmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_vecmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0dda444cfad0f0ca774e85197336190fb3e98066 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/eigen3/main_vecmat.cpp @@ -0,0 +1,36 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "eigen3_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc2586243092771e0b1f9919c6a093f522b8d685 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/CMakeLists.txt @@ -0,0 +1,6 @@ + +find_package(GMM) +if (GMM_FOUND) + include_directories(${GMM_INCLUDES}) + btl_add_bench(btl_gmm main.cpp) +endif (GMM_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_LU_solve_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_LU_solve_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..dcb9f567feb098552c8090722769ffafee67d32d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_LU_solve_interface.hh @@ -0,0 +1,192 @@ +//===================================================== +// File : blitz_LU_solve_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:31 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BLITZ_LU_SOLVE_INTERFACE_HH +#define BLITZ_LU_SOLVE_INTERFACE_HH + +#include "blitz/array.h" +#include + +BZ_USING_NAMESPACE(blitz) + +template +class blitz_LU_solve_interface : public blitz_interface +{ + +public : + + typedef typename blitz_interface::gene_matrix gene_matrix; + typedef typename blitz_interface::gene_vector gene_vector; + + typedef blitz::Array Pivot_Vector; + + inline static void new_Pivot_Vector(Pivot_Vector & pivot,int N) + { + + pivot.resize(N); + + } + + inline static void free_Pivot_Vector(Pivot_Vector & pivot) + { + + return; + + } + + + static inline real matrix_vector_product_sliced(const gene_matrix & A, gene_vector B, int row, int col_start, int col_end) + { + + real somme=0.; + + for (int j=col_start ; j=big ) big = abs( LU( i, j ) ) ; + } + if( big==0. ) { + INFOS( "blitz_LU_factor::Singular matrix" ) ; + exit( 0 ) ; + } + ImplicitScaling( i ) = 1./big ; + } + // Loop over columns of Crout's method : + for( int j=0; j=big ) { + dum = ImplicitScaling( i )*abs( theSum ) ; + big = dum ; + index_max = i ; + } + } + // Interchanging rows and the scale factor : + if( j!=index_max ) { + for( int k=0; k=0; i-- ) { + theSum = X( i ) ; + // theSum = B( i ) ; + theSum -= matrix_vector_product_sliced(LU, X, i, i+1, N) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*X( Range( i+1, toEnd ) ) ) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*B( Range( i+1, toEnd ) ) ) ; + // Store a component of the solution vector : + X( i ) = theSum/LU( i, i ) ; + // B( i ) = theSum/LU( i, i ) ; + } + + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..3ea303c1bb5b70f520433f168c299a61d06a8e36 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/gmm_interface.hh @@ -0,0 +1,144 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef GMM_INTERFACE_HH +#define GMM_INTERFACE_HH + +#include +#include + +using namespace gmm; + +template +class gmm_interface { + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef gmm::dense_matrix gene_matrix; + typedef stl_vector gene_vector; + + static inline std::string name( void ) + { + return "gmm"; + } + + static void free_matrix(gene_matrix & A, int N){ + return ; + } + + static void free_vector(gene_vector & B){ + return ; + } + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl[0].size(),A_stl.size()); + + for (int j=0; j ipvt(N); + gmm::lu_factor(R, ipvt); + } + + static inline void hessenberg(const gene_matrix & X, gene_matrix & R, int N){ + gmm::copy(X,R); + gmm::Hessenberg_reduction(R,X,false); + } + + static inline void tridiagonalization(const gene_matrix & X, gene_matrix & R, int N){ + gmm::copy(X,R); + gmm::Householder_tridiagonalization(R,X,false); + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/main.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f0c051eb997cbedcfab817d2bd0316be0328838 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/gmm/main.cpp @@ -0,0 +1,51 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "gmm_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" +#include "action_hessenberg.hh" +#include "action_partial_lu.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + //bench > >(MIN_LU,MAX_LU,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/.kdbgrc.main b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/.kdbgrc.main new file mode 100644 index 0000000000000000000000000000000000000000..fed082f7f58239a598b2f69344e74744a8567200 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/.kdbgrc.main @@ -0,0 +1,12 @@ +[General] +DebuggerCmdStr= +DriverName=GDB +FileVersion=1 +OptionsSelected= +ProgramArgs= +TTYLevel=7 +WorkingDirectory= + +[Memory] +ColumnWidths=80,0 +NumExprs=0 diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..14b47a808c990500baadcef95268a8636b2e3bd1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/CMakeLists.txt @@ -0,0 +1,6 @@ + +find_package(MTL4) +if (MTL4_FOUND) + include_directories(${MTL4_INCLUDE_DIR}) + btl_add_bench(btl_mtl4 main.cpp) +endif (MTL4_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/main.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96fcfb9c9d06ab40afcc39015c580bef54d6adbe --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/main.cpp @@ -0,0 +1,46 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "mtl4_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" +#include "action_cholesky.hh" +// #include "action_lu_decomp.hh" + +BTL_MAIN; + +int main() +{ + + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_LU_solve_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_LU_solve_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..dcb9f567feb098552c8090722769ffafee67d32d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_LU_solve_interface.hh @@ -0,0 +1,192 @@ +//===================================================== +// File : blitz_LU_solve_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:31 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef BLITZ_LU_SOLVE_INTERFACE_HH +#define BLITZ_LU_SOLVE_INTERFACE_HH + +#include "blitz/array.h" +#include + +BZ_USING_NAMESPACE(blitz) + +template +class blitz_LU_solve_interface : public blitz_interface +{ + +public : + + typedef typename blitz_interface::gene_matrix gene_matrix; + typedef typename blitz_interface::gene_vector gene_vector; + + typedef blitz::Array Pivot_Vector; + + inline static void new_Pivot_Vector(Pivot_Vector & pivot,int N) + { + + pivot.resize(N); + + } + + inline static void free_Pivot_Vector(Pivot_Vector & pivot) + { + + return; + + } + + + static inline real matrix_vector_product_sliced(const gene_matrix & A, gene_vector B, int row, int col_start, int col_end) + { + + real somme=0.; + + for (int j=col_start ; j=big ) big = abs( LU( i, j ) ) ; + } + if( big==0. ) { + INFOS( "blitz_LU_factor::Singular matrix" ) ; + exit( 0 ) ; + } + ImplicitScaling( i ) = 1./big ; + } + // Loop over columns of Crout's method : + for( int j=0; j=big ) { + dum = ImplicitScaling( i )*abs( theSum ) ; + big = dum ; + index_max = i ; + } + } + // Interchanging rows and the scale factor : + if( j!=index_max ) { + for( int k=0; k=0; i-- ) { + theSum = X( i ) ; + // theSum = B( i ) ; + theSum -= matrix_vector_product_sliced(LU, X, i, i+1, N) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*X( Range( i+1, toEnd ) ) ) ; + // theSum -= sum( LU( i, Range( i+1, toEnd ) )*B( Range( i+1, toEnd ) ) ) ; + // Store a component of the solution vector : + X( i ) = theSum/LU( i, i ) ; + // B( i ) = theSum/LU( i, i ) ; + } + + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..3795ac61ec02f23dab639d1f4d9814bf67da10cf --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/mtl4/mtl4_interface.hh @@ -0,0 +1,144 @@ +//===================================================== +// Copyright (C) 2008 Gael Guennebaud +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef MTL4_INTERFACE_HH +#define MTL4_INTERFACE_HH + +#include +#include +// #include +#include + +using namespace mtl; + +template +class mtl4_interface { + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef mtl::dense2D > gene_matrix; + typedef mtl::dense_vector gene_vector; + + static inline std::string name() { return "mtl4"; } + + static void free_matrix(gene_matrix & A, int N){ + return ; + } + + static void free_vector(gene_vector & B){ + return ; + } + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.change_dim(A_stl[0].size(), A_stl.size()); + + for (int j=0; j C(N,N); +// C = B; +// X = (A*C); + } + + static inline void transposed_matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int N){ + X = (trans(A)*trans(B)); + } + +// static inline void ata_product(const gene_matrix & A, gene_matrix & X, int N){ +// X = (trans(A)*A); +// } + + static inline void aat_product(const gene_matrix & A, gene_matrix & X, int N){ + X = (A*trans(A)); + } + + static inline void matrix_vector_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + X = (A*B); + } + + static inline void atv_product(gene_matrix & A, gene_vector & B, gene_vector & X, int N){ + X = (trans(A)*B); + } + + static inline void axpy(const real coef, const gene_vector & X, gene_vector & Y, int N){ + Y += coef * X; + } + + static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int N){ + Y = a*X + b*Y; + } + +// static inline void cholesky(const gene_matrix & X, gene_matrix & C, int N){ +// C = X; +// recursive_cholesky(C); +// } + +// static inline void lu_decomp(const gene_matrix & X, gene_matrix & R, int N){ +// R = X; +// std::vector ipvt(N); +// lu_factor(R, ipvt); +// } + + static inline void trisolve_lower(const gene_matrix & L, const gene_vector& B, gene_vector & X, int N){ + X = lower_trisolve(L, B); + } + + static inline void copy_matrix(const gene_matrix & source, gene_matrix & cible, int N){ + cible = source; + } + + static inline void copy_vector(const gene_vector & source, gene_vector & cible, int N){ + cible = source; + } + +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..09d6d8e43ee4de933fd273105b56f42c7f75a701 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/CMakeLists.txt @@ -0,0 +1,44 @@ + + +if((NOT TENSOR_INCLUDE_DIR) AND Eigen_SOURCE_DIR) + # unless TENSOR_INCLUDE_DIR is defined, let's use current Eigen version + set(TENSOR_INCLUDE_DIR ${Eigen_SOURCE_DIR}) + set(TENSOR_FOUND TRUE) +else() + find_package(Tensor) +endif() + +if (TENSOR_FOUND) + + include_directories(${TENSOR_INCLUDE_DIR}) + btl_add_bench(btl_tensor_linear main_linear.cpp) + btl_add_bench(btl_tensor_vecmat main_vecmat.cpp) + btl_add_bench(btl_tensor_matmat main_matmat.cpp) + + btl_add_target_property(btl_tensor_linear COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=tensor") + btl_add_target_property(btl_tensor_vecmat COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=tensor") + btl_add_target_property(btl_tensor_matmat COMPILE_FLAGS "-fno-exceptions -DBTL_PREFIX=tensor") + + option(BTL_BENCH_NOGCCVEC "also bench Eigen explicit vec without GCC's auto vec" OFF) + if(CMAKE_COMPILER_IS_GNUCXX AND BTL_BENCH_NOGCCVEC) + btl_add_bench(btl_tensor_nogccvec_linear main_linear.cpp) + btl_add_bench(btl_tensor_nogccvec_vecmat main_vecmat.cpp) + btl_add_bench(btl_tensor_nogccvec_matmat main_matmat.cpp) + + btl_add_target_property(btl_tensor_nogccvec_linear COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=tensor_nogccvec") + btl_add_target_property(btl_tensor_nogccvec_vecmat COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=tensor_nogccvec") + btl_add_target_property(btl_tensor_nogccvec_matmat COMPILE_FLAGS "-fno-exceptions -fno-tree-vectorize -DBTL_PREFIX=tensor_nogccvec") + endif() + + + if(NOT BTL_NOVEC) + btl_add_bench(btl_tensor_novec_linear main_linear.cpp OFF) + btl_add_bench(btl_tensor_novec_vecmat main_vecmat.cpp OFF) + btl_add_bench(btl_tensor_novec_matmat main_matmat.cpp OFF) + btl_add_target_property(btl_tensor_novec_linear COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=tensor_novec") + btl_add_target_property(btl_tensor_novec_vecmat COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=tensor_novec") + btl_add_target_property(btl_tensor_novec_matmat COMPILE_FLAGS "-fno-exceptions -DEIGEN_DONT_VECTORIZE -DBTL_PREFIX=tensor_novec") + + endif(NOT BTL_NOVEC) + +endif (TENSOR_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_linear.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_linear.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e257f1e72e0b4249a7a2d74869a353f14d912002 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_linear.cpp @@ -0,0 +1,23 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2014 Benoit Steiner +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include "utilities.h" +#include "tensor_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_matmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_matmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..675fcfc6d573edfe806c3b0e211f4e58bbe75bf9 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_matmat.cpp @@ -0,0 +1,21 @@ +//===================================================== +// Copyright (C) 2014 Benoit Steiner +//===================================================== +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +#include "utilities.h" +#include "tensor_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_vecmat.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_vecmat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1af00c81b42fcc2438e5471f397bafa2381244ea --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/main_vecmat.cpp @@ -0,0 +1,21 @@ +//===================================================== +// Copyright (C) 2014 Benoit Steiner +//===================================================== +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +#include "utilities.h" +#include "tensor_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_MV,MAX_MV,NB_POINT); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/tensor_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/tensor_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..97b8e0f0b30a7dcc33d9f973ae865e294400ece0 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tensors/tensor_interface.hh @@ -0,0 +1,105 @@ +//===================================================== +// Copyright (C) 2014 Benoit Steiner +//===================================================== +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. +// +#ifndef TENSOR_INTERFACE_HH +#define TENSOR_INTERFACE_HH + +#include +#include +#include "btl.hh" + +using namespace Eigen; + +template +class tensor_interface +{ +public : + typedef real real_type; + typedef typename Eigen::Tensor::Index Index; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef Eigen::Tensor gene_matrix; + typedef Eigen::Tensor gene_vector; + + + static inline std::string name( void ) + { + return EIGEN_MAKESTRING(BTL_PREFIX); + } + + static void free_matrix(gene_matrix & /*A*/, int /*N*/) {} + + static void free_vector(gene_vector & /*B*/) {} + + static BTL_DONT_INLINE void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(Eigen::array(A_stl[0].size(), A_stl.size())); + + for (unsigned int j=0; j(i,j)) = A_stl[j][i]; + } + } + } + + static BTL_DONT_INLINE void vector_from_stl(gene_vector & B, stl_vector & B_stl){ + B.resize(B_stl.size()); + + for (unsigned int i=0; i(i,j)); + } + } + } + + static inline void matrix_matrix_product(const gene_matrix & A, const gene_matrix & B, gene_matrix & X, int /*N*/){ + typedef typename Eigen::Tensor::DimensionPair DimPair; + const Eigen::array dims(DimPair(1, 0)); + X/*.noalias()*/ = A.contract(B, dims); + } + + static inline void matrix_vector_product(const gene_matrix & A, const gene_vector & B, gene_vector & X, int /*N*/){ + typedef typename Eigen::Tensor::DimensionPair DimPair; + const Eigen::array dims(DimPair(1, 0)); + X/*.noalias()*/ = A.contract(B, dims); + } + + static inline void axpy(real coef, const gene_vector & X, gene_vector & Y, int /*N*/){ + Y += X.constant(coef) * X; + } + + static inline void axpby(real a, const gene_vector & X, real b, gene_vector & Y, int /*N*/){ + Y = X.constant(a)*X + Y.constant(b)*Y; + } + + static EIGEN_DONT_INLINE void copy_matrix(const gene_matrix & source, gene_matrix & cible, int /*N*/){ + cible = source; + } + + static EIGEN_DONT_INLINE void copy_vector(const gene_vector & source, gene_vector & cible, int /*N*/){ + cible = source; + } +}; + +#endif diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..25b565b972360f99d49dc7560bd7989ba1f24682 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/CMakeLists.txt @@ -0,0 +1,6 @@ + +find_package(Tvmet) +if (TVMET_FOUND) + include_directories(${TVMET_INCLUDE_DIR}) + btl_add_bench(btl_tvmet main.cpp OFF) +endif (TVMET_FOUND) diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/main.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..633215c43626fc179fe8d16ca0c1ff8e35f8cf54 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/main.cpp @@ -0,0 +1,40 @@ +//===================================================== +// File : main.cpp +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "tvmet_interface.hh" +#include "static/bench_static.hh" +#include "action_matrix_vector_product.hh" +#include "action_matrix_matrix_product.hh" +#include "action_atv_product.hh" +#include "action_axpy.hh" + +BTL_MAIN; + +int main() +{ + bench_static(); + bench_static(); + bench_static(); + bench_static(); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/tvmet_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/tvmet_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..b441ada2125bb4236e29eea4dc7c6ddfa570f162 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/tvmet/tvmet_interface.hh @@ -0,0 +1,104 @@ +//===================================================== +// File : tvmet_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:30 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef TVMET_INTERFACE_HH +#define TVMET_INTERFACE_HH + +#include +#include +#include + +#include + +using namespace tvmet; + +template +class tvmet_interface{ + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef Vector gene_vector; + typedef Matrix gene_matrix; + + static inline std::string name() { return "tiny_tvmet"; } + + static void free_matrix(gene_matrix & A, int N){} + + static void free_vector(gene_vector & B){} + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + for (int j=0; j +// Copyright (C) EDF R&D, lun sep 30 14:23:27 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#include "utilities.h" +#include "ublas_interface.hh" +#include "bench.hh" +#include "basic_actions.hh" + +BTL_MAIN; + +int main() +{ + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + bench > >(MIN_AXPY,MAX_AXPY,NB_POINT); + + bench > >(MIN_MV,MAX_MV,NB_POINT); + bench > >(MIN_MV,MAX_MV,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); +// bench > >(MIN_MM,MAX_MM,NB_POINT); + + bench > >(MIN_MM,MAX_MM,NB_POINT); + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/ublas/ublas_interface.hh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/ublas/ublas_interface.hh new file mode 100644 index 0000000000000000000000000000000000000000..95cad5195e3cbf2885a69696c550d06c190b4755 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/btl/libs/ublas/ublas_interface.hh @@ -0,0 +1,141 @@ +//===================================================== +// File : ublas_interface.hh +// Author : L. Plagne +// Copyright (C) EDF R&D, lun sep 30 14:23:27 CEST 2002 +//===================================================== +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; either version 2 +// of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#ifndef UBLAS_INTERFACE_HH +#define UBLAS_INTERFACE_HH + +#include +#include +#include +#include + +using namespace boost::numeric; + +template +class ublas_interface{ + +public : + + typedef real real_type ; + + typedef std::vector stl_vector; + typedef std::vector stl_matrix; + + typedef typename boost::numeric::ublas::matrix gene_matrix; + typedef typename boost::numeric::ublas::vector gene_vector; + + static inline std::string name( void ) { return "ublas"; } + + static void free_matrix(gene_matrix & A, int N) {} + + static void free_vector(gene_vector & B) {} + + static inline void matrix_from_stl(gene_matrix & A, stl_matrix & A_stl){ + A.resize(A_stl.size(),A_stl[0].size()); + for (int j=0; j +#include "../Eigen/Core" + +using namespace Eigen; +using namespace std; + +#define DUMP_CPUID(CODE) {\ + int abcd[4]; \ + abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0;\ + EIGEN_CPUID(abcd, CODE, 0); \ + std::cout << "The code " << CODE << " gives " \ + << (int*)(abcd[0]) << " " << (int*)(abcd[1]) << " " \ + << (int*)(abcd[2]) << " " << (int*)(abcd[3]) << " " << std::endl; \ + } + +int main() +{ + cout << "Eigen's L1 = " << internal::queryL1CacheSize() << endl; + cout << "Eigen's L2/L3 = " << internal::queryTopLevelCacheSize() << endl; + int l1, l2, l3; + internal::queryCacheSizes(l1, l2, l3); + cout << "Eigen's L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; + + #ifdef EIGEN_CPUID + + int abcd[4]; + int string[8]; + char* string_char = (char*)(string); + + // vendor ID + EIGEN_CPUID(abcd,0x0,0); + string[0] = abcd[1]; + string[1] = abcd[3]; + string[2] = abcd[2]; + string[3] = 0; + cout << endl; + cout << "vendor id = " << string_char << endl; + cout << endl; + int max_funcs = abcd[0]; + + internal::queryCacheSizes_intel_codes(l1, l2, l3); + cout << "Eigen's intel codes L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; + if(max_funcs>=4) + { + internal::queryCacheSizes_intel_direct(l1, l2, l3); + cout << "Eigen's intel direct L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; + } + internal::queryCacheSizes_amd(l1, l2, l3); + cout << "Eigen's amd L1, L2, L3 = " << l1 << " " << l2 << " " << l3 << endl; + cout << endl; + + // dump Intel direct method + if(max_funcs>=4) + { + l1 = l2 = l3 = 0; + int cache_id = 0; + int cache_type = 0; + do { + abcd[0] = abcd[1] = abcd[2] = abcd[3] = 0; + EIGEN_CPUID(abcd,0x4,cache_id); + cache_type = (abcd[0] & 0x0F) >> 0; + int cache_level = (abcd[0] & 0xE0) >> 5; // A[7:5] + int ways = (abcd[1] & 0xFFC00000) >> 22; // B[31:22] + int partitions = (abcd[1] & 0x003FF000) >> 12; // B[21:12] + int line_size = (abcd[1] & 0x00000FFF) >> 0; // B[11:0] + int sets = (abcd[2]); // C[31:0] + int cache_size = (ways+1) * (partitions+1) * (line_size+1) * (sets+1); + + cout << "cache[" << cache_id << "].type = " << cache_type << "\n"; + cout << "cache[" << cache_id << "].level = " << cache_level << "\n"; + cout << "cache[" << cache_id << "].ways = " << ways << "\n"; + cout << "cache[" << cache_id << "].partitions = " << partitions << "\n"; + cout << "cache[" << cache_id << "].line_size = " << line_size << "\n"; + cout << "cache[" << cache_id << "].sets = " << sets << "\n"; + cout << "cache[" << cache_id << "].size = " << cache_size << "\n"; + + cache_id++; + } while(cache_type>0 && cache_id<16); + } + + // dump everything + std::cout << endl <<"Raw dump:" << endl; + for(int i=0; i +#include "BenchTimer.h" +#include +#include +#include +#include +#include +using namespace Eigen; + +std::map > results; +std::vector labels; +std::vector sizes; + +template +EIGEN_DONT_INLINE +void compute_norm_equation(Solver &solver, const MatrixType &A) { + if(A.rows()!=A.cols()) + solver.compute(A.transpose()*A); + else + solver.compute(A); +} + +template +EIGEN_DONT_INLINE +void compute(Solver &solver, const MatrixType &A) { + solver.compute(A); +} + +template +void bench(int id, int rows, int size = Size) +{ + typedef Matrix Mat; + typedef Matrix MatDyn; + typedef Matrix MatSquare; + Mat A(rows,size); + A.setRandom(); + if(rows==size) + A = A*A.adjoint(); + BenchTimer t_llt, t_ldlt, t_lu, t_fplu, t_qr, t_cpqr, t_cod, t_fpqr, t_jsvd, t_bdcsvd; + + int svd_opt = ComputeThinU|ComputeThinV; + + int tries = 5; + int rep = 1000/size; + if(rep==0) rep = 1; +// rep = rep*rep; + + LLT llt(size); + LDLT ldlt(size); + PartialPivLU lu(size); + FullPivLU fplu(size,size); + HouseholderQR qr(A.rows(),A.cols()); + ColPivHouseholderQR cpqr(A.rows(),A.cols()); + CompleteOrthogonalDecomposition cod(A.rows(),A.cols()); + FullPivHouseholderQR fpqr(A.rows(),A.cols()); + JacobiSVD jsvd(A.rows(),A.cols()); + BDCSVD bdcsvd(A.rows(),A.cols()); + + BENCH(t_llt, tries, rep, compute_norm_equation(llt,A)); + BENCH(t_ldlt, tries, rep, compute_norm_equation(ldlt,A)); + BENCH(t_lu, tries, rep, compute_norm_equation(lu,A)); + if(size<=1000) + BENCH(t_fplu, tries, rep, compute_norm_equation(fplu,A)); + BENCH(t_qr, tries, rep, compute(qr,A)); + BENCH(t_cpqr, tries, rep, compute(cpqr,A)); + BENCH(t_cod, tries, rep, compute(cod,A)); + if(size*rows<=10000000) + BENCH(t_fpqr, tries, rep, compute(fpqr,A)); + if(size<500) // JacobiSVD is really too slow for too large matrices + BENCH(t_jsvd, tries, rep, jsvd.compute(A,svd_opt)); +// if(size*rows<=20000000) + BENCH(t_bdcsvd, tries, rep, bdcsvd.compute(A,svd_opt)); + + results["LLT"][id] = t_llt.best(); + results["LDLT"][id] = t_ldlt.best(); + results["PartialPivLU"][id] = t_lu.best(); + results["FullPivLU"][id] = t_fplu.best(); + results["HouseholderQR"][id] = t_qr.best(); + results["ColPivHouseholderQR"][id] = t_cpqr.best(); + results["CompleteOrthogonalDecomposition"][id] = t_cod.best(); + results["FullPivHouseholderQR"][id] = t_fpqr.best(); + results["JacobiSVD"][id] = t_jsvd.best(); + results["BDCSVD"][id] = t_bdcsvd.best(); +} + + +int main() +{ + labels.push_back("LLT"); + labels.push_back("LDLT"); + labels.push_back("PartialPivLU"); + labels.push_back("FullPivLU"); + labels.push_back("HouseholderQR"); + labels.push_back("ColPivHouseholderQR"); + labels.push_back("CompleteOrthogonalDecomposition"); + labels.push_back("FullPivHouseholderQR"); + labels.push_back("JacobiSVD"); + labels.push_back("BDCSVD"); + + for(int i=0; i(k,sizes[k](0),sizes[k](1)); + } + + cout.width(32); + cout << "solver/size"; + cout << " "; + for(int k=0; k=1e6) cout << "-"; + else cout << r(k); + cout << " "; + } + cout << endl; + } + + // HTML output + cout << "" << endl; + cout << "" << endl; + for(int k=0; k" << sizes[k](0) << "x" << sizes[k](1) << ""; + cout << "" << endl; + for(int i=0; i"; + ArrayXf r = (results[labels[i]]*100000.f).floor()/100.f; + for(int k=0; k=1e6) cout << ""; + else + { + cout << ""; + } + } + cout << "" << endl; + } + cout << "
solver/size
" << labels[i] << "-" << r(k); + if(i>0) + cout << " (x" << numext::round(10.f*results[labels[i]](k)/results["LLT"](k))/10.f << ")"; + if(i<4 && sizes[k](0)!=sizes[k](1)) + cout << " *"; + cout << "
" << endl; + +// cout << "LLT (ms) " << (results["LLT"]*1000.).format(fmt) << "\n"; +// cout << "LDLT (%) " << (results["LDLT"]/results["LLT"]).format(fmt) << "\n"; +// cout << "PartialPivLU (%) " << (results["PartialPivLU"]/results["LLT"]).format(fmt) << "\n"; +// cout << "FullPivLU (%) " << (results["FullPivLU"]/results["LLT"]).format(fmt) << "\n"; +// cout << "HouseholderQR (%) " << (results["HouseholderQR"]/results["LLT"]).format(fmt) << "\n"; +// cout << "ColPivHouseholderQR (%) " << (results["ColPivHouseholderQR"]/results["LLT"]).format(fmt) << "\n"; +// cout << "CompleteOrthogonalDecomposition (%) " << (results["CompleteOrthogonalDecomposition"]/results["LLT"]).format(fmt) << "\n"; +// cout << "FullPivHouseholderQR (%) " << (results["FullPivHouseholderQR"]/results["LLT"]).format(fmt) << "\n"; +// cout << "JacobiSVD (%) " << (results["JacobiSVD"]/results["LLT"]).format(fmt) << "\n"; +// cout << "BDCSVD (%) " << (results["BDCSVD"]/results["LLT"]).format(fmt) << "\n"; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/eig33.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/eig33.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47947a9bed50df66bcc840dbf3fafeb60cae87e8 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/eig33.cpp @@ -0,0 +1,195 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2010 Gael Guennebaud +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + +// The computeRoots function included in this is based on materials +// covered by the following copyright and license: +// +// Geometric Tools, LLC +// Copyright (c) 1998-2010 +// Distributed under the Boost Software License, Version 1.0. +// +// Permission is hereby granted, free of charge, to any person or organization +// obtaining a copy of the software and accompanying documentation covered by +// this license (the "Software") to use, reproduce, display, distribute, +// execute, and transmit the Software, and to prepare derivative works of the +// Software, and to permit third-parties to whom the Software is furnished to +// do so, all subject to the following: +// +// The copyright notices in the Software and this entire statement, including +// the above license grant, this restriction and the following disclaimer, +// must be included in all copies of the Software, in whole or in part, and +// all derivative works of the Software, unless such copies or derivative +// works are solely in the form of machine-executable object code generated by +// a source language processor. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +#include +#include +#include +#include +#include + +using namespace Eigen; +using namespace std; + +template +inline void computeRoots(const Matrix& m, Roots& roots) +{ + typedef typename Matrix::Scalar Scalar; + const Scalar s_inv3 = 1.0/3.0; + const Scalar s_sqrt3 = std::sqrt(Scalar(3.0)); + + // The characteristic equation is x^3 - c2*x^2 + c1*x - c0 = 0. The + // eigenvalues are the roots to this equation, all guaranteed to be + // real-valued, because the matrix is symmetric. + Scalar c0 = m(0,0)*m(1,1)*m(2,2) + Scalar(2)*m(0,1)*m(0,2)*m(1,2) - m(0,0)*m(1,2)*m(1,2) - m(1,1)*m(0,2)*m(0,2) - m(2,2)*m(0,1)*m(0,1); + Scalar c1 = m(0,0)*m(1,1) - m(0,1)*m(0,1) + m(0,0)*m(2,2) - m(0,2)*m(0,2) + m(1,1)*m(2,2) - m(1,2)*m(1,2); + Scalar c2 = m(0,0) + m(1,1) + m(2,2); + + // Construct the parameters used in classifying the roots of the equation + // and in solving the equation for the roots in closed form. + Scalar c2_over_3 = c2*s_inv3; + Scalar a_over_3 = (c1 - c2*c2_over_3)*s_inv3; + if (a_over_3 > Scalar(0)) + a_over_3 = Scalar(0); + + Scalar half_b = Scalar(0.5)*(c0 + c2_over_3*(Scalar(2)*c2_over_3*c2_over_3 - c1)); + + Scalar q = half_b*half_b + a_over_3*a_over_3*a_over_3; + if (q > Scalar(0)) + q = Scalar(0); + + // Compute the eigenvalues by solving for the roots of the polynomial. + Scalar rho = std::sqrt(-a_over_3); + Scalar theta = std::atan2(std::sqrt(-q),half_b)*s_inv3; + Scalar cos_theta = std::cos(theta); + Scalar sin_theta = std::sin(theta); + roots(2) = c2_over_3 + Scalar(2)*rho*cos_theta; + roots(0) = c2_over_3 - rho*(cos_theta + s_sqrt3*sin_theta); + roots(1) = c2_over_3 - rho*(cos_theta - s_sqrt3*sin_theta); +} + +template +void eigen33(const Matrix& mat, Matrix& evecs, Vector& evals) +{ + typedef typename Matrix::Scalar Scalar; + // Scale the matrix so its entries are in [-1,1]. The scaling is applied + // only when at least one matrix entry has magnitude larger than 1. + + Scalar shift = mat.trace()/3; + Matrix scaledMat = mat; + scaledMat.diagonal().array() -= shift; + Scalar scale = scaledMat.cwiseAbs()/*.template triangularView()*/.maxCoeff(); + scale = std::max(scale,Scalar(1)); + scaledMat/=scale; + + // Compute the eigenvalues +// scaledMat.setZero(); + computeRoots(scaledMat,evals); + + // compute the eigen vectors + // **here we assume 3 differents eigenvalues** + + // "optimized version" which appears to be slower with gcc! +// Vector base; +// Scalar alpha, beta; +// base << scaledMat(1,0) * scaledMat(2,1), +// scaledMat(1,0) * scaledMat(2,0), +// -scaledMat(1,0) * scaledMat(1,0); +// for(int k=0; k<2; ++k) +// { +// alpha = scaledMat(0,0) - evals(k); +// beta = scaledMat(1,1) - evals(k); +// evecs.col(k) = (base + Vector(-beta*scaledMat(2,0), -alpha*scaledMat(2,1), alpha*beta)).normalized(); +// } +// evecs.col(2) = evecs.col(0).cross(evecs.col(1)).normalized(); + +// // naive version +// Matrix tmp; +// tmp = scaledMat; +// tmp.diagonal().array() -= evals(0); +// evecs.col(0) = tmp.row(0).cross(tmp.row(1)).normalized(); +// +// tmp = scaledMat; +// tmp.diagonal().array() -= evals(1); +// evecs.col(1) = tmp.row(0).cross(tmp.row(1)).normalized(); +// +// tmp = scaledMat; +// tmp.diagonal().array() -= evals(2); +// evecs.col(2) = tmp.row(0).cross(tmp.row(1)).normalized(); + + // a more stable version: + if((evals(2)-evals(0))<=Eigen::NumTraits::epsilon()) + { + evecs.setIdentity(); + } + else + { + Matrix tmp; + tmp = scaledMat; + tmp.diagonal ().array () -= evals (2); + evecs.col (2) = tmp.row (0).cross (tmp.row (1)).normalized (); + + tmp = scaledMat; + tmp.diagonal ().array () -= evals (1); + evecs.col(1) = tmp.row (0).cross(tmp.row (1)); + Scalar n1 = evecs.col(1).norm(); + if(n1<=Eigen::NumTraits::epsilon()) + evecs.col(1) = evecs.col(2).unitOrthogonal(); + else + evecs.col(1) /= n1; + + // make sure that evecs[1] is orthogonal to evecs[2] + evecs.col(1) = evecs.col(2).cross(evecs.col(1).cross(evecs.col(2))).normalized(); + evecs.col(0) = evecs.col(2).cross(evecs.col(1)); + } + + // Rescale back to the original size. + evals *= scale; + evals.array()+=shift; +} + +int main() +{ + BenchTimer t; + int tries = 10; + int rep = 400000; + typedef Matrix3d Mat; + typedef Vector3d Vec; + Mat A = Mat::Random(3,3); + A = A.adjoint() * A; +// Mat Q = A.householderQr().householderQ(); +// A = Q * Vec(2.2424567,2.2424566,7.454353).asDiagonal() * Q.transpose(); + + SelfAdjointEigenSolver eig(A); + BENCH(t, tries, rep, eig.compute(A)); + std::cout << "Eigen iterative: " << t.best() << "s\n"; + + BENCH(t, tries, rep, eig.computeDirect(A)); + std::cout << "Eigen direct : " << t.best() << "s\n"; + + Mat evecs; + Vec evals; + BENCH(t, tries, rep, eigen33(A,evecs,evals)); + std::cout << "Direct: " << t.best() << "s\n\n"; + +// std::cerr << "Eigenvalue/eigenvector diffs:\n"; +// std::cerr << (evals - eig.eigenvalues()).transpose() << "\n"; +// for(int k=0;k<3;++k) +// if(evecs.col(k).dot(eig.eigenvectors().col(k))<0) +// evecs.col(k) = -evecs.col(k); +// std::cerr << evecs - eig.eigenvectors() << "\n\n"; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/geometry.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/geometry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b187a515f58d1f6f64f79a75614a404376016c02 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/geometry.cpp @@ -0,0 +1,126 @@ + +#include +#include +#include + +using namespace std; +using namespace Eigen; + +#ifndef SCALAR +#define SCALAR float +#endif + +#ifndef SIZE +#define SIZE 8 +#endif + +typedef SCALAR Scalar; +typedef NumTraits::Real RealScalar; +typedef Matrix A; +typedef Matrix B; +typedef Matrix C; +typedef Matrix M; + +template +EIGEN_DONT_INLINE void transform(const Transformation& t, Data& data) +{ + EIGEN_ASM_COMMENT("begin"); + data = t * data; + EIGEN_ASM_COMMENT("end"); +} + +template +EIGEN_DONT_INLINE void transform(const Quaternion& t, Data& data) +{ + EIGEN_ASM_COMMENT("begin quat"); + for(int i=0;i struct ToRotationMatrixWrapper +{ + enum {Dim = T::Dim}; + typedef typename T::Scalar Scalar; + ToRotationMatrixWrapper(const T& o) : object(o) {} + T object; +}; + +template +EIGEN_DONT_INLINE void transform(const ToRotationMatrixWrapper& t, Data& data) +{ + EIGEN_ASM_COMMENT("begin quat via mat"); + data = t.object.toRotationMatrix() * data; + EIGEN_ASM_COMMENT("end quat via mat"); +} + +template +EIGEN_DONT_INLINE void transform(const Transform& t, Data& data) +{ + data = (t * data.colwise().homogeneous()).template block(0,0); +} + +template struct get_dim { enum { Dim = T::Dim }; }; +template +struct get_dim > { enum { Dim = R }; }; + +template +struct bench_impl +{ + static EIGEN_DONT_INLINE void run(const Transformation& t) + { + Matrix::Dim,N> data; + data.setRandom(); + bench_impl::run(t); + BenchTimer timer; + BENCH(timer,10,100000,transform(t,data)); + cout.width(9); + cout << timer.best() << " "; + } +}; + + +template +struct bench_impl +{ + static EIGEN_DONT_INLINE void run(const Transformation&) {} +}; + +template +EIGEN_DONT_INLINE void bench(const std::string& msg, const Transformation& t) +{ + cout << msg << " "; + bench_impl::run(t); + std::cout << "\n"; +} + +int main(int argc, char ** argv) +{ + Matrix mat34; mat34.setRandom(); + Transform iso3(mat34); + Transform aff3(mat34); + Transform caff3(mat34); + Transform proj3(mat34); + Quaternion quat;quat.setIdentity(); + ToRotationMatrixWrapper > quatmat(quat); + Matrix mat33; mat33.setRandom(); + + cout.precision(4); + std::cout + << "N "; + for(int i=0;i +#include +#include +#include +#include "../../BenchTimer.h" +using namespace Eigen; + +#ifndef SCALAR +#error SCALAR must be defined +#endif + +typedef SCALAR Scalar; + +typedef Matrix Mat; + +EIGEN_DONT_INLINE +void gemm(const Mat &A, const Mat &B, Mat &C) +{ + C.noalias() += A * B; +} + +EIGEN_DONT_INLINE +double bench(long m, long n, long k) +{ + Mat A(m,k); + Mat B(k,n); + Mat C(m,n); + A.setRandom(); + B.setRandom(); + C.setZero(); + + BenchTimer t; + + double up = 1e8*4/sizeof(Scalar); + double tm0 = 4, tm1 = 10; + if(NumTraits::IsComplex) + { + up /= 4; + tm0 = 2; + tm1 = 4; + } + + double flops = 2. * m * n * k; + long rep = std::max(1., std::min(100., up/flops) ); + long tries = std::max(tm0, std::min(tm1, up/flops) ); + + BENCH(t, tries, rep, gemm(A,B,C)); + + return 1e-9 * rep * flops / t.best(); +} + +int main(int argc, char **argv) +{ + std::vector results; + + std::ifstream settings("gemm_settings.txt"); + long m, n, k; + while(settings >> m >> n >> k) + { + //std::cerr << " Testing " << m << " " << n << " " << k << std::endl; + results.push_back( bench(m, n, k) ); + } + + std::cout << RowVectorXd::Map(results.data(), results.size()); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/gemm_settings.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/gemm_settings.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c43e1c7d1b33f73d7bc09fbe0e0746d1bd3b55b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/gemm_settings.txt @@ -0,0 +1,15 @@ +8 8 8 +9 9 9 +24 24 24 +239 239 239 +240 240 240 +2400 24 24 +24 2400 24 +24 24 2400 +24 2400 2400 +2400 24 2400 +2400 2400 24 +2400 2400 64 +4800 23 160 +23 4800 160 +2400 2400 2400 diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6dc370155206866fc584ebb94cc646423baa272d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include "../../BenchTimer.h" +using namespace Eigen; + +#ifndef SCALAR +#error SCALAR must be defined +#endif + +typedef SCALAR Scalar; + +template +EIGEN_DONT_INLINE +void lazy_gemm(const MatA &A, const MatB &B, MatC &C) +{ +// escape((void*)A.data()); +// escape((void*)B.data()); + C.noalias() += A.lazyProduct(B); +// escape((void*)C.data()); +} + +template +EIGEN_DONT_INLINE +double bench() +{ + typedef Matrix MatA; + typedef Matrix MatB; + typedef Matrix MatC; + + MatA A(m,k); + MatB B(k,n); + MatC C(m,n); + A.setRandom(); + B.setRandom(); + C.setZero(); + + BenchTimer t; + + double up = 1e7*4/sizeof(Scalar); + double tm0 = 10, tm1 = 20; + + double flops = 2. * m * n * k; + long rep = std::max(10., std::min(10000., up/flops) ); + long tries = std::max(tm0, std::min(tm1, up/flops) ); + + BENCH(t, tries, rep, lazy_gemm(A,B,C)); + + return 1e-9 * rep * flops / t.best(); +} + +template +double bench_t(int t) +{ + if(t) + return bench(); + else + return bench(); +} + +EIGEN_DONT_INLINE +double bench_mnk(int m, int n, int k, int t) +{ + int id = m*10000 + n*100 + k; + switch(id) { + case 10101 : return bench_t< 1, 1, 1>(t); break; + case 20202 : return bench_t< 2, 2, 2>(t); break; + case 30303 : return bench_t< 3, 3, 3>(t); break; + case 40404 : return bench_t< 4, 4, 4>(t); break; + case 50505 : return bench_t< 5, 5, 5>(t); break; + case 60606 : return bench_t< 6, 6, 6>(t); break; + case 70707 : return bench_t< 7, 7, 7>(t); break; + case 80808 : return bench_t< 8, 8, 8>(t); break; + case 90909 : return bench_t< 9, 9, 9>(t); break; + case 101010 : return bench_t<10,10,10>(t); break; + case 111111 : return bench_t<11,11,11>(t); break; + case 121212 : return bench_t<12,12,12>(t); break; + } + return 0; +} + +int main(int argc, char **argv) +{ + std::vector results; + + std::ifstream settings("lazy_gemm_settings.txt"); + long m, n, k, t; + while(settings >> m >> n >> k >> t) + { + //std::cerr << " Testing " << m << " " << n << " " << k << std::endl; + results.push_back( bench_mnk(m, n, k, t) ); + } + + std::cout << RowVectorXd::Map(results.data(), results.size()); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm_settings.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm_settings.txt new file mode 100644 index 0000000000000000000000000000000000000000..407d5d4fad773fd419347c5f3ee313fc3b9e7d7b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/lazy_gemm_settings.txt @@ -0,0 +1,15 @@ +1 1 1 0 +2 2 2 0 +3 3 3 0 +4 4 4 0 +4 4 4 1 +5 5 5 0 +6 6 6 0 +7 7 7 0 +7 7 7 1 +8 8 8 0 +9 9 9 0 +10 10 10 0 +11 11 11 0 +12 12 12 0 +12 12 12 1 diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/make_plot.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/make_plot.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd3214ac915b60a913b21ccd0cceba58f1750e88 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/make_plot.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# base name of the bench +# it reads $1.out +# and generates $1.pdf +WHAT=$1 +bench=$2 + +header="rev " +while read line +do + if [ ! -z '$line' ]; then + header="$header \"$line\"" + fi +done < $bench"_settings.txt" + +echo $header > $WHAT.out.header +cat $WHAT.out >> $WHAT.out.header + + +echo "set title '$WHAT'" > $WHAT.gnuplot +echo "set key autotitle columnhead outside " >> $WHAT.gnuplot +echo "set xtics rotate 1" >> $WHAT.gnuplot + +echo "set term pdf color rounded enhanced fontscale 0.35 size 7in,5in" >> $WHAT.gnuplot +echo set output "'"$WHAT.pdf"'" >> $WHAT.gnuplot + +col=`cat $bench"_settings.txt" | wc -l` +echo "plot for [col=2:$col+1] '$WHAT.out.header' using 0:col:xticlabels(1) with lines" >> $WHAT.gnuplot +echo " " >> $WHAT.gnuplot + +gnuplot -persist < $WHAT.gnuplot + +# generate a png file +# convert -background white -density 120 -rotate 90 -resize 800 +dither -colors 256 -quality 0 $WHAT.ps -background white -flatten .$WHAT.png + +# clean +rm $WHAT.out.header $WHAT.gnuplot \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/run.sh b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d6ee40bca2b7315ceed7624980f183423d9ae76 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/perf_monitoring/gemm/run.sh @@ -0,0 +1,156 @@ +#!/bin/bash + +# ./run.sh gemm +# ./run.sh lazy_gemm + +# Examples of environment variables to be set: +# PREFIX="haswell-fma-" +# CXX_FLAGS="-mfma" + +# Options: +# -up : enforce the recomputation of existing data, and keep best results as a merging strategy +# -s : recompute selected changesets only and keep bests + +bench=$1 + +if echo "$*" | grep '\-up' > /dev/null; then + update=true +else + update=false +fi + +if echo "$*" | grep '\-s' > /dev/null; then + selected=true +else + selected=false +fi + +global_args="$*" + +if [ $selected == true ]; then + echo "Recompute selected changesets only and keep bests" +elif [ $update == true ]; then + echo "(Re-)Compute all changesets and keep bests" +else + echo "Skip previously computed changesets" +fi + + + +if [ ! -d "eigen_src" ]; then + hg clone https://bitbucket.org/eigen/eigen eigen_src +else + cd eigen_src + hg pull -u + cd .. +fi + +if [ ! -z '$CXX' ]; then + CXX=g++ +fi + +function make_backup +{ + if [ -f "$1.out" ]; then + mv "$1.out" "$1.backup" + fi +} + +function merge +{ + count1=`echo $1 | wc -w` + count2=`echo $2 | wc -w` + + if [ $count1 == $count2 ]; then + a=( $1 ); b=( $2 ) + res="" + for (( i=0 ; i<$count1 ; i++ )); do + ai=${a[$i]}; bi=${b[$i]} + tmp=`echo "if ($ai > $bi) $ai else $bi " | bc -l` + res="$res $tmp" + done + echo $res + + else + echo $1 + fi +} + +function test_current +{ + rev=$1 + scalar=$2 + name=$3 + + prev="" + if [ -e "$name.backup" ]; then + prev=`grep $rev "$name.backup" | cut -c 14-` + fi + res=$prev + count_rev=`echo $prev | wc -w` + count_ref=`cat $bench"_settings.txt" | wc -l` + if echo "$global_args" | grep "$rev" > /dev/null; then + rev_found=true + else + rev_found=false + fi +# echo $update et $selected et $rev_found because $rev et "$global_args" +# echo $count_rev et $count_ref + if [ $update == true ] || [ $count_rev != $count_ref ] || ([ $selected == true ] && [ $rev_found == true ]); then + if $CXX -O2 -DNDEBUG -march=native $CXX_FLAGS -I eigen_src $bench.cpp -DSCALAR=$scalar -o $name; then + curr=`./$name` + if [ $count_rev == $count_ref ]; then + echo "merge previous $prev" + echo "with new $curr" + else + echo "got $curr" + fi + res=`merge "$curr" "$prev"` +# echo $res + echo "$rev $res" >> $name.out + else + echo "Compilation failed, skip rev $rev" + fi + else + echo "Skip existing results for $rev / $name" + echo "$rev $res" >> $name.out + fi +} + +make_backup $PREFIX"s"$bench +make_backup $PREFIX"d"$bench +make_backup $PREFIX"c"$bench + +cut -f1 -d"#" < changesets.txt | grep -E '[[:alnum:]]' | while read rev +do + if [ ! -z '$rev' ]; then + echo "Testing rev $rev" + cd eigen_src + hg up -C $rev > /dev/null + actual_rev=`hg identify | cut -f1 -d' '` + cd .. + + test_current $actual_rev float $PREFIX"s"$bench + test_current $actual_rev double $PREFIX"d"$bench + test_current $actual_rev "std::complex" $PREFIX"c"$bench + fi + +done + +echo "Float:" +cat $PREFIX"s""$bench.out" +echo " " + +echo "Double:" +cat $PREFIX"d""$bench.out" +echo "" + +echo "Complex:" +cat $PREFIX"c""$bench.out" +echo "" + +./make_plot.sh $PREFIX"s"$bench $bench +./make_plot.sh $PREFIX"d"$bench $bench +./make_plot.sh $PREFIX"c"$bench $bench + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/product_threshold.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/product_threshold.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd6d15a07105d5f596ed6c01900a7d2ac900ac3d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/product_threshold.cpp @@ -0,0 +1,143 @@ + +#include +#include +#include + +using namespace Eigen; +using namespace std; + +#define END 9 + +template struct map_size { enum { ret = S }; }; +template<> struct map_size<10> { enum { ret = 20 }; }; +template<> struct map_size<11> { enum { ret = 50 }; }; +template<> struct map_size<12> { enum { ret = 100 }; }; +template<> struct map_size<13> { enum { ret = 300 }; }; + +template struct alt_prod +{ + enum { + ret = M==1 && N==1 ? InnerProduct + : K==1 ? OuterProduct + : M==1 ? GemvProduct + : N==1 ? GemvProduct + : GemmProduct + }; +}; + +void print_mode(int mode) +{ + if(mode==InnerProduct) std::cout << "i"; + if(mode==OuterProduct) std::cout << "o"; + if(mode==CoeffBasedProductMode) std::cout << "c"; + if(mode==LazyCoeffBasedProductMode) std::cout << "l"; + if(mode==GemvProduct) std::cout << "v"; + if(mode==GemmProduct) std::cout << "m"; +} + +template +EIGEN_DONT_INLINE void prod(const Lhs& a, const Rhs& b, Res& c) +{ + c.noalias() += typename ProductReturnType::Type(a,b); +} + +template +EIGEN_DONT_INLINE void bench_prod() +{ + typedef Matrix Lhs; Lhs a; a.setRandom(); + typedef Matrix Rhs; Rhs b; b.setRandom(); + typedef Matrix Res; Res c; c.setRandom(); + + BenchTimer t; + double n = 2.*double(M)*double(N)*double(K); + int rep = 100000./n; + rep /= 2; + if(rep<1) rep = 1; + do { + rep *= 2; + t.reset(); + BENCH(t,1,rep,prod(a,b,c)); + } while(t.best()<0.1); + + t.reset(); + BENCH(t,5,rep,prod(a,b,c)); + + print_mode(Mode); + std::cout << int(1e-6*n*rep/t.best()) << "\t"; +} + +template struct print_n; +template struct loop_on_m; +template struct loop_on_n; + +template +struct loop_on_k +{ + static void run() + { + std::cout << "K=" << K << "\t"; + print_n::run(); + std::cout << "\n"; + + loop_on_m::run(); + std::cout << "\n\n"; + + loop_on_k::run(); + } +}; + +template +struct loop_on_k { static void run(){} }; + + +template +struct loop_on_m +{ + static void run() + { + std::cout << M << "f\t"; + loop_on_n::run(); + std::cout << "\n"; + + std::cout << M << "f\t"; + loop_on_n::run(); + std::cout << "\n"; + + loop_on_m::run(); + } +}; + +template +struct loop_on_m { static void run(){} }; + +template +struct loop_on_n +{ + static void run() + { + bench_prod::ret : Mode>(); + + loop_on_n::run(); + } +}; + +template +struct loop_on_n { static void run(){} }; + +template struct print_n +{ + static void run() + { + std::cout << map_size::ret << "\t"; + print_n::run(); + } +}; + +template<> struct print_n { static void run(){} }; + +int main() +{ + loop_on_k<1,1,1>::run(); + + return 0; +} diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quat_slerp.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quat_slerp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bffb3bf11bc842616c976477ab18f38dd4e60fe6 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quat_slerp.cpp @@ -0,0 +1,247 @@ + +#include +#include +#include +using namespace Eigen; +using namespace std; + + + +template +EIGEN_DONT_INLINE Q nlerp(const Q& a, const Q& b, typename Q::Scalar t) +{ + return Q((a.coeffs() * (1.0-t) + b.coeffs() * t).normalized()); +} + +template +EIGEN_DONT_INLINE Q slerp_eigen(const Q& a, const Q& b, typename Q::Scalar t) +{ + return a.slerp(t,b); +} + +template +EIGEN_DONT_INLINE Q slerp_legacy(const Q& a, const Q& b, typename Q::Scalar t) +{ + typedef typename Q::Scalar Scalar; + static const Scalar one = Scalar(1) - dummy_precision(); + Scalar d = a.dot(b); + Scalar absD = internal::abs(d); + if (absD>=one) + return a; + + // theta is the angle between the 2 quaternions + Scalar theta = std::acos(absD); + Scalar sinTheta = internal::sin(theta); + + Scalar scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta; + Scalar scale1 = internal::sin( ( t * theta) ) / sinTheta; + if (d<0) + scale1 = -scale1; + + return Q(scale0 * a.coeffs() + scale1 * b.coeffs()); +} + +template +EIGEN_DONT_INLINE Q slerp_legacy_nlerp(const Q& a, const Q& b, typename Q::Scalar t) +{ + typedef typename Q::Scalar Scalar; + static const Scalar one = Scalar(1) - epsilon(); + Scalar d = a.dot(b); + Scalar absD = internal::abs(d); + + Scalar scale0; + Scalar scale1; + + if (absD>=one) + { + scale0 = Scalar(1) - t; + scale1 = t; + } + else + { + // theta is the angle between the 2 quaternions + Scalar theta = std::acos(absD); + Scalar sinTheta = internal::sin(theta); + + scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta; + scale1 = internal::sin( ( t * theta) ) / sinTheta; + if (d<0) + scale1 = -scale1; + } + + return Q(scale0 * a.coeffs() + scale1 * b.coeffs()); +} + +template +inline T sin_over_x(T x) +{ + if (T(1) + x*x == T(1)) + return T(1); + else + return std::sin(x)/x; +} + +template +EIGEN_DONT_INLINE Q slerp_rw(const Q& a, const Q& b, typename Q::Scalar t) +{ + typedef typename Q::Scalar Scalar; + + Scalar d = a.dot(b); + Scalar theta; + if (d<0.0) + theta = /*M_PI -*/ Scalar(2)*std::asin( (a.coeffs()+b.coeffs()).norm()/2 ); + else + theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 ); + + // theta is the angle between the 2 quaternions +// Scalar theta = std::acos(absD); + Scalar sinOverTheta = sin_over_x(theta); + + Scalar scale0 = (Scalar(1)-t)*sin_over_x( ( Scalar(1) - t ) * theta) / sinOverTheta; + Scalar scale1 = t * sin_over_x( ( t * theta) ) / sinOverTheta; + if (d<0) + scale1 = -scale1; + + return Quaternion(scale0 * a.coeffs() + scale1 * b.coeffs()); +} + +template +EIGEN_DONT_INLINE Q slerp_gael(const Q& a, const Q& b, typename Q::Scalar t) +{ + typedef typename Q::Scalar Scalar; + + Scalar d = a.dot(b); + Scalar theta; +// theta = Scalar(2) * atan2((a.coeffs()-b.coeffs()).norm(),(a.coeffs()+b.coeffs()).norm()); +// if (d<0.0) +// theta = M_PI-theta; + + if (d<0.0) + theta = /*M_PI -*/ Scalar(2)*std::asin( (-a.coeffs()-b.coeffs()).norm()/2 ); + else + theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 ); + + + Scalar scale0; + Scalar scale1; + if(theta*theta-Scalar(6)==-Scalar(6)) + { + scale0 = Scalar(1) - t; + scale1 = t; + } + else + { + Scalar sinTheta = std::sin(theta); + scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta; + scale1 = internal::sin( ( t * theta) ) / sinTheta; + if (d<0) + scale1 = -scale1; + } + + return Quaternion(scale0 * a.coeffs() + scale1 * b.coeffs()); +} + +int main() +{ + typedef double RefScalar; + typedef float TestScalar; + + typedef Quaternion Qd; + typedef Quaternion Qf; + + unsigned int g_seed = (unsigned int) time(NULL); + std::cout << g_seed << "\n"; +// g_seed = 1259932496; + srand(g_seed); + + Matrix maxerr(7); + maxerr.setZero(); + + Matrix avgerr(7); + avgerr.setZero(); + + cout << "double=>float=>double nlerp eigen legacy(snap) legacy(nlerp) rightway gael's criteria\n"; + + int rep = 100; + int iters = 40; + for (int w=0; w()); + Qd br(b.cast()); + Qd cr; + + + + cout.precision(8); + cout << std::scientific; + for (int i=0; i(); + c[0] = nlerp(a,b,t); + c[1] = slerp_eigen(a,b,t); + c[2] = slerp_legacy(a,b,t); + c[3] = slerp_legacy_nlerp(a,b,t); + c[4] = slerp_rw(a,b,t); + c[5] = slerp_gael(a,b,t); + + VectorXd err(7); + err[0] = (cr.coeffs()-refc.cast().coeffs()).norm(); +// std::cout << err[0] << " "; + for (int k=0; k<6; ++k) + { + err[k+1] = (c[k].coeffs()-refc.coeffs()).norm(); +// std::cout << err[k+1] << " "; + } + maxerr = maxerr.cwise().max(err); + avgerr += err; +// std::cout << "\n"; + b = cr.cast(); + br = cr; + } +// std::cout << "\n"; + } + avgerr /= RefScalar(rep*iters); + cout << "\n\nAccuracy:\n" + << " max: " << maxerr.transpose() << "\n"; + cout << " avg: " << avgerr.transpose() << "\n"; + + // perf bench + Quaternionf a,b; + a.coeffs().setRandom(); + a.normalize(); + b.coeffs().setRandom(); + b.normalize(); + //b = a; + float s = 0.65; + + #define BENCH(FUNC) {\ + BenchTimer t; \ + for(int k=0; k<2; ++k) {\ + t.start(); \ + for(int i=0; i<1000000; ++i) \ + FUNC(a,b,s); \ + t.stop(); \ + } \ + cout << " " << #FUNC << " => \t " << t.value() << "s\n"; \ + } + + cout << "\nSpeed:\n" << std::fixed; + BENCH(nlerp); + BENCH(slerp_eigen); + BENCH(slerp_legacy); + BENCH(slerp_legacy_nlerp); + BENCH(slerp_rw); + BENCH(slerp_gael); +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quatmul.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quatmul.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d9d7922cf72ad0c56fa990cfa63c329756a07cd --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/quatmul.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +#include + +using namespace Eigen; + +template +EIGEN_DONT_INLINE void quatmul_default(const Quat& a, const Quat& b, Quat& c) +{ + c = a * b; +} + +template +EIGEN_DONT_INLINE void quatmul_novec(const Quat& a, const Quat& b, Quat& c) +{ + c = internal::quat_product<0, Quat, Quat, typename Quat::Scalar, Aligned>::run(a,b); +} + +template void bench(const std::string& label) +{ + int tries = 10; + int rep = 1000000; + BenchTimer t; + + Quat a(4, 1, 2, 3); + Quat b(2, 3, 4, 5); + Quat c; + + std::cout.precision(3); + + BENCH(t, tries, rep, quatmul_default(a,b,c)); + std::cout << label << " default " << 1e3*t.best(CPU_TIMER) << "ms \t" << 1e-6*double(rep)/(t.best(CPU_TIMER)) << " M mul/s\n"; + + BENCH(t, tries, rep, quatmul_novec(a,b,c)); + std::cout << label << " novec " << 1e3*t.best(CPU_TIMER) << "ms \t" << 1e-6*double(rep)/(t.best(CPU_TIMER)) << " M mul/s\n"; +} + +int main() +{ + bench("float "); + bench("double"); + + return 0; + +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_cholesky.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_cholesky.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecb2267866383b895759c8d8af173512703d9d4d --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_cholesky.cpp @@ -0,0 +1,216 @@ +// #define EIGEN_TAUCS_SUPPORT +// #define EIGEN_CHOLMOD_SUPPORT +#include +#include + +// g++ -DSIZE=10000 -DDENSITY=0.001 sparse_cholesky.cpp -I.. -DDENSEMATRI -O3 -g0 -DNDEBUG -DNBTRIES=1 -I /home/gael/Coding/LinearAlgebra/taucs_full/src/ -I/home/gael/Coding/LinearAlgebra/taucs_full/build/linux/ -L/home/gael/Coding/LinearAlgebra/taucs_full/lib/linux/ -ltaucs /home/gael/Coding/LinearAlgebra/GotoBLAS/libgoto.a -lpthread -I /home/gael/Coding/LinearAlgebra/SuiteSparse/CHOLMOD/Include/ $CHOLLIB -I /home/gael/Coding/LinearAlgebra/SuiteSparse/UFconfig/ /home/gael/Coding/LinearAlgebra/SuiteSparse/CCOLAMD/Lib/libccolamd.a /home/gael/Coding/LinearAlgebra/SuiteSparse/CHOLMOD/Lib/libcholmod.a -lmetis /home/gael/Coding/LinearAlgebra/SuiteSparse/AMD/Lib/libamd.a /home/gael/Coding/LinearAlgebra/SuiteSparse/CAMD/Lib/libcamd.a /home/gael/Coding/LinearAlgebra/SuiteSparse/CCOLAMD/Lib/libccolamd.a /home/gael/Coding/LinearAlgebra/SuiteSparse/COLAMD/Lib/libcolamd.a -llapack && ./a.out + +#define NOGMM +#define NOMTL + +#ifndef SIZE +#define SIZE 10 +#endif + +#ifndef DENSITY +#define DENSITY 0.01 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include "BenchSparseUtil.h" + +#ifndef MINDENSITY +#define MINDENSITY 0.0004 +#endif + +#ifndef NBTRIES +#define NBTRIES 10 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j EigenSparseTriMatrix; +typedef SparseMatrix EigenSparseSelfAdjointMatrix; + +void fillSpdMatrix(float density, int rows, int cols, EigenSparseSelfAdjointMatrix& dst) +{ + dst.startFill(rows*cols*density); + for(int j = 0; j < cols; j++) + { + dst.fill(j,j) = internal::random(10,20); + for(int i = j+1; i < rows; i++) + { + Scalar v = (internal::random(0,1) < density) ? internal::random() : 0; + if (v!=0) + dst.fill(i,j) = v; + } + + } + dst.endFill(); +} + +#include + +template +void doEigen(const char* name, const EigenSparseSelfAdjointMatrix& sm1, int flags = 0) +{ + std::cout << name << "..." << std::flush; + BenchTimer timer; + timer.start(); + SparseLLT chol(sm1, flags); + timer.stop(); + std::cout << ":\t" << timer.value() << endl; + + std::cout << " nnz: " << sm1.nonZeros() << " => " << chol.matrixL().nonZeros() << "\n"; +// std::cout << "sparse\n" << chol.matrixL() << "%\n"; +} + +int main(int argc, char *argv[]) +{ + int rows = SIZE; + int cols = SIZE; + float density = DENSITY; + BenchTimer timer; + + VectorXf b = VectorXf::Random(cols); + VectorXf x = VectorXf::Random(cols); + + bool densedone = false; + + //for (float density = DENSITY; density>=MINDENSITY; density*=0.5) +// float density = 0.5; + { + EigenSparseSelfAdjointMatrix sm1(rows, cols); + std::cout << "Generate sparse matrix (might take a while)...\n"; + fillSpdMatrix(density, rows, cols, sm1); + std::cout << "DONE\n\n"; + + // dense matrices + #ifdef DENSEMATRIX + if (!densedone) + { + densedone = true; + std::cout << "Eigen Dense\t" << density*100 << "%\n"; + DenseMatrix m1(rows,cols); + eiToDense(sm1, m1); + m1 = (m1 + m1.transpose()).eval(); + m1.diagonal() *= 0.5; + +// BENCH(LLT chol(m1);) +// std::cout << "dense:\t" << timer.value() << endl; + + BenchTimer timer; + timer.start(); + LLT chol(m1); + timer.stop(); + std::cout << "dense:\t" << timer.value() << endl; + int count = 0; + for (int j=0; j("Eigen/Sparse", sm1, Eigen::IncompleteFactorization); + + #ifdef EIGEN_CHOLMOD_SUPPORT + doEigen("Eigen/Cholmod", sm1, Eigen::IncompleteFactorization); + #endif + + #ifdef EIGEN_TAUCS_SUPPORT + doEigen("Eigen/Taucs", sm1, Eigen::IncompleteFactorization); + #endif + + #if 0 + // TAUCS + { + taucs_ccs_matrix A = sm1.asTaucsMatrix(); + + //BENCH(taucs_ccs_matrix* chol = taucs_ccs_factor_llt(&A, 0, 0);) +// BENCH(taucs_supernodal_factor_to_ccs(taucs_ccs_factor_llt_ll(&A));) +// std::cout << "taucs:\t" << timer.value() << endl; + + taucs_ccs_matrix* chol = taucs_ccs_factor_llt(&A, 0, 0); + + for (int j=0; jcolptr[j]; icolptr[j+1]; ++i) + std::cout << chol->values.d[i] << " "; + } + } + + // CHOLMOD + #ifdef EIGEN_CHOLMOD_SUPPORT + { + cholmod_common c; + cholmod_start (&c); + cholmod_sparse A; + cholmod_factor *L; + + A = sm1.asCholmodMatrix(); + BenchTimer timer; +// timer.reset(); + timer.start(); + std::vector perm(cols); +// std::vector set(ncols); + for (int i=0; icolptr[j]; icolptr[j+1]; ++i) +// std::cout << chol->values.s[i] << " "; +// } + } + #endif + + #endif + + + + } + + + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_dense_product.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_dense_product.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f3f5194065679dc4b395bab5f7a50c9b7998359a --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_dense_product.cpp @@ -0,0 +1,187 @@ + +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.005 -DSIZE=10000 && ./a.out +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.05 -DSIZE=2000 && ./a.out +// -DNOGMM -DNOMTL -DCSPARSE +// -I /home/gael/Coding/LinearAlgebra/CSparse/Include/ /home/gael/Coding/LinearAlgebra/CSparse/Lib/libcsparse.a +#ifndef SIZE +#define SIZE 650000 +#endif + +#ifndef DENSITY +#define DENSITY 0.01 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include "BenchSparseUtil.h" + +#ifndef MINDENSITY +#define MINDENSITY 0.0004 +#endif + +#ifndef NBTRIES +#define NBTRIES 10 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j=MINDENSITY; density*=0.5) + { + //fillMatrix(density, rows, cols, sm1); + fillMatrix2(7, rows, cols, sm1); + + // dense matrices + #ifdef DENSEMATRIX + { + std::cout << "Eigen Dense\t" << density*100 << "%\n"; + DenseMatrix m1(rows,cols); + eiToDense(sm1, m1); + + timer.reset(); + timer.start(); + for (int k=0; k m1(sm1); +// std::cout << "Eigen dyn-sparse\t" << m1.nonZeros()/float(m1.rows()*m1.cols())*100 << "%\n"; +// +// BENCH(for (int k=0; k gmmV1(cols), gmmV2(cols); + Map >(&gmmV1[0], cols) = v1; + Map >(&gmmV2[0], cols) = v2; + + BENCH( asm("#myx"); gmm::mult(m1, gmmV1, gmmV2); asm("#myy"); ) + std::cout << " a * v:\t" << timer.value() << endl; + + BENCH( gmm::mult(gmm::transposed(m1), gmmV1, gmmV2); ) + std::cout << " a' * v:\t" << timer.value() << endl; + } + #endif + + #ifndef NOUBLAS + { + std::cout << "ublas sparse\t" << density*100 << "%\n"; + UBlasSparse m1(rows,cols); + eiToUblas(sm1, m1); + + boost::numeric::ublas::vector uv1, uv2; + eiToUblasVec(v1,uv1); + eiToUblasVec(v2,uv2); + +// std::vector gmmV1(cols), gmmV2(cols); +// Map >(&gmmV1[0], cols) = v1; +// Map >(&gmmV2[0], cols) = v2; + + BENCH( uv2 = boost::numeric::ublas::prod(m1, uv1); ) + std::cout << " a * v:\t" << timer.value() << endl; + +// BENCH( boost::ublas::prod(gmm::transposed(m1), gmmV1, gmmV2); ) +// std::cout << " a' * v:\t" << timer.value() << endl; + } + #endif + + // MTL4 + #ifndef NOMTL + { + std::cout << "MTL4\t" << density*100 << "%\n"; + MtlSparse m1(rows,cols); + eiToMtl(sm1, m1); + mtl::dense_vector mtlV1(cols, 1.0); + mtl::dense_vector mtlV2(cols, 1.0); + + timer.reset(); + timer.start(); + for (int k=0; k + +#define NOGMM +#define NOMTL + +#ifndef SIZE +#define SIZE 10 +#endif + +#ifndef DENSITY +#define DENSITY 0.01 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include "BenchSparseUtil.h" + +#ifndef MINDENSITY +#define MINDENSITY 0.0004 +#endif + +#ifndef NBTRIES +#define NBTRIES 10 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j VectorX; + +#include + +template +void doEigen(const char* name, const EigenSparseMatrix& sm1, const VectorX& b, VectorX& x, int flags = 0) +{ + std::cout << name << "..." << std::flush; + BenchTimer timer; timer.start(); + SparseLU lu(sm1, flags); + timer.stop(); + if (lu.succeeded()) + std::cout << ":\t" << timer.value() << endl; + else + { + std::cout << ":\t FAILED" << endl; + return; + } + + bool ok; + timer.reset(); timer.start(); + ok = lu.solve(b,&x); + timer.stop(); + if (ok) + std::cout << " solve:\t" << timer.value() << endl; + else + std::cout << " solve:\t" << " FAILED" << endl; + + //std::cout << x.transpose() << "\n"; +} + +int main(int argc, char *argv[]) +{ + int rows = SIZE; + int cols = SIZE; + float density = DENSITY; + BenchTimer timer; + + VectorX b = VectorX::Random(cols); + VectorX x = VectorX::Random(cols); + + bool densedone = false; + + //for (float density = DENSITY; density>=MINDENSITY; density*=0.5) +// float density = 0.5; + { + EigenSparseMatrix sm1(rows, cols); + fillMatrix(density, rows, cols, sm1); + + // dense matrices + #ifdef DENSEMATRIX + if (!densedone) + { + densedone = true; + std::cout << "Eigen Dense\t" << density*100 << "%\n"; + DenseMatrix m1(rows,cols); + eiToDense(sm1, m1); + + BenchTimer timer; + timer.start(); + FullPivLU lu(m1); + timer.stop(); + std::cout << "Eigen/dense:\t" << timer.value() << endl; + + timer.reset(); + timer.start(); + lu.solve(b,&x); + timer.stop(); + std::cout << " solve:\t" << timer.value() << endl; +// std::cout << b.transpose() << "\n"; +// std::cout << x.transpose() << "\n"; + } + #endif + + #ifdef EIGEN_UMFPACK_SUPPORT + x.setZero(); + doEigen("Eigen/UmfPack (auto)", sm1, b, x, 0); + #endif + + #ifdef EIGEN_SUPERLU_SUPPORT + x.setZero(); + doEigen("Eigen/SuperLU (nat)", sm1, b, x, Eigen::NaturalOrdering); +// doEigen("Eigen/SuperLU (MD AT+A)", sm1, b, x, Eigen::MinimumDegree_AT_PLUS_A); +// doEigen("Eigen/SuperLU (MD ATA)", sm1, b, x, Eigen::MinimumDegree_ATA); + doEigen("Eigen/SuperLU (COLAMD)", sm1, b, x, Eigen::ColApproxMinimumDegree); + #endif + + } + + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_product.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_product.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2fc44f0d47e5fbce2a4692ddcfdfb4deb4fa521 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_product.cpp @@ -0,0 +1,323 @@ + +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.005 -DSIZE=10000 && ./a.out +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.05 -DSIZE=2000 && ./a.out +// -DNOGMM -DNOMTL -DCSPARSE +// -I /home/gael/Coding/LinearAlgebra/CSparse/Include/ /home/gael/Coding/LinearAlgebra/CSparse/Lib/libcsparse.a + +#include + +#ifndef SIZE +#define SIZE 1000000 +#endif + +#ifndef NNZPERCOL +#define NNZPERCOL 6 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include +#include "BenchTimer.h" +#include "BenchUtil.h" +#include "BenchSparseUtil.h" + +#ifndef NBTRIES +#define NBTRIES 1 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j +// void mkl_multiply(const Lhs& lhs, const Rhs& rhs, Res& res) +// { +// char n = 'N'; +// float alpha = 1; +// char matdescra[6]; +// matdescra[0] = 'G'; +// matdescra[1] = 0; +// matdescra[2] = 0; +// matdescra[3] = 'C'; +// mkl_scscmm(&n, lhs.rows(), rhs.cols(), lhs.cols(), &alpha, matdescra, +// lhs._valuePtr(), lhs._innerIndexPtr(), lhs.outerIndexPtr(), +// pntre, b, &ldb, &beta, c, &ldc); +// // mkl_somatcopy('C', 'T', lhs.rows(), lhs.cols(), 1, +// // lhs._valuePtr(), lhs.rows(), DST, dst_stride); +// } +// +// #endif + + +#ifdef CSPARSE +cs* cs_sorted_multiply(const cs* a, const cs* b) +{ +// return cs_multiply(a,b); + + cs* A = cs_transpose(a, 1); + cs* B = cs_transpose(b, 1); + cs* D = cs_multiply(B,A); /* D = B'*A' */ + cs_spfree (A) ; + cs_spfree (B) ; + cs_dropzeros (D) ; /* drop zeros from D */ + cs* C = cs_transpose (D, 1) ; /* C = D', so that C is sorted */ + cs_spfree (D) ; + return C; + +// cs* A = cs_transpose(a, 1); +// cs* C = cs_transpose(A, 1); +// return C; +} + +cs* cs_sorted_multiply2(const cs* a, const cs* b) +{ + cs* D = cs_multiply(a,b); + cs* E = cs_transpose(D,1); + cs_spfree(D); + cs* C = cs_transpose(E,1); + cs_spfree(E); + return C; +} +#endif + +void bench_sort(); + +int main(int argc, char *argv[]) +{ +// bench_sort(); + + int rows = SIZE; + int cols = SIZE; + float density = DENSITY; + + EigenSparseMatrix sm1(rows,cols), sm2(rows,cols), sm3(rows,cols), sm4(rows,cols); + + BenchTimer timer; + for (int nnzPerCol = NNZPERCOL; nnzPerCol>1; nnzPerCol/=1.1) + { + sm1.setZero(); + sm2.setZero(); + fillMatrix2(nnzPerCol, rows, cols, sm1); + fillMatrix2(nnzPerCol, rows, cols, sm2); +// std::cerr << "filling OK\n"; + + // dense matrices + #ifdef DENSEMATRIX + { + std::cout << "Eigen Dense\t" << nnzPerCol << "%\n"; + DenseMatrix m1(rows,cols), m2(rows,cols), m3(rows,cols); + eiToDense(sm1, m1); + eiToDense(sm2, m2); + + timer.reset(); + timer.start(); + for (int k=0; k m1(sm1), m2(sm2), m3(sm3); + std::cout << "Eigen dyn-sparse\t" << m1.nonZeros()/(float(m1.rows())*float(m1.cols()))*100 << "% * " + << m2.nonZeros()/(float(m2.rows())*float(m2.cols()))*100 << "%\n"; + +// timer.reset(); +// timer.start(); + BENCH(for (int k=0; k +#include +#include +#include + +#ifndef SIZE +#define SIZE 10000 +#endif + +#ifndef DENSITY +#define DENSITY 0.01 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include "BenchSparseUtil.h" + +#ifndef MINDENSITY +#define MINDENSITY 0.0004 +#endif + +#ifndef NBTRIES +#define NBTRIES 10 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j +void dostuff(const char* name, EigenSparseMatrix& sm1) +{ + int rows = sm1.rows(); + int cols = sm1.cols(); + sm1.setZero(); + BenchTimer t; + SetterType* set1 = new SetterType(sm1); + t.reset(); t.start(); + for (int k=0; k(0,rows-1),internal::random(0,cols-1)) += 1; + t.stop(); + std::cout << "std::map => \t" << t.value()-rtime + << " nnz=" << set1->nonZeros() << std::flush; + + // getchar(); + + t.reset(); t.start(); delete set1; t.stop(); + std::cout << " back: \t" << t.value() << "\n"; +} + +int main(int argc, char *argv[]) +{ + int rows = SIZE; + int cols = SIZE; + float density = DENSITY; + + EigenSparseMatrix sm1(rows,cols), sm2(rows,cols); + + + nentries = rows*cols*density; + std::cout << "n = " << nentries << "\n"; + int dummy; + BenchTimer t; + + t.reset(); t.start(); + for (int k=0; k(0,rows-1) + internal::random(0,cols-1); + t.stop(); + rtime = t.value(); + std::cout << "rtime = " << rtime << " (" << dummy << ")\n\n"; + const int Bits = 6; + for (;;) + { + dostuff >("std::map ", sm1); + dostuff >("gnu::hash_map", sm1); + dostuff >("google::dense", sm1); + dostuff >("google::sparse", sm1); + +// { +// RandomSetter set1(sm1); +// t.reset(); t.start(); +// for (int k=0; k(0,rows-1),internal::random(0,cols-1)) += 1; +// t.stop(); +// std::cout << "gnu::hash_map => \t" << t.value()-rtime +// << " nnz=" << set1.nonZeros() << "\n";getchar(); +// } +// { +// RandomSetter set1(sm1); +// t.reset(); t.start(); +// for (int k=0; k(0,rows-1),internal::random(0,cols-1)) += 1; +// t.stop(); +// std::cout << "google::dense => \t" << t.value()-rtime +// << " nnz=" << set1.nonZeros() << "\n";getchar(); +// } +// { +// RandomSetter set1(sm1); +// t.reset(); t.start(); +// for (int k=0; k(0,rows-1),internal::random(0,cols-1)) += 1; +// t.stop(); +// std::cout << "google::sparse => \t" << t.value()-rtime +// << " nnz=" << set1.nonZeros() << "\n";getchar(); +// } + std::cout << "\n\n"; + } + + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_setter.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_setter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9f0b11cc4b7c3819ffb530bd1cec9cbb4f84272 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_setter.cpp @@ -0,0 +1,485 @@ + +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.005 -DSIZE=10000 && ./a.out +//g++ -O3 -g0 -DNDEBUG sparse_product.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.05 -DSIZE=2000 && ./a.out +// -DNOGMM -DNOMTL -DCSPARSE +// -I /home/gael/Coding/LinearAlgebra/CSparse/Include/ /home/gael/Coding/LinearAlgebra/CSparse/Lib/libcsparse.a +#ifndef SIZE +#define SIZE 100000 +#endif + +#ifndef NBPERROW +#define NBPERROW 24 +#endif + +#ifndef REPEAT +#define REPEAT 2 +#endif + +#ifndef NBTRIES +#define NBTRIES 2 +#endif + +#ifndef KK +#define KK 10 +#endif + +#ifndef NOGOOGLE +#define EIGEN_GOOGLEHASH_SUPPORT +#include +#endif + +#include "BenchSparseUtil.h" + +#define CHECK_MEM +// #define CHECK_MEM std/**/::cout << "check mem\n"; getchar(); + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j Coordinates; +typedef std::vector Values; + +EIGEN_DONT_INLINE Scalar* setinnerrand_eigen(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_dynamic(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_compact(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_sumeq(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_gnu_hash(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_google_dense(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_eigen_google_sparse(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_scipy(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_ublas_mapped(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_ublas_coord(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_ublas_compressed(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_ublas_genvec(const Coordinates& coords, const Values& vals); +EIGEN_DONT_INLINE Scalar* setrand_mtl(const Coordinates& coords, const Values& vals); + +int main(int argc, char *argv[]) +{ + int rows = SIZE; + int cols = SIZE; + bool fullyrand = true; + + BenchTimer timer; + Coordinates coords; + Values values; + if(fullyrand) + { + Coordinates pool; + pool.reserve(cols*NBPERROW); + std::cerr << "fill pool" << "\n"; + for (int i=0; i stencil(SIZE,SIZE); + Vector2i ij(internal::random(0,rows-1),internal::random(0,cols-1)); +// if(stencil.coeffRef(ij.x(), ij.y())==0) + { +// stencil.coeffRef(ij.x(), ij.y()) = 1; + pool.push_back(ij); + + } + ++i; + } + std::cerr << "pool ok" << "\n"; + int n = cols*NBPERROW*KK; + coords.reserve(n); + values.reserve(n); + for (int i=0; i(0,pool.size()); + coords.push_back(pool[i]); + values.push_back(internal::random()); + } + } + else + { + for (int j=0; j(0,rows-1),j)); + values.push_back(internal::random()); + } + } + std::cout << "nnz = " << coords.size() << "\n"; + CHECK_MEM + + // dense matrices + #ifdef DENSEMATRIX + { + BENCH(setrand_eigen_dense(coords,values);) + std::cout << "Eigen Dense\t" << timer.value() << "\n"; + } + #endif + + // eigen sparse matrices +// if (!fullyrand) +// { +// BENCH(setinnerrand_eigen(coords,values);) +// std::cout << "Eigen fillrand\t" << timer.value() << "\n"; +// } + { + BENCH(setrand_eigen_dynamic(coords,values);) + std::cout << "Eigen dynamic\t" << timer.value() << "\n"; + } +// { +// BENCH(setrand_eigen_compact(coords,values);) +// std::cout << "Eigen compact\t" << timer.value() << "\n"; +// } + { + BENCH(setrand_eigen_sumeq(coords,values);) + std::cout << "Eigen sumeq\t" << timer.value() << "\n"; + } + { +// BENCH(setrand_eigen_gnu_hash(coords,values);) +// std::cout << "Eigen std::map\t" << timer.value() << "\n"; + } + { + BENCH(setrand_scipy(coords,values);) + std::cout << "scipy\t" << timer.value() << "\n"; + } + #ifndef NOGOOGLE + { + BENCH(setrand_eigen_google_dense(coords,values);) + std::cout << "Eigen google dense\t" << timer.value() << "\n"; + } + { + BENCH(setrand_eigen_google_sparse(coords,values);) + std::cout << "Eigen google sparse\t" << timer.value() << "\n"; + } + #endif + + #ifndef NOUBLAS + { +// BENCH(setrand_ublas_mapped(coords,values);) +// std::cout << "ublas mapped\t" << timer.value() << "\n"; + } + { + BENCH(setrand_ublas_genvec(coords,values);) + std::cout << "ublas vecofvec\t" << timer.value() << "\n"; + } + /*{ + timer.reset(); + timer.start(); + for (int k=0; k mat(SIZE,SIZE); + //mat.startFill(2000000/*coords.size()*/); + for (int i=0; i mat(SIZE,SIZE); + mat.reserve(coords.size()/10); + for (int i=0; i mat(SIZE,SIZE); + for (int j=0; j aux(SIZE,SIZE); + mat.reserve(n); + for (int i=j*n; i<(j+1)*n; ++i) + { + aux.insert(coords[i].x(), coords[i].y()) += vals[i]; + } + aux.finalize(); + mat += aux; + } + return &mat.coeffRef(coords[0].x(), coords[0].y()); +} + +EIGEN_DONT_INLINE Scalar* setrand_eigen_compact(const Coordinates& coords, const Values& vals) +{ + using namespace Eigen; + DynamicSparseMatrix setter(SIZE,SIZE); + setter.reserve(coords.size()/10); + for (int i=0; i mat = setter; + CHECK_MEM; + return &mat.coeffRef(coords[0].x(), coords[0].y()); +} + +EIGEN_DONT_INLINE Scalar* setrand_eigen_gnu_hash(const Coordinates& coords, const Values& vals) +{ + using namespace Eigen; + SparseMatrix mat(SIZE,SIZE); + { + RandomSetter, StdMapTraits > setter(mat); + for (int i=0; i mat(SIZE,SIZE); + { + RandomSetter, GoogleDenseHashMapTraits> setter(mat); + for (int i=0; i mat(SIZE,SIZE); + { + RandomSetter, GoogleSparseHashMapTraits> setter(mat); + for (int i=0; i +void coo_tocsr(const int n_row, + const int n_col, + const int nnz, + const Coordinates Aij, + const Values Ax, + int Bp[], + int Bj[], + T Bx[]) +{ + //compute number of non-zero entries per row of A coo_tocsr + std::fill(Bp, Bp + n_row, 0); + + for (int n = 0; n < nnz; n++){ + Bp[Aij[n].x()]++; + } + + //cumsum the nnz per row to get Bp[] + for(int i = 0, cumsum = 0; i < n_row; i++){ + int temp = Bp[i]; + Bp[i] = cumsum; + cumsum += temp; + } + Bp[n_row] = nnz; + + //write Aj,Ax into Bj,Bx + for(int n = 0; n < nnz; n++){ + int row = Aij[n].x(); + int dest = Bp[row]; + + Bj[dest] = Aij[n].y(); + Bx[dest] = Ax[n]; + + Bp[row]++; + } + + for(int i = 0, last = 0; i <= n_row; i++){ + int temp = Bp[i]; + Bp[i] = last; + last = temp; + } + + //now Bp,Bj,Bx form a CSR representation (with possible duplicates) +} + +template< class T1, class T2 > +bool kv_pair_less(const std::pair& x, const std::pair& y){ + return x.first < y.first; +} + + +template +void csr_sort_indices(const I n_row, + const I Ap[], + I Aj[], + T Ax[]) +{ + std::vector< std::pair > temp; + + for(I i = 0; i < n_row; i++){ + I row_start = Ap[i]; + I row_end = Ap[i+1]; + + temp.clear(); + + for(I jj = row_start; jj < row_end; jj++){ + temp.push_back(std::make_pair(Aj[jj],Ax[jj])); + } + + std::sort(temp.begin(),temp.end(),kv_pair_less); + + for(I jj = row_start, n = 0; jj < row_end; jj++, n++){ + Aj[jj] = temp[n].first; + Ax[jj] = temp[n].second; + } + } +} + +template +void csr_sum_duplicates(const I n_row, + const I n_col, + I Ap[], + I Aj[], + T Ax[]) +{ + I nnz = 0; + I row_end = 0; + for(I i = 0; i < n_row; i++){ + I jj = row_end; + row_end = Ap[i+1]; + while( jj < row_end ){ + I j = Aj[jj]; + T x = Ax[jj]; + jj++; + while( jj < row_end && Aj[jj] == j ){ + x += Ax[jj]; + jj++; + } + Aj[nnz] = j; + Ax[nnz] = x; + nnz++; + } + Ap[i+1] = nnz; + } +} + +EIGEN_DONT_INLINE Scalar* setrand_scipy(const Coordinates& coords, const Values& vals) +{ + using namespace Eigen; + SparseMatrix mat(SIZE,SIZE); + mat.resizeNonZeros(coords.size()); +// std::cerr << "setrand_scipy...\n"; + coo_tocsr(SIZE,SIZE, coords.size(), coords, vals, mat._outerIndexPtr(), mat._innerIndexPtr(), mat._valuePtr()); +// std::cerr << "coo_tocsr ok\n"; + + csr_sort_indices(SIZE, mat._outerIndexPtr(), mat._innerIndexPtr(), mat._valuePtr()); + + csr_sum_duplicates(SIZE, SIZE, mat._outerIndexPtr(), mat._innerIndexPtr(), mat._valuePtr()); + + mat.resizeNonZeros(mat._outerIndexPtr()[SIZE]); + + return &mat.coeffRef(coords[0].x(), coords[0].y()); +} + + +#ifndef NOUBLAS +EIGEN_DONT_INLINE Scalar* setrand_ublas_mapped(const Coordinates& coords, const Values& vals) +{ + using namespace boost; + using namespace boost::numeric; + using namespace boost::numeric::ublas; + mapped_matrix aux(SIZE,SIZE); + for (int i=0; i mat(aux); + return 0;// &mat(coords[0].x(), coords[0].y()); +} +/*EIGEN_DONT_INLINE Scalar* setrand_ublas_coord(const Coordinates& coords, const Values& vals) +{ + using namespace boost; + using namespace boost::numeric; + using namespace boost::numeric::ublas; + coordinate_matrix aux(SIZE,SIZE); + for (int i=0; i mat(aux); + return 0;//&mat(coords[0].x(), coords[0].y()); +} +EIGEN_DONT_INLINE Scalar* setrand_ublas_compressed(const Coordinates& coords, const Values& vals) +{ + using namespace boost; + using namespace boost::numeric; + using namespace boost::numeric::ublas; + compressed_matrix mat(SIZE,SIZE); + for (int i=0; i > foo; + generalized_vector_of_vector > > aux(SIZE,SIZE); + for (int i=0; i mat(aux); + return 0;//&mat(coords[0].x(), coords[0].y()); +} +#endif + +#ifndef NOMTL +EIGEN_DONT_INLINE void setrand_mtl(const Coordinates& coords, const Values& vals); +#endif + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_transpose.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_transpose.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9aacf5f111ffb93999d50f80aea192bd4c84f8e --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/sparse_transpose.cpp @@ -0,0 +1,104 @@ + +//g++ -O3 -g0 -DNDEBUG sparse_transpose.cpp -I.. -I/home/gael/Coding/LinearAlgebra/mtl4/ -DDENSITY=0.005 -DSIZE=10000 && ./a.out +// -DNOGMM -DNOMTL +// -DCSPARSE -I /home/gael/Coding/LinearAlgebra/CSparse/Include/ /home/gael/Coding/LinearAlgebra/CSparse/Lib/libcsparse.a + +#ifndef SIZE +#define SIZE 10000 +#endif + +#ifndef DENSITY +#define DENSITY 0.01 +#endif + +#ifndef REPEAT +#define REPEAT 1 +#endif + +#include "BenchSparseUtil.h" + +#ifndef MINDENSITY +#define MINDENSITY 0.0004 +#endif + +#ifndef NBTRIES +#define NBTRIES 10 +#endif + +#define BENCH(X) \ + timer.reset(); \ + for (int _j=0; _j=MINDENSITY; density*=0.5) + { + fillMatrix(density, rows, cols, sm1); + + // dense matrices + #ifdef DENSEMATRIX + { + DenseMatrix m1(rows,cols), m3(rows,cols); + eiToDense(sm1, m1); + BENCH(for (int k=0; k EigenSparseTriMatrix; +typedef SparseMatrix EigenSparseTriMatrixRow; + +void fillMatrix(float density, int rows, int cols, EigenSparseTriMatrix& dst) +{ + dst.startFill(rows*cols*density); + for(int j = 0; j < cols; j++) + { + for(int i = 0; i < j; i++) + { + Scalar v = (internal::random(0,1) < density) ? internal::random() : 0; + if (v!=0) + dst.fill(i,j) = v; + } + dst.fill(j,j) = internal::random(); + } + dst.endFill(); +} + +int main(int argc, char *argv[]) +{ + int rows = SIZE; + int cols = SIZE; + float density = DENSITY; + BenchTimer timer; + #if 1 + EigenSparseTriMatrix sm1(rows,cols); + typedef Matrix DenseVector; + DenseVector b = DenseVector::Random(cols); + DenseVector x = DenseVector::Random(cols); + + bool densedone = false; + + for (float density = DENSITY; density>=MINDENSITY; density*=0.5) + { + EigenSparseTriMatrix sm1(rows, cols); + fillMatrix(density, rows, cols, sm1); + + // dense matrices + #ifdef DENSEMATRIX + if (!densedone) + { + densedone = true; + std::cout << "Eigen Dense\t" << density*100 << "%\n"; + DenseMatrix m1(rows,cols); + Matrix m2(rows,cols); + eiToDense(sm1, m1); + m2 = m1; + + BENCH(x = m1.marked().solveTriangular(b);) + std::cout << " colmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x.transpose() << "\n"; + + BENCH(x = m2.marked().solveTriangular(b);) + std::cout << " rowmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x.transpose() << "\n"; + } + #endif + + // eigen sparse matrices + { + std::cout << "Eigen sparse\t" << density*100 << "%\n"; + EigenSparseTriMatrixRow sm2 = sm1; + + BENCH(x = sm1.solveTriangular(b);) + std::cout << " colmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x.transpose() << "\n"; + + BENCH(x = sm2.solveTriangular(b);) + std::cout << " rowmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x.transpose() << "\n"; + +// x = b; +// BENCH(sm1.inverseProductInPlace(x);) +// std::cout << " colmajor^-1 * b:\t" << timer.value() << " (inplace)" << endl; +// std::cerr << x.transpose() << "\n"; +// +// x = b; +// BENCH(sm2.inverseProductInPlace(x);) +// std::cout << " rowmajor^-1 * b:\t" << timer.value() << " (inplace)" << endl; +// std::cerr << x.transpose() << "\n"; + } + + + + // CSparse + #ifdef CSPARSE + { + std::cout << "CSparse \t" << density*100 << "%\n"; + cs *m1; + eiToCSparse(sm1, m1); + + BENCH(x = b; if (!cs_lsolve (m1, x.data())){std::cerr << "cs_lsolve failed\n"; break;}; ) + std::cout << " colmajor^-1 * b:\t" << timer.value() << endl; + } + #endif + + // GMM++ + #ifndef NOGMM + { + std::cout << "GMM++ sparse\t" << density*100 << "%\n"; + GmmSparse m1(rows,cols); + gmm::csr_matrix m2; + eiToGmm(sm1, m1); + gmm::copy(m1,m2); + std::vector gmmX(cols), gmmB(cols); + Map >(&gmmX[0], cols) = x; + Map >(&gmmB[0], cols) = b; + + gmmX = gmmB; + BENCH(gmm::upper_tri_solve(m1, gmmX, false);) + std::cout << " colmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << Map >(&gmmX[0], cols).transpose() << "\n"; + + gmmX = gmmB; + BENCH(gmm::upper_tri_solve(m2, gmmX, false);) + timer.stop(); + std::cout << " rowmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << Map >(&gmmX[0], cols).transpose() << "\n"; + } + #endif + + // MTL4 + #ifndef NOMTL + { + std::cout << "MTL4\t" << density*100 << "%\n"; + MtlSparse m1(rows,cols); + MtlSparseRowMajor m2(rows,cols); + eiToMtl(sm1, m1); + m2 = m1; + mtl::dense_vector x(rows, 1.0); + mtl::dense_vector b(rows, 1.0); + + BENCH(x = mtl::upper_trisolve(m1,b);) + std::cout << " colmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x << "\n"; + + BENCH(x = mtl::upper_trisolve(m2,b);) + std::cout << " rowmajor^-1 * b:\t" << timer.value() << endl; +// std::cerr << x << "\n"; + } + #endif + + + std::cout << "\n\n"; + } + #endif + + #if 0 + // bench small matrices (in-place versus return bye value) + { + timer.reset(); + for (int _j=0; _j<10; ++_j) { + Matrix4f m = Matrix4f::Random(); + Vector4f b = Vector4f::Random(); + Vector4f x = Vector4f::Random(); + timer.start(); + for (int _k=0; _k<1000000; ++_k) { + b = m.inverseProduct(b); + } + timer.stop(); + } + std::cout << "4x4 :\t" << timer.value() << endl; + } + + { + timer.reset(); + for (int _j=0; _j<10; ++_j) { + Matrix4f m = Matrix4f::Random(); + Vector4f b = Vector4f::Random(); + Vector4f x = Vector4f::Random(); + timer.start(); + for (int _k=0; _k<1000000; ++_k) { + m.inverseProductInPlace(x); + } + timer.stop(); + } + std::cout << "4x4 IP :\t" << timer.value() << endl; + } + #endif + + return 0; +} + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/CMakeLists.txt b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..029ba6d6be57b404e697fe9c399a1d5401553ae1 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/CMakeLists.txt @@ -0,0 +1,85 @@ + + +set(BLAS_FOUND TRUE) +set(LAPACK_FOUND TRUE) +set(BLAS_LIBRARIES eigen_blas_static) +set(LAPACK_LIBRARIES eigen_lapack_static) + +set(SPARSE_LIBS "") + +# find_library(PARDISO_LIBRARIES pardiso412-GNU450-X86-64) +# if(PARDISO_LIBRARIES) +# add_definitions("-DEIGEN_PARDISO_SUPPORT") +# set(SPARSE_LIBS ${SPARSE_LIBS} ${PARDISO_LIBRARIES}) +# endif(PARDISO_LIBRARIES) + +find_package(Cholmod) +if(CHOLMOD_FOUND AND BLAS_FOUND AND LAPACK_FOUND) + add_definitions("-DEIGEN_CHOLMOD_SUPPORT") + include_directories(${CHOLMOD_INCLUDES}) + set(SPARSE_LIBS ${SPARSE_LIBS} ${CHOLMOD_LIBRARIES} ${BLAS_LIBRARIES} ${LAPACK_LIBRARIES}) + set(CHOLMOD_ALL_LIBS ${CHOLMOD_LIBRARIES} ${BLAS_LIBRARIES} ${LAPACK_LIBRARIES}) +endif() + +find_package(Umfpack) +if(UMFPACK_FOUND AND BLAS_FOUND) + add_definitions("-DEIGEN_UMFPACK_SUPPORT") + include_directories(${UMFPACK_INCLUDES}) + set(SPARSE_LIBS ${SPARSE_LIBS} ${UMFPACK_LIBRARIES} ${BLAS_LIBRARIES}) + set(UMFPACK_ALL_LIBS ${UMFPACK_LIBRARIES} ${BLAS_LIBRARIES}) +endif() + +find_package(SuperLU 4.0) +if(SUPERLU_FOUND AND BLAS_FOUND) + add_definitions("-DEIGEN_SUPERLU_SUPPORT") + include_directories(${SUPERLU_INCLUDES}) + set(SPARSE_LIBS ${SPARSE_LIBS} ${SUPERLU_LIBRARIES} ${BLAS_LIBRARIES}) + set(SUPERLU_ALL_LIBS ${SUPERLU_LIBRARIES} ${BLAS_LIBRARIES}) +endif() + + +find_package(PASTIX QUIET COMPONENTS METIS SCOTCH) +# check that the PASTIX found is a version without MPI +find_path(PASTIX_pastix_nompi.h_INCLUDE_DIRS + NAMES pastix_nompi.h + HINTS ${PASTIX_INCLUDE_DIRS} +) +if (NOT PASTIX_pastix_nompi.h_INCLUDE_DIRS) + message(STATUS "A version of Pastix has been found but pastix_nompi.h does not exist in the include directory." + " Because Eigen tests require a version without MPI, we disable the Pastix backend.") +endif() +if(PASTIX_FOUND AND PASTIX_pastix_nompi.h_INCLUDE_DIRS AND BLAS_FOUND) + add_definitions("-DEIGEN_PASTIX_SUPPORT") + include_directories(${PASTIX_INCLUDE_DIRS_DEP}) + if(SCOTCH_FOUND) + include_directories(${SCOTCH_INCLUDE_DIRS}) + set(PASTIX_LIBRARIES ${PASTIX_LIBRARIES} ${SCOTCH_LIBRARIES}) + elseif(METIS_FOUND) + include_directories(${METIS_INCLUDE_DIRS}) + set(PASTIX_LIBRARIES ${PASTIX_LIBRARIES} ${METIS_LIBRARIES}) + endif(SCOTCH_FOUND) + set(SPARSE_LIBS ${SPARSE_LIBS} ${PASTIX_LIBRARIES_DEP} ${ORDERING_LIBRARIES}) + set(PASTIX_ALL_LIBS ${PASTIX_LIBRARIES_DEP}) +endif() + +if(METIS_FOUND) + include_directories(${METIS_INCLUDE_DIRS}) + set (SPARSE_LIBS ${SPARSE_LIBS} ${METIS_LIBRARIES}) + add_definitions("-DEIGEN_METIS_SUPPORT") +endif(METIS_FOUND) + +find_library(RT_LIBRARY rt) +if(RT_LIBRARY) + set(SPARSE_LIBS ${SPARSE_LIBS} ${RT_LIBRARY}) +endif(RT_LIBRARY) + +add_executable(spbenchsolver spbenchsolver.cpp) +target_link_libraries (spbenchsolver ${SPARSE_LIBS}) + +add_executable(spsolver sp_solver.cpp) +target_link_libraries (spsolver ${SPARSE_LIBS}) + + +add_executable(test_sparseLU test_sparseLU.cpp) +target_link_libraries (test_sparseLU ${SPARSE_LIBS}) + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/sp_solver.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/sp_solver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1f4bac8afdb4aa03bc8f6201a93fc86f982d4e7 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/sp_solver.cpp @@ -0,0 +1,125 @@ +// Small bench routine for Eigen available in Eigen +// (C) Desire NUENTSA WAKAM, INRIA + +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +// #include +#include +#include +using namespace std; +using namespace Eigen; + +int main(int argc, char **args) +{ + SparseMatrix A; + typedef SparseMatrix::Index Index; + typedef Matrix DenseMatrix; + typedef Matrix DenseRhs; + VectorXd b, x, tmp; + BenchTimer timer,totaltime; + //SparseLU > solver; +// SuperLU > solver; + ConjugateGradient, Lower,IncompleteCholesky > solver; + ifstream matrix_file; + string line; + int n; + // Set parameters +// solver.iparm(IPARM_THREAD_NBR) = 4; + /* Fill the matrix with sparse matrix stored in Matrix-Market coordinate column-oriented format */ + if (argc < 2) assert(false && "please, give the matrix market file "); + + timer.start(); + totaltime.start(); + loadMarket(A, args[1]); + cout << "End charging matrix " << endl; + bool iscomplex=false, isvector=false; + int sym; + getMarketHeader(args[1], sym, iscomplex, isvector); + if (iscomplex) { cout<< " Not for complex matrices \n"; return -1; } + if (isvector) { cout << "The provided file is not a matrix file\n"; return -1;} + if (sym != 0) { // symmetric matrices, only the lower part is stored + SparseMatrix temp; + temp = A; + A = temp.selfadjointView(); + } + timer.stop(); + + n = A.cols(); + // ====== TESTS FOR SPARSE TUTORIAL ====== +// cout<< "OuterSize " << A.outerSize() << " inner " << A.innerSize() << endl; +// SparseMatrix mat1(A); +// SparseMatrix mat2; +// cout << " norm of A " << mat1.norm() << endl; ; +// PermutationMatrix perm(n); +// perm.resize(n,1); +// perm.indices().setLinSpaced(n, 0, n-1); +// mat2 = perm * mat1; +// mat.subrows(); +// mat2.resize(n,n); +// mat2.reserve(10); +// mat2.setConstant(); +// std::cout<< "NORM " << mat1.squaredNorm()<< endl; + + cout<< "Time to load the matrix " << timer.value() < 2) + loadMarketVector(b, args[2]); + else + { + b.resize(n); + tmp.resize(n); +// tmp.setRandom(); + for (int i = 0; i < n; i++) tmp(i) = i; + b = A * tmp ; + } +// Scaling > scal; +// scal.computeRef(A); +// b = scal.LeftScaling().cwiseProduct(b); + + /* Compute the factorization */ + cout<< "Starting the factorization "<< endl; + timer.reset(); + timer.start(); + cout<< "Size of Input Matrix "<< b.size()<<"\n\n"; + cout<< "Rows and columns "<< A.rows() <<" " < + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.cpp b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4acd0039cee4c0af59e5c794b79d9443458ec283 --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.cpp @@ -0,0 +1,87 @@ +#include + +void bench_printhelp() +{ + cout<< " \nbenchsolver : performs a benchmark of all the solvers available in Eigen \n\n"; + cout<< " MATRIX FOLDER : \n"; + cout<< " The matrices for the benchmark should be collected in a folder specified with an environment variable EIGEN_MATRIXDIR \n"; + cout<< " The matrices are stored using the matrix market coordinate format \n"; + cout<< " The matrix and associated right-hand side (rhs) files are named respectively \n"; + cout<< " as MatrixName.mtx and MatrixName_b.mtx. If the rhs does not exist, a random one is generated. \n"; + cout<< " If a matrix is SPD, the matrix should be named as MatrixName_SPD.mtx \n"; + cout<< " If a true solution exists, it should be named as MatrixName_x.mtx; \n" ; + cout<< " it will be used to compute the norm of the error relative to the computed solutions\n\n"; + cout<< " OPTIONS : \n"; + cout<< " -h or --help \n print this help and return\n\n"; + cout<< " -d matrixdir \n Use matrixdir as the matrix folder instead of the one specified in the environment variable EIGEN_MATRIXDIR\n\n"; + cout<< " -o outputfile.xml \n Output the statistics to a xml file \n\n"; + cout<< " --eps Sets the relative tolerance for iterative solvers (default 1e-08) \n\n"; + cout<< " --maxits Sets the maximum number of iterations (default 1000) \n\n"; + +} +int main(int argc, char ** args) +{ + + bool help = ( get_options(argc, args, "-h") || get_options(argc, args, "--help") ); + if(help) { + bench_printhelp(); + return 0; + } + + // Get the location of the test matrices + string matrix_dir; + if (!get_options(argc, args, "-d", &matrix_dir)) + { + if(getenv("EIGEN_MATRIXDIR") == NULL){ + std::cerr << "Please, specify the location of the matrices with -d mat_folder or the environment variable EIGEN_MATRIXDIR \n"; + std::cerr << " Run with --help to see the list of all the available options \n"; + return -1; + } + matrix_dir = getenv("EIGEN_MATRIXDIR"); + } + + std::ofstream statbuf; + string statFile ; + + // Get the file to write the statistics + bool statFileExists = get_options(argc, args, "-o", &statFile); + if(statFileExists) + { + statbuf.open(statFile.c_str(), std::ios::out); + if(statbuf.good()){ + statFileExists = true; + printStatheader(statbuf); + statbuf.close(); + } + else + std::cerr << "Unable to open the provided file for writting... \n"; + } + + // Get the maximum number of iterations and the tolerance + int maxiters = 1000; + double tol = 1e-08; + string inval; + if (get_options(argc, args, "--eps", &inval)) + tol = atof(inval.c_str()); + if(get_options(argc, args, "--maxits", &inval)) + maxiters = atoi(inval.c_str()); + + string current_dir; + // Test the real-arithmetics matrices + Browse_Matrices(matrix_dir, statFileExists, statFile,maxiters, tol); + + // Test the complex-arithmetics matrices + Browse_Matrices >(matrix_dir, statFileExists, statFile, maxiters, tol); + + if(statFileExists) + { + statbuf.open(statFile.c_str(), std::ios::app); + statbuf << " \n"; + cout << "\n Output written in " << statFile << " ...\n"; + statbuf.close(); + } + + return 0; +} + + diff --git a/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.h b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.h new file mode 100644 index 0000000000000000000000000000000000000000..19c719c049a3f84d748446489bcc89b0792df42b --- /dev/null +++ b/duix-android/dh_aigc_android/duix-sdk/src/main/cpp/include/eigen3/bench/spbench/spbenchsolver.h @@ -0,0 +1,554 @@ +// This file is part of Eigen, a lightweight C++ template library +// for linear algebra. +// +// Copyright (C) 2012 Désiré Nuentsa-Wakam +// +// This Source Code Form is subject to the terms of the Mozilla +// Public License v. 2.0. If a copy of the MPL was not distributed +// with this file, You can obtain one at http://mozilla.org/MPL/2.0/. + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "spbenchstyle.h" + +#ifdef EIGEN_METIS_SUPPORT +#include +#endif + +#ifdef EIGEN_CHOLMOD_SUPPORT +#include +#endif + +#ifdef EIGEN_UMFPACK_SUPPORT +#include +#endif + +#ifdef EIGEN_PARDISO_SUPPORT +#include +#endif + +#ifdef EIGEN_SUPERLU_SUPPORT +#include +#endif + +#ifdef EIGEN_PASTIX_SUPPORT +#include +#endif + +// CONSTANTS +#define EIGEN_UMFPACK 10 +#define EIGEN_SUPERLU 20 +#define EIGEN_PASTIX 30 +#define EIGEN_PARDISO 40 +#define EIGEN_SPARSELU_COLAMD 50 +#define EIGEN_SPARSELU_METIS 51 +#define EIGEN_BICGSTAB 60 +#define EIGEN_BICGSTAB_ILUT 61 +#define EIGEN_GMRES 70 +#define EIGEN_GMRES_ILUT 71 +#define EIGEN_SIMPLICIAL_LDLT 80 +#define EIGEN_CHOLMOD_LDLT 90 +#define EIGEN_PASTIX_LDLT 100 +#define EIGEN_PARDISO_LDLT 110 +#define EIGEN_SIMPLICIAL_LLT 120 +#define EIGEN_CHOLMOD_SUPERNODAL_LLT 130 +#define EIGEN_CHOLMOD_SIMPLICIAL_LLT 140 +#define EIGEN_PASTIX_LLT 150 +#define EIGEN_PARDISO_LLT 160 +#define EIGEN_CG 170 +#define EIGEN_CG_PRECOND 180 + +using namespace Eigen; +using namespace std; + + +// Global variables for input parameters +int MaximumIters; // Maximum number of iterations +double RelErr; // Relative error of the computed solution +double best_time_val; // Current best time overall solvers +int best_time_id; // id of the best solver for the current system + +template inline typename NumTraits::Real test_precision() { return NumTraits::dummy_precision(); } +template<> inline float test_precision() { return 1e-3f; } +template<> inline double test_precision() { return 1e-6; } +template<> inline float test_precision >() { return test_precision(); } +template<> inline double test_precision >() { return test_precision(); } + +void printStatheader(std::ofstream& out) +{ + // Print XML header + // NOTE It would have been much easier to write these XML documents using external libraries like tinyXML or Xerces-C++. + + out << " \n"; + out << " \n"; + out << "\n]>"; + out << "\n\n\n"; + + out << "\n \n" ; //root XML element + // Print the xsl style section + printBenchStyle(out); + // List all available solvers + out << " \n"; +#ifdef EIGEN_UMFPACK_SUPPORT + out <<" \n"; + out << " LU \n"; + out << " UMFPACK \n"; + out << " \n"; +#endif +#ifdef EIGEN_SUPERLU_SUPPORT + out <<" \n"; + out << " LU \n"; + out << " SUPERLU \n"; + out << " \n"; +#endif +#ifdef EIGEN_CHOLMOD_SUPPORT + out <<" \n"; + out << " LLT SP \n"; + out << " CHOLMOD \n"; + out << " \n"; + + out <<" \n"; + out << " LLT \n"; + out << " CHOLMOD \n"; + out << " \n"; + + out <<" \n"; + out << " LDLT \n"; + out << " CHOLMOD \n"; + out << " \n"; +#endif +#ifdef EIGEN_PARDISO_SUPPORT + out <<" \n"; + out << " LU \n"; + out << " PARDISO \n"; + out << " \n"; + + out <<" \n"; + out << " LLT \n"; + out << " PARDISO \n"; + out << " \n"; + + out <<" \n"; + out << " LDLT \n"; + out << " PARDISO \n"; + out << " \n"; +#endif +#ifdef EIGEN_PASTIX_SUPPORT + out <<" \n"; + out << " LU \n"; + out << " PASTIX \n"; + out << " \n"; + + out <<" \n"; + out << " LLT \n"; + out << " PASTIX \n"; + out << " \n"; + + out <<" \n"; + out << " LDLT \n"; + out << " PASTIX \n"; + out << " \n"; +#endif + + out <<" \n"; + out << " BICGSTAB \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " BICGSTAB_ILUT \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " GMRES_ILUT \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " LDLT \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " LLT \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " CG \n"; + out << " EIGEN \n"; + out << " \n"; + + out <<" \n"; + out << " LU_COLAMD \n"; + out << " EIGEN \n"; + out << " \n"; + +#ifdef EIGEN_METIS_SUPPORT + out <<" \n"; + out << " LU_METIS \n"; + out << " EIGEN \n"; + out << " \n"; +#endif + out << " \n"; + +} + + +template +void call_solver(Solver &solver, const int solver_id, const typename Solver::MatrixType& A, const Matrix& b, const Matrix& refX,std::ofstream& statbuf) +{ + + double total_time; + double compute_time; + double solve_time; + double rel_error; + Matrix x; + BenchTimer timer; + timer.reset(); + timer.start(); + solver.compute(A); + if (solver.info() != Success) + { + std::cerr << "Solver failed ... \n"; + return; + } + timer.stop(); + compute_time = timer.value(); + statbuf << "