Added to_json and from_json to Matrix and Vector

This commit is contained in:
Chris Watson 2019-06-17 23:18:45 -07:00
parent 20bd6423d9
commit 442bf3cde3
No known key found for this signature in database
GPG Key ID: 37DAEF5F446370A4
2 changed files with 53 additions and 0 deletions

View File

@ -1,3 +1,4 @@
require "json"
require "./vector" require "./vector"
module Apatite::LinearAlgebra module Apatite::LinearAlgebra
@ -18,6 +19,21 @@ module Apatite::LinearAlgebra
@column_count = column_count || rows[0].size @column_count = column_count || rows[0].size
end 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. # Creates a matrix where each argument is a row.
def self.[](*rows) def self.[](*rows)
rows(rows) rows(rows)
@ -528,6 +544,12 @@ module Apatite::LinearAlgebra
end end
end end
def to_json(json : JSON::Builder)
json.array do
each &.to_json(json)
end
end
@[AlwaysInline] @[AlwaysInline]
def unsafe_fetch(index : Int) def unsafe_fetch(index : Int)
@buffer[index] @buffer[index]

View File

@ -1,3 +1,5 @@
require "json"
module Apatite::LinearAlgebra module Apatite::LinearAlgebra
# Represents a mathematical vector, and also constitutes a row or column # Represents a mathematical vector, and also constitutes a row or column
# of a `Matrix` # of a `Matrix`
@ -75,6 +77,21 @@ module Apatite::LinearAlgebra
end end
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 # 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. # for each index of `self`, assigning the block's value in that index.
# #
@ -742,6 +759,20 @@ module Apatite::LinearAlgebra
io << "}" io << "}"
end 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 def pretty_print(pp) : Nil
pp.list("Vector{", self, "}") pp.list("Vector{", self, "}")
end end