AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-159072

user366312's questions

Martin Hope
user366312
Asked: 2024-05-23 18:41:37 +0800 CST

我该如何像在电子表格中那样按列对CSV文件进行排序?

  • 6
假设我有一个如下的CSV文件: ``` Column1,Column2,Column3 C,3,1 B,2,2 A,3,3 C,3,10 B,2,20 A,2,30 C,3,100 B,1,200 A,1,300 ``` 我想按照以下顺序对其进行排序: 1. 首先按Column1排序 2. 其次按Column2排序 3. 最后按Column3排序 排序后的结果应该是这样的: ``` Column1,Column2,Column3 A,1,300 A,2,30 A,3,3 B,1,200 B,2,2 B,2,20 C,3,1 C,3,10 C,3,100 ``` 为了按列对CSV进行升序/降序排序,我创建了以下类: ```csharp using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace SikorskiLibMemoryLess { public enum SortTypeEnum { Ascending, Descending } public static class ListExtensions { public static string ToCommaSeparatedString(this List list) { if (list == null || !list.Any()) { return string.Empty; } return string.Join(",", list); } } public class CSVSorter { public List Header { get; private set; } public List> Data { get; private set; } public CSVSorter() { Data = new List>(); } public void LoadCSV(string filePath, bool hasHeader = true) { using (StreamReader sr = new StreamReader(filePath)) { string line; bool isFirstLine = true; while ((line = sr.ReadLine()) != null) { List columns = line.Split(',').Select(col => string.IsNullOrWhiteSpace(col) ? null : col).ToList(); if (isFirstLine && hasHeader) { Header = columns; isFirstLine = false; } else { Data.Add(columns); if (isFirstLine) { isFirstLine = false; if (!hasHeader) { Header = Enumerable.Range(1, columns.Count).Select(i => "Column" + i).ToList(); } } } } } } public void LoadCSV(string fileName, string fileDir, bool hasHeader = true) { string filePath = Path.Combine(fileDir, fileName); LoadCSV(filePath, hasHeader); } public void LoadCSV(IEnumerable> csvData, bool hasHeader = true) { bool isFirstLine = true; foreach (var columns in csvData) { var processedColumns = columns.Select(col => string.IsNullOrWhiteSpace(col) ? null : col).ToList(); if (isFirstLine && hasHeader) { Header = processedColumns; isFirstLine = false; } else { Data.Add(processedColumns); if (isFirstLine) { isFirstLine = false; if (!hasHeader) { Header = Enumerable.Range(1, processedColumns.Count).Select(i => "Column" + i).ToList(); } } } } } public void Sort(int[] columns, SortTypeEnum ascendingOrDescending) { try { IOrderedEnumerable> sortedData = null; if (ascendingOrDescending == SortTypeEnum.Ascending) { sortedData = Data.OrderBy(row => GetColumnValueSafe(row, columns[0])); for (int i = 1; i < columns.Length; i++) { sortedData = sortedData.ThenBy(row => GetColumnValueSafe(row, columns[i])); } } Data = sortedData.ToList(); } catch (Exception ex) { Console.WriteLine($"Error during sorting: {ex.Message}"); Console.WriteLine(ex.StackTrace); } } private string GetColumnValueSafe(List row, int columnIndex) { return columnIndex < row.Count ? row[columnIndex] : null; } public IEnumerable> Get() { yield return Header; foreach (var row in Data) { yield return row; } } public void SaveCSV(string filePath) { using (StreamWriter sw = new StreamWriter(filePath)) { // 写入标题 sw.WriteLine(string.Join(",", Header)); // 写入数据行 foreach (var row in Data) { sw.WriteLine(string.Join(",", row.Select(col => col ?? ""))); } } } public void SaveCSV(string fileName, string fileDir) { string
c#
  • 1 个回答
  • 29 Views
Martin Hope
user366312
Asked: 2024-01-22 21:43:50 +0800 CST

如何从这个指数拟合函数返回 A 和 b?

  • 5
using System;
using System.Collections.Generic;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.Optimization;

namespace NonLinearRegressionExample
{
    public class NonlinearRegressionCurveFitting
    {
        public static (List<double>, List<double>, List<double>) FitCurve(List<double> xData, List<double> yData)
        {
            // example data
            var xDataDense = new DenseVector(xData.ToArray());
            var yDataDense = new DenseVector(yData.ToArray());

            Vector<double> Model(Vector<double> parameters, Vector<double> x)
            {
                var y = CreateVector.Dense<double>(x.Count);
                for (int i = 0; i < x.Count; i++)
                {
                    y[i] = parameters[0] * Math.Exp(parameters[1] * x[i]);
                }
                return y;
            }

            var start = new DenseVector(new double[] { 1.0, 0.1 });
            var objective = ObjectiveFunction.NonlinearModel(Model, xDataDense, yDataDense);
            var solver = new LevenbergMarquardtMinimizer(maximumIterations: 10000);
            var result = solver.FindMinimum(objective, start);

            Vector<double> points = result.MinimizedValues;

            Vector<double> minimizing = result.MinimizingPoint;

            return (xData, new List<double>(points.ToArray()), new List<double>(minimizing.ToArray()));
        }
    }
}

驱动程序:

var fittedCurve = NonlinearRegressionCurveFitting.FitCurve(xData, yData);

            List<double> points = fittedCurve.Item2;
            List<double> result = fittedCurve.Item3;

            ///Output the results
            if (result.Count == 2)
            {
                DataPlotter plotter = new DataPlotter();
                //plotter.ZoomXaxis(0, 10);
                plotter.AddCurve("original",
                    new List<double>(xData.ToArray()),
                    new List<double>(yData.ToArray()),
                    IsSymbolVisible: false, color: Color.Red);
                plotter.AddCurve("fitted",
                    new List<double>(xData.ToArray()),
                    new List<double>(points.ToArray()),
                    IsSymbolVisible: false,
                    color: Color.Green);
                plotter.AddPoint("Point", result[0], result[1], Color.BlueViolet);
                plotter.ShowDialog();
            }

上述源代码使用非线性回归拟合指数曲线。

但是,如何从指数公式的 C# 函数中返回最佳值A和值b

y = A * exp(-x * b)

?

。

该函数返回的值MinimizingPoint似乎是 x 轴的起点。

在此输入图像描述

。

c#
  • 1 个回答
  • 70 Views
Martin Hope
user366312
Asked: 2024-01-14 00:58:48 +0800 CST

该函数无法检测两条曲线的交点

  • 6

下面的源代码应该找到两条曲线之间的交点。

但是,该函数无法检测交点。

我该如何修复它?

在此输入图像描述

using MathNet.Numerics.Interpolation;
using System.Collections.Generic;
using System.Linq;

public static Vec2 FindIntersectionOfTwoCurves(List<double> xList1, List<double> yList1,
                                               List<double> xList2, List<double> yList2)
{
    if (xList1 == null || yList1 == null || xList2 == null || yList2 == null ||
        xList1.Count != yList1.Count || xList2.Count != yList2.Count)
        return null;

    IInterpolation interpolation1 = Interpolate.Linear(xList1, yList1);
    IInterpolation interpolation2 = Interpolate.Linear(xList2, yList2);

    double lowerBound = Math.Max(xList1.Min(), xList2.Min());
    double upperBound = Math.Min(xList1.Max(), xList2.Max());

    double step = (upperBound - lowerBound) / 1000; // adjust the step size as needed
    for (double x = lowerBound; x <= upperBound; x += step)
    {
        double y1 = interpolation1.Interpolate(x);
        double y2 = interpolation2.Interpolate(x);

        if (Math.Abs(y1 - y2) < 1e-7)
        {
            return new Vec2(x, y1);
        }
    }

    return null;
}

public class Vec2
{
    public double X { get; set; }
    public double Y { get; set; }

    public Vec2(double x, double y)
    {
        X = x;
        Y = y;
    }
}
c#
  • 2 个回答
  • 87 Views
Martin Hope
user366312
Asked: 2023-10-25 08:48:05 +0800 CST

保存时数据框未垂直堆叠

  • 5

数据1.dat

   1 ASN C  7.042   9.118  0.000 1 1 1 1  1  0
   2 LEU H  5.781   5.488  7.470 0 0 0 0  1  0
   3 THR H  5.399   5.166  6.452 0 0 0 0  0  0
   4 GLU H  5.373   4.852  6.069 0 0 0 0  1  0
   5 LEU H  5.423   5.164  6.197 0 0 0 0  2  0
   6 LYS H  5.247   4.943  6.434 0 0 0 0  1  0
   7 ASN C  5.485   8.103  8.264 0 0 0 0  1  0
   8 THR C  6.675   9.152  9.047 0 0 0 0  1  0
   9 PRO C  6.372   8.536 11.954 0 0 0 0  0  0
  10 VAL H  5.669   5.433  6.703 0 0 0 0  0  0
  11 SER H  5.304   4.924  6.407 0 0 0 0  0  0
  12 GLU H  5.461   5.007  6.088 0 0 0 0  1  0
  13 LEU H  5.265   5.057  6.410 0 0 0 0  3  0
  14 ILE H  5.379   5.026  6.206 0 0 0 0  1  0
  15 THR H  5.525   5.154  6.000 0 0 0 0  1  0
  16 LEU H  5.403   5.173  6.102 0 0 0 0  1  0
  17 GLY H  5.588   5.279  6.195 0 0 0 0  1  0
  18 GLU H  5.381   5.238  6.675 0 0 0 0  1  0
  19 ASN H  5.298   5.287  6.668 0 0 0 0  1  0
  20 MSE H  5.704   7.411  4.926 0 0 0 0  1  0

数据2.dat

  21 GLY C  5.978   9.254  9.454 0 0 0 0  1  0
  22 LEU C  6.778  10.534 12.640 0 0 1 2  2  0
  23 GLU C  7.187   7.217 10.728 0 0 0 0  2  0
  24 ASN C  5.392   8.296 10.702 0 0 0 0  0  0
  25 LEU C  5.657   6.064  9.609 0 0 0 1  3  0
  26 ALA C  5.446   5.528  7.503 0 0 0 0  2  0
  27 ARG C  5.656   8.071  8.419 0 0 0 0  0  0
  28 MSE C  6.890   9.157  8.728 0 0 0 0  1  0
  29 ARG C  6.330   7.993 11.562 0 0 0 0  0  0
  30 LYS H  5.428   5.207  5.897 0 0 0 0  1  0
  31 GLN H  5.402   5.046  6.349 0 0 0 0  1  0
  32 ASP H  5.426   5.093  6.226 0 0 0 1  1  0
  33 ILE H  5.361   5.004  6.194 0 0 0 0  6  0
  34 ILE H  5.443   5.150  6.190 0 0 0 0  5  0
  35 PHE H  5.403   5.181  6.293 0 0 0 0  1  0
  36 ALA H  5.533   5.357  6.193 0 0 0 0  3  0
  37 ILE H  5.634   5.167  6.025 0 0 0 1  5  0
  38 LEU H  5.402   5.121  6.104 0 0 0 0  3  0
  39 LYS H  5.470   5.092  6.101 0 0 0 0  1  0
  40 GLN H  5.491   5.210  6.054 0 0 0 0  2  0
import os
import pandas as pd
from src.utils.get_root_dir import get_root_directory

def save_dataframe_to_ascii(df, filepath):
    df.to_csv(filepath, sep=',', index=False)

def getDataFrame(dataDirectoryPathString: str) -> pd.DataFrame:
    dataframes = []
    for filename in os.listdir(dataDirectoryPathString):
        if filename.endswith('.dat'):
            filepath = os.path.join(dataDirectoryPathString, filename)
            df = pd.read_csv(filepath, sep='\t')
            dataframes.append(df)
    concatenated_df = pd.concat(dataframes, ignore_index=True)
    return concatenated_df


if __name__ == "__main__":
    dataFrame = getDataFrame(get_root_directory() + "/data/")
    save_dataframe_to_ascii(dataFrame, get_root_directory() + "/save/save.txt")

输出:

   1 ASN C  7.042   9.118  0.000 1 1 1 1  1  0,  21 GLY C  5.978   9.254  9.454 0 0 0 0  1  0
   2 LEU H  5.781   5.488  7.470 0 0 0 0  1  0,
   3 THR H  5.399   5.166  6.452 0 0 0 0  0  0,
   4 GLU H  5.373   4.852  6.069 0 0 0 0  1  0,
   5 LEU H  5.423   5.164  6.197 0 0 0 0  2  0,
   6 LYS H  5.247   4.943  6.434 0 0 0 0  1  0,
   7 ASN C  5.485   8.103  8.264 0 0 0 0  1  0,
   8 THR C  6.675   9.152  9.047 0 0 0 0  1  0,
   9 PRO C  6.372   8.536 11.954 0 0 0 0  0  0,
  10 VAL H  5.669   5.433  6.703 0 0 0 0  0  0,
  11 SER H  5.304   4.924  6.407 0 0 0 0  0  0,
  12 GLU H  5.461   5.007  6.088 0 0 0 0  1  0,
  13 LEU H  5.265   5.057  6.410 0 0 0 0  3  0,
  14 ILE H  5.379   5.026  6.206 0 0 0 0  1  0,
  15 THR H  5.525   5.154  6.000 0 0 0 0  1  0,
  16 LEU H  5.403   5.173  6.102 0 0 0 0  1  0,
  17 GLY H  5.588   5.279  6.195 0 0 0 0  1  0,
  18 GLU H  5.381   5.238  6.675 0 0 0 0  1  0,
  19 ASN H  5.298   5.287  6.668 0 0 0 0  1  0,
  20 MSE H  5.704   7.411  4.926 0 0 0 0  1  0,
,  22 LEU C  6.778  10.534 12.640 0 0 1 2  2  0
,  23 GLU C  7.187   7.217 10.728 0 0 0 0  2  0
,  24 ASN C  5.392   8.296 10.702 0 0 0 0  0  0
,  25 LEU C  5.657   6.064  9.609 0 0 0 1  3  0
,  26 ALA C  5.446   5.528  7.503 0 0 0 0  2  0
,  27 ARG C  5.656   8.071  8.419 0 0 0 0  0  0
,  28 MSE C  6.890   9.157  8.728 0 0 0 0  1  0
,  29 ARG C  6.330   7.993 11.562 0 0 0 0  0  0
,  30 LYS H  5.428   5.207  5.897 0 0 0 0  1  0
,  31 GLN H  5.402   5.046  6.349 0 0 0 0  1  0
,  32 ASP H  5.426   5.093  6.226 0 0 0 1  1  0
,  33 ILE H  5.361   5.004  6.194 0 0 0 0  6  0
,  34 ILE H  5.443   5.150  6.190 0 0 0 0  5  0
,  35 PHE H  5.403   5.181  6.293 0 0 0 0  1  0
,  36 ALA H  5.533   5.357  6.193 0 0 0 0  3  0
,  37 ILE H  5.634   5.167  6.025 0 0 0 1  5  0
,  38 LEU H  5.402   5.121  6.104 0 0 0 0  3  0
,  39 LYS H  5.470   5.092  6.101 0 0 0 0  1  0
,  40 GLN H  5.491   5.210  6.054 0 0 0 0  2  0

这些行应该垂直堆叠。

为什么输出断了?

我该如何修复它?

python
  • 1 个回答
  • 39 Views
Martin Hope
user366312
Asked: 2023-09-17 20:04:05 +0800 CST

为什么 trunc() 返回 0?

  • 7
  • 即使值相等,单元测试也会失败

我被上面的问题困住了。

在尝试解决这个问题时,我编写了以下清单。

我希望它保留小数点后两位数。

#include "simulation.hpp"
#include <cstdio>

typedef double real;

double truncate_(double f)
{
    return std::trunc(f * 100.0);
}

int main()
{
    //Simulation sim;
    //sim.run();
    LennardJones lj(Constants::EPSILON, Constants::SIGMA, Constants::KB);

    Vec3 diatance(4.0, 4.0, 4.0);

    real attractive = lj.getPotentialAttractive(diatance);
    real repulsive = lj.getPotentialRepulsive(diatance);

    std::cout << attractive << std::endl;
    std::cout << repulsive << std::endl;

    real attractive2 = truncate_(attractive);
    real repulsive2 = truncate_(repulsive);

    std::cout << attractive2 << std::endl;
    std::cout << repulsive2 << std::endl;

    getchar(); // Wait for a keypress
}

输出:

-4.84292e-06
6.82474e-08
-0
0
c++
  • 1 个回答
  • 65 Views
Martin Hope
user366312
Asked: 2023-08-19 19:26:31 +0800 CST

为什么他们只填充一个共享内存?

  • 4
  • 使用全局内存的合并读取来优化跨步访问的处理

上面的链接说:

__global__ void coalescedMultiply(float *a, float *c, int M)
{
  __shared__ float aTile[TILE_DIM][TILE_DIM],
                   transposedTile[TILE_DIM][TILE_DIM];
  int row = blockIdx.y * blockDim.y + threadIdx.y;
  int col = blockIdx.x * blockDim.x + threadIdx.x;
  float sum = 0.0f;
  aTile[threadIdx.y][threadIdx.x] = > a[row*TILE_DIM+threadIdx.x];
  transposedTile[threadIdx.x][threadIdx.y] =
      a[(blockIdx.x*blockDim.x + threadIdx.y)*TILE_DIM +
      threadIdx.x];  
  __syncthreads();
  for (int i = 0; i < TILE_DIM; i++) {
      sum += aTile[threadIdx.y][i]* transposedTile[i][threadIdx.x];
  }
  c[row*M+col] = sum;
}

(...)
这些多方银行冲突的代价非常高昂。简单的补救措施是填充共享内存阵列,使其具有额外的列,如以下代码行所示。

__shared__ float transposedTile[TILE_DIM][TILE_DIM+1];

我的问题是,

为什么它们只填充右侧 ( transposedTile) 共享内存,而不是同时填充 (transposedTile和aTile)?

cuda
  • 1 个回答
  • 28 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve