Ok here is how I solved this, I can now easily save my matrices in gforth and then load them back in gforth or even in python in case I wanted to do some stuff like easy graph plotting. I will show both
to begin my matrices are a variable that stores an address on heap so @ will get the address and a second @ get the value. They have a header that is #dimensions,dimsize1,dimsize2,...,dimsizen.
: matrixsave ( var, str -- )
w/o create-file throw dup >r swap dup matrixcellnumber swap dup @ @ rot + 1+ chars/cell * swap @ swap rot write-file r> close-file drop drop
;
This will create a file with the name given by string. Matrixcellnumber is a word I wrote that returns the number of cells excluding the header (which is why we then need the number of dimensions+1 to get the total number of cells). chars/cell is a constant that gives the number of characters per cell. we then write the number of characters that correponds to the size of the matrix to a file. Note this will not be human readable at all!
Opening this file in forth is fairly similar just read in all the chars and save to an allocated memory space.
Using it in python
To use it in python I wrote the following script
char_array = []
with open("matrix.txt","rb") as file:
while 1:
my_char = file.read(8)
if not my_char:
break
char_array.append(my_char)
int_array = np.zeros(len(char_array))
int_array[0] = int.from_bytes(char_array[0],byteorder="little")
print(int_array.shape)
start = 0
dt = np.dtype(float)
dt = dt.newbyteorder('<')
for i in range(0,int(int_array[0]+1)):
int_array[i] = int.from_bytes(char_array[i],byteorder="little")
start += 1
for i in range(start,len(char_array)):
int_array[i] = np.frombuffer(char_array[i],dtype=dt)[0]
sizes = tuple(int_array[1:(int(int_array[0])+1)].astype(int))
float_array = np.reshape(int_array[int(int_array[0]+1):],sizes)
print(float_array)
ok so the name of int array is misleading only the header is ints, the rest of the data is assumed to be floats. So we start by loading in the bytes to "char array", then we read the first integer +1 to which gives us the size of the header. Next we read in the rest of the header. Moving after the start of the header we then read everything else in as floats. Next we want to reshape it to be the dimensions according to the header, work out those sizes, throw away the header and reshape it.
This was all quite a pain to work out so I hope this will be useful for anyone else trying something like this! :)
gforthor File Tutorial and then enter numbers in Forth.