ak9im/p2/data.go
leo c3f9185077
p2: calculate impulse func estimate
* add visualisation code
* add pic
2023-02-26 21:20:40 +01:00

156 lines
2.5 KiB
Go

package main
import (
"encoding/csv"
"errors"
"io"
"os"
"strconv"
)
func readData(f *os.File) ([][]float64, error) {
records := make([][]string, 0, 252)
r := csv.NewReader(f)
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return [][]float64{}, err
}
records = append(records, record)
}
data, err := parseRecords(records)
if err != nil {
return data, err
}
return data, nil
}
func parseRecords(r [][]string) ([][]float64, error) {
if len(r) == 0 {
return [][]float64{}, errors.New("ErrNoRecords")
}
// remove the header.
r = r[1:]
u := 0
y := 1
data := [][]float64{make([]float64, 0, len(r)), make([]float64, 0, len(r))}
for _, uy := range r {
fu, err := strconv.ParseFloat(uy[u], 64)
if err != nil {
return [][]float64{}, err
}
fy, err := strconv.ParseFloat(uy[y], 64)
if err != nil {
return [][]float64{}, err
}
data[u] = append(data[u], fu)
data[y] = append(data[y], fy)
}
return data, nil
}
func readFile(s *string) ([][]float64, error) {
f, err := os.Open(*s)
if err != nil {
return [][]float64{}, err
}
defer f.Close()
data, err := readData(f)
if err != nil {
return [][]float64{}, err
}
return data, nil
}
func saveStuff(
meanU, meanY,
varianceU, varianceY,
cov float64,
autocorrelationU, autocorrelationY,
mutCorrelationUY, mutCorrelationYU,
impulseFunc []float64,
) error {
fFnames := map[string]float64{
"mean_u": meanU,
"mean_y": meanY,
"variance_u": varianceU,
"variance_y": varianceY,
"covariance_uy": cov,
}
sFnames := map[string][]float64{
"autocorrelation_u": autocorrelationU,
"autocorrelation_y": autocorrelationY,
"mutual_correlation_uy": mutCorrelationUY,
"mutual_correlation_yu": mutCorrelationYU,
"impulse_func": impulseFunc,
}
prefix := "data/"
suffix := ".txt"
for k, v := range fFnames {
f, err := os.Create(prefix + k + suffix)
if err != nil {
return err
}
defer f.Close()
_, err = f.WriteString(strconv.FormatFloat(v, 'f', 64, 64))
if err != nil {
return err
}
}
suffix = ".csv"
for k, v := range sFnames {
f, err := os.Create(prefix + k + suffix)
if err != nil {
return err
}
defer f.Close()
w := csv.NewWriter(f)
s := recordsFromFloat64Slice(v)
err = w.WriteAll(s)
if err != nil {
return err
}
}
return nil
}
func recordsFromFloat64Slice(f []float64) [][]string {
s := make([][]string, 0, len(f))
for i := range f {
tmp := strconv.FormatFloat(f[i], 'f', 64, 64)
s = append(s, []string{tmp})
}
return s
}