Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion numojo/core/complex/complex_ndarray.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ from utils import Variant

from numojo.core.complex.complex_simd import ComplexSIMD
from numojo.core.datatypes import TypeCoercion, _concise_dtype_str
from numojo.core.flags import Flags
from numojo.core.item import Item
from numojo.core.ndshape import NDArrayShape
from numojo.core.ndstrides import NDArrayStrides
Expand Down Expand Up @@ -78,7 +79,7 @@ struct ComplexNDArray[
"""Size of ComplexNDArray."""
var strides: NDArrayStrides
"""Contains offset, strides."""
var flags: Dict[String, Bool]
var flags: Flags
"Information about the memory layout of the array."

"""LIFETIME METHODS"""
Expand Down
175 changes: 175 additions & 0 deletions numojo/core/flags.mojo
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
# ===----------------------------------------------------------------------=== #
# Distributed under the Apache 2.0 License with LLVM Exceptions.
# See LICENSE and the LLVM License for more information.
# https://github.com/Mojo-Numerics-and-Algorithms-group/NuMojo/blob/main/LICENSE
# https://llvm.org/LICENSE.txt
# ===----------------------------------------------------------------------=== #
"""
Implements Flags type.
"""

from numojo.core.ndshape import NDArrayShape
from numojo.core.ndstrides import NDArrayStrides


@register_passable
struct Flags:
"""
Information about the memory layout of the array.
The Flags object can be accessed dictionary-like.
or by using lowercased attribute names.
Short names are available for convenience when using dictionary-like access.
"""

# attributes
var C_CONTIGUOUS: Bool
"""C_CONTIGUOUS (C): The data is in a C-style contiguous segment."""
var F_CONTIGUOUS: Bool
"""F_CONTIGUOUS (F): The data is in a Fortran-style contiguous segment."""
var OWNDATA: Bool
"""OWNDATA (O): The array owns the underlying data buffer."""
var WRITEABLE: Bool
"""
The data area can be written to.
If it is False, the data is read-only and be blocked from writing.
The WRITEABLE field of a view or slice is inherited from the array where
it is derived. If the parent object is not writeable, the child object is
also not writeable. If the parent object is writeable, the child object may
be not writeable.
"""

# === ---------------------------------------------------------------- === #
# Life cycle dunder methods
# === ---------------------------------------------------------------- === #

fn __init__(
out self,
c_contiguous: Bool,
f_contiguous: Bool,
owndata: Bool,
writeable: Bool,
):
"""
Initializes the Flags object with provided information.

Args:
c_contiguous: The data is in a C-style contiguous segment.
f_contiguous: The data is in a Fortran-style contiguous segment.
owndata: The array owns the underlying data buffer.
writeable: The data area can be written to.
If owndata is False, writeable is forced to be False.
"""

self.C_CONTIGUOUS = c_contiguous
self.F_CONTIGUOUS = f_contiguous
self.OWNDATA = owndata
self.WRITEABLE = writeable and owndata

fn __init__(
out self,
shape: NDArrayShape,
strides: NDArrayStrides,
owndata: Bool,
writeable: Bool,
) raises:
"""
Initializes the Flags object according the shape and strides information.

Args:
shape: The shape of the array.
strides: The strides of the array.
owndata: The array owns the underlying data buffer.
writeable: The data area can be written to.
If owndata is False, writeable is forced to be False.
"""

self.C_CONTIGUOUS = (
True if (strides[-1] == 1) or (shape[-1] == 1) else False
)
self.F_CONTIGUOUS = (
True if (strides[0] == 1) or (shape[0] == 1) else False
)
self.OWNDATA = owndata
self.WRITEABLE = writeable and owndata

fn __init__(
out self,
shape: Tuple[Int, Int],
strides: Tuple[Int, Int],
owndata: Bool,
writeable: Bool,
):
"""
Initializes the Flags object according the shape and strides information.

Args:
shape: The shape of the array.
strides: The strides of the array.
owndata: The array owns the underlying data buffer.
writeable: The data area can be written to.
If owndata is False, writeable is forced to be False.
"""

self.C_CONTIGUOUS = (
True if (strides[1] == 1) or (shape[1] == 1) else False
)
self.F_CONTIGUOUS = (
True if (strides[0] == 1) or (shape[0] == 1) else False
)
self.OWNDATA = owndata
self.WRITEABLE = writeable and owndata

fn __copyinit__(out self, other: Self):
"""
Initializes the Flags object by copying the information from
another Flags object.

Args:
other: The Flags object to copy information from.
"""

self.C_CONTIGUOUS = other.C_CONTIGUOUS
self.F_CONTIGUOUS = other.F_CONTIGUOUS
self.OWNDATA = other.OWNDATA
self.WRITEABLE = other.WRITEABLE

# === ---------------------------------------------------------------- === #
# Get and set dunder methods
# === ---------------------------------------------------------------- === #

fn __getitem__(self, key: String) raises -> Bool:
"""
Get the value of the fields with the given key.
The Flags object can be accessed dictionary-like.
Short names are available for convenience.

Args:
key: The key of the field to get.

Returns:
The value of the field with the given key.
"""
if (
(key != "C_CONTIGUOUS")
and (key != "C")
and (key != "F_CONTIGUOUS")
and (key != "F")
and (key != "OWNDATA")
and (key != "O")
and (key != "WRITEABLE")
and (key != "W")
):
raise Error(
String(
"\nError in `Flags.__getitem__()`: "
"Invalid field name or short name: {}".format(key)
)
)
if (key == "C_CONTIGUOUS") or (key == "C"):
return self.C_CONTIGUOUS
elif (key == "F_CONTIGUOUS") or (key == "F"):
return self.F_CONTIGUOUS
elif (key == "OWNDATA") or (key == "O"):
return self.OWNDATA
else: # (key == "WRITEABLE") or (key == "W")
return self.WRITEABLE
20 changes: 9 additions & 11 deletions numojo/core/matrix.mojo
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
"""

from algorithm import parallelize, vectorize
from collections import Dict
from memory import UnsafePointer, memcpy, memset_zero
from random import random_float64
from sys import simdwidthof
from python import PythonObject, Python

from numojo.core.flags import Flags
from numojo.core.ndarray import NDArray
from numojo.core.own_data import OwnData
from numojo.core.utility import _get_offset, _update_flags
from numojo.core.utility import _get_offset
from numojo.routines.manipulation import broadcast_to

# ===----------------------------------------------------------------------===#
Expand Down Expand Up @@ -102,7 +102,7 @@ struct Matrix[dtype: DType = DType.float64](
var strides: Tuple[Int, Int]
"""Strides of matrix."""

var flags: Dict[String, Bool]
var flags: Flags
"Information about the memory layout of the array."

# ===-------------------------------------------------------------------===#
Expand All @@ -125,10 +125,9 @@ struct Matrix[dtype: DType = DType.float64](
self.strides = (shape[1], 1)
self.size = shape[0] * shape[1]
self._buf = OwnData[dtype](size=self.size)
# Initialize information on memory layout
self.flags = Dict[String, Bool]()
_update_flags(self.flags, self.shape, self.strides)
self.flags["OWNDATA"] = True
self.flags = Flags(
self.shape, self.strides, owndata=True, writeable=True
)

@always_inline("nodebug")
fn __init__(
Expand Down Expand Up @@ -163,10 +162,9 @@ struct Matrix[dtype: DType = DType.float64](

self._buf = OwnData[dtype](self.size)

# Initialize information on memory layout
self.flags = Dict[String, Bool]()
_update_flags(self.flags, self.shape, self.strides)
self.flags["OWNDATA"] = True
self.flags = Flags(
self.shape, self.strides, owndata=True, writeable=True
)

if data.flags["C_CONTIGUOUS"]:
for i in range(data.shape[0]):
Expand Down
Loading