From 442bf3cde3e4dc587ae564586b6728399aa850a4 Mon Sep 17 00:00:00 2001 From: Chris Watson Date: Mon, 17 Jun 2019 23:18:45 -0700 Subject: [PATCH] Added to_json and from_json to Matrix and Vector --- src/apatite/linear_algebra/matrix.cr | 22 ++++++++++++++++++++ src/apatite/linear_algebra/vector.cr | 31 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/apatite/linear_algebra/matrix.cr b/src/apatite/linear_algebra/matrix.cr index 96c67f1..9cc4bd8 100644 --- a/src/apatite/linear_algebra/matrix.cr +++ b/src/apatite/linear_algebra/matrix.cr @@ -1,3 +1,4 @@ +require "json" require "./vector" module Apatite::LinearAlgebra @@ -18,6 +19,21 @@ module Apatite::LinearAlgebra @column_count = column_count || rows[0].size end + # Creates a new `Vector` instance from a `JSON::PullParser` + def self.new(pull : JSON::PullParser) + arr = [] of Vector + new(pull) do |element| + arr << element + end + rows(arr) + end + + def self.new(pull : JSON::PullParser, &block) + pull.read_array do + yield Vector.new(pull) + end + end + # Creates a matrix where each argument is a row. def self.[](*rows) rows(rows) @@ -528,6 +544,12 @@ module Apatite::LinearAlgebra end end + def to_json(json : JSON::Builder) + json.array do + each &.to_json(json) + end + end + @[AlwaysInline] def unsafe_fetch(index : Int) @buffer[index] diff --git a/src/apatite/linear_algebra/vector.cr b/src/apatite/linear_algebra/vector.cr index 0673b79..ca2271b 100644 --- a/src/apatite/linear_algebra/vector.cr +++ b/src/apatite/linear_algebra/vector.cr @@ -1,3 +1,5 @@ +require "json" + module Apatite::LinearAlgebra # Represents a mathematical vector, and also constitutes a row or column # of a `Matrix` @@ -75,6 +77,21 @@ module Apatite::LinearAlgebra end end + # Creates a new `Vector` instance from a `JSON::PullParser` + def self.new(pull : JSON::PullParser) + vec = new + new(pull) do |element| + vec << element + end + vec + end + + def self.new(pull : JSON::PullParser, &block) + pull.read_array do + yield Float64.new(pull) + end + end + # Creates a new `Vector` of the given *size* and invokes the given block once # for each index of `self`, assigning the block's value in that index. # @@ -742,6 +759,20 @@ module Apatite::LinearAlgebra io << "}" end + def to_json(json : JSON::Builder) + json.array do + each &.to_json(json) + end + end + + def from_json(string_or_io) + parser = JSON::PullParser.new(string_or_io) + new(parser) do |element| + yield element + end + nil + end + def pretty_print(pp) : Nil pp.list("Vector{", self, "}") end