File: sundials_csv.py

package info (click to toggle)
sundials 7.1.1%2Bdfsg1-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 83,788 kB
  • sloc: ansic: 264,746; f90: 120,987; cpp: 69,481; python: 5,134; sh: 2,483; makefile: 266; perl: 123
file content (99 lines) | stat: -rw-r--r-- 2,298 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3
# -----------------------------------------------------------------------------
# Programmer(s): David J. Gardner @ LLNL
# -----------------------------------------------------------------------------
# SUNDIALS Copyright Start
# Copyright (c) 2002-2024, Lawrence Livermore National Security
# and Southern Methodist University.
# All rights reserved.
#
# See the top-level LICENSE and NOTICE files for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# SUNDIALS Copyright End
# -----------------------------------------------------------------------------
# Function to parse SUNDIALS CSV output files
# -----------------------------------------------------------------------------

def num(s):
    """Try to convert a string to an int or float"""

    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s


def keys(filename):
    """Extracts keys from a SUNDIALS CSV file

    Parameters
    ----------
    filename : str
        The file location of the SUNDIALS CSV file

    Returns
    -------
    list
        A list of dictionary keys
    """

    # Get keys from the first row
    with open(filename, mode='r') as csvfile:
        keys = csvfile.readline().split(",")[::2]

    return keys


def read(filename):
    """Reads a SUNDIALS CSV file

    Parameters
    ----------
    filename : str
        The file location of the SUNDIALS CSV file

    Returns
    -------
    dict
        A dictionary containing the CSV keys and values
    """

    import csv

    # Get dictionary keys
    fields = keys(filename)

    # Initialize dictionary
    csv_dict = {}
    for k in fields:
        csv_dict[k] = []

    # Get values from each row
    with open(filename, mode='r') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            values = row[1::2]
            for k, v in zip(fields, values):
                csv_dict[k].append(num(v))

    return csv_dict


def write(filename):
    """Prints a SUNDIALS CSV file

    Parameters
    ----------
    filename : str
        The file location of the SUNDIALS CSV file
    """

    csv_dict = read(filename)

    for key in csv_dict.keys():
        print(f"{key:29} = {csv_dict[key]}")
    print()