Files
obitools4/pkg/obiformats/json_writer.go
T

185 lines
3.8 KiB
Go
Raw Normal View History

2023-11-07 11:56:49 +02:00
package obiformats
import (
"bufio"
"bytes"
"io"
"os"
2023-11-07 12:10:14 +02:00
"strconv"
"strings"
2024-11-29 18:39:18 +01:00
"sync/atomic"
2023-11-07 11:56:49 +02:00
"time"
"github.com/goccy/go-json"
2023-11-29 12:14:37 +01:00
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obiiter"
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obiseq"
"git.metabarcoding.org/obitools/obitools4/obitools4/pkg/obiutils"
2023-11-07 11:56:49 +02:00
log "github.com/sirupsen/logrus"
)
2023-11-07 12:10:14 +02:00
func _UnescapeUnicodeCharactersInJSON(_jsonRaw []byte) ([]byte, error) {
str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(_jsonRaw)), `\\u`, `\u`, -1))
if err != nil {
return nil, err
}
return []byte(str), nil
}
2023-11-07 11:56:49 +02:00
func JSONRecord(sequence *obiseq.BioSequence) []byte {
record := make(map[string]interface{}, 4)
record["id"] = sequence.Id()
if sequence.HasSequence() {
record["sequence"] = sequence.String()
}
if sequence.HasQualities() {
record["qualities"] = sequence.QualitiesString()
}
if sequence.HasAnnotation() {
record["annotations"] = sequence.Annotations()
}
text, error := json.MarshalIndent(record, " ", " ")
2023-11-07 12:10:14 +02:00
if error != nil {
log.Panicf("conversion to JSON error on sequence id %s", sequence.Id())
}
text, error = _UnescapeUnicodeCharactersInJSON(text)
2023-11-07 11:56:49 +02:00
if error != nil {
log.Panicf("conversion to JSON error on sequence id %s", sequence.Id())
}
return text
}
2024-11-29 18:15:03 +01:00
func FormatJSONBatch(batch obiiter.BioSequenceBatch) *bytes.Buffer {
2023-11-07 11:56:49 +02:00
buff := new(bytes.Buffer)
2024-11-29 18:15:03 +01:00
2023-11-07 11:56:49 +02:00
json := bufio.NewWriter(buff)
2024-11-29 18:15:03 +01:00
if batch.Order() == 0 {
json.WriteString("[\n")
} else {
json.WriteString(",\n")
}
2023-11-07 11:56:49 +02:00
n := batch.Slice().Len() - 1
for i, s := range batch.Slice() {
json.WriteString(" ")
json.Write(JSONRecord(s))
if i < n {
json.WriteString(",\n")
}
}
json.Flush()
2024-11-29 18:15:03 +01:00
return buff
2023-11-07 11:56:49 +02:00
}
func WriteJSON(iterator obiiter.IBioSequence,
file io.WriteCloser,
options ...WithOption) (obiiter.IBioSequence, error) {
2024-11-29 18:39:18 +01:00
var latestChunk atomic.Int64
2023-11-07 11:56:49 +02:00
opt := MakeOptions(options)
file, _ = obiutils.CompressStream(file, opt.CompressedFile(), opt.CloseFile())
newIter := obiiter.MakeIBioSequence()
nwriters := opt.ParallelWorkers()
2024-11-29 18:15:03 +01:00
chunkchan := WriteFileChunk(file, opt.CloseFile())
2023-11-07 11:56:49 +02:00
newIter.Add(nwriters)
go func() {
newIter.WaitAndClose()
2024-11-29 18:39:18 +01:00
chunkchan <- FileChunk{
Source: "end",
Raw: bytes.NewBuffer([]byte("\n]\n")),
Order: int(latestChunk.Load()) + 1,
}
2023-11-07 11:56:49 +02:00
for len(chunkchan) > 0 {
time.Sleep(time.Millisecond)
}
close(chunkchan)
}()
ff := func(iterator obiiter.IBioSequence) {
for iterator.Next() {
batch := iterator.Get()
2024-11-29 18:15:03 +01:00
ss := FileChunk{
Source: batch.Source(),
Raw: FormatJSONBatch(batch),
Order: batch.Order(),
2023-11-07 11:56:49 +02:00
}
2024-11-29 18:15:03 +01:00
chunkchan <- ss
2024-11-29 18:39:18 +01:00
latestChunk.Store(int64(batch.Order()))
2023-11-07 11:56:49 +02:00
newIter.Push(batch)
}
newIter.Done()
}
log.Debugln("Start of the JSON file writing")
2024-11-29 18:15:03 +01:00
for i := 1; i < nwriters; i++ {
2023-11-07 11:56:49 +02:00
go ff(iterator.Split())
}
2024-11-29 18:15:03 +01:00
go ff(iterator)
2023-11-07 11:56:49 +02:00
return newIter, nil
}
func WriteJSONToStdout(iterator obiiter.IBioSequence,
options ...WithOption) (obiiter.IBioSequence, error) {
2024-11-29 18:15:03 +01:00
options = append(options, OptionCloseFile())
2023-11-07 11:56:49 +02:00
return WriteJSON(iterator, os.Stdout, options...)
}
func WriteJSONToFile(iterator obiiter.IBioSequence,
filename string,
options ...WithOption) (obiiter.IBioSequence, error) {
opt := MakeOptions(options)
flags := os.O_WRONLY | os.O_CREATE
if opt.AppendFile() {
flags |= os.O_APPEND
2024-06-19 13:15:30 +02:00
} else {
flags |= os.O_TRUNC
2023-11-07 11:56:49 +02:00
}
2024-06-19 13:15:30 +02:00
2023-11-07 11:56:49 +02:00
file, err := os.OpenFile(filename, flags, 0660)
if err != nil {
log.Fatalf("open file error: %v", err)
return obiiter.NilIBioSequence, err
}
options = append(options, OptionCloseFile())
iterator, err = WriteJSON(iterator, file, options...)
if opt.HaveToSavePaired() {
var revfile *os.File
revfile, err = os.OpenFile(opt.PairedFileName(), flags, 0660)
if err != nil {
log.Fatalf("open file error: %v", err)
return obiiter.NilIBioSequence, err
}
iterator, err = WriteJSON(iterator.PairedWith(), revfile, options...)
}
return iterator, err
}