diff --git a/.gitignore b/.gitignore index 1d7d221..1930ded 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ __pycache__ *.pth *.ort -*.config \ No newline at end of file +*.config +*.data +*node_modules** +**out** \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..5a971da --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "format": "c" + } +} \ No newline at end of file diff --git a/README.md b/README.md index f70d063..2aa5608 100644 --- a/README.md +++ b/README.md @@ -3,10 +3,13 @@ A converter and basic tester for rwkv V5 onnx ## supports * fp16, fp32 -* onnx opsversions 15/17/18 +* onnx opsversions 15/17 * file sizes > 2GB * cuda, cpu, tensorRT, mps -## Note: converter requires protobuf 3.20.0 +## Quantization +* Quantize using 'python3 ./quant.py' + +## Note: converter requires protobuf 3.20.2 Install with -`pip install protobuf==3.20.0` +`pip install protobuf==3.20.2` diff --git a/buildcustomopfornumpy.sh b/buildcustomopfornumpy.sh new file mode 100755 index 0000000..7593e9b --- /dev/null +++ b/buildcustomopfornumpy.sh @@ -0,0 +1,31 @@ +SCRIPT=''' +from distutils.core import setup, Extension + + +def configuration(parent_package="", top_path=None): + import numpy + from numpy.distutils.misc_util import Configuration + from numpy.distutils.misc_util import get_info + + #Necessary for the half-float d-type. + info = get_info("npymath") + + config = Configuration("", + parent_package, + top_path) + config.add_extension("wkv5", + ["runexamples/cpp/customkernal/numpy.c"], + extra_info=info, + # march=native, + extra_compile_args=["-march=native"], + ) + + + return config + +if __name__ == "__main__": + from numpy.distutils.core import setup + setup(configuration=configuration) +''' + +python3 -c "$SCRIPT" build_ext --inplace \ No newline at end of file diff --git a/convert.py b/convert.py index bc80840..f16be9c 100644 --- a/convert.py +++ b/convert.py @@ -12,36 +12,36 @@ def __init__(self, w): self.ops = ops self.headsnume, self.headsize = w[f"blocks.0.att.time_decay"].shape - self.postprocess0 = ops.initTensor((w["ln_out.weight"])) - self.postprocess1 = ops.initTensor((w["ln_out.bias"])) - self.postprocess2 = ops.initTensor((w["head.weight"])) + self.postprocess0 = ops.initTensor((w["ln_out.weight"].reshape(1,-1))) + self.postprocess1 = ops.initTensor((w["ln_out.bias"].reshape(1,-1))) + self.postprocess2 = ops.initTensor((w["head.weight"]).t()) self.emb = ops.initTensor(w["emb.weight"]) - self.emb1 = ops.initTensor(w["blocks.0.ln0.weight"]) - self.emb2 = ops.initTensor(w["blocks.0.ln0.bias"]) + self.emb1 = ops.initTensor(w["blocks.0.ln0.weight"].reshape(1,-1)) + self.emb2 = ops.initTensor(w["blocks.0.ln0.bias"].reshape(1,-1)) self.ln1w = (ops.stack( - [w[f"blocks.{x}.ln1.weight"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.ln1.weight"].reshape(1,-1) for x in range(ops.n_layers)])) self.ln1b = (ops.stack( - [w[f"blocks.{x}.ln1.bias"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.ln1.bias"].reshape(1,-1) for x in range(ops.n_layers)])) self.ln2w = (ops.stack( - [w[f"blocks.{x}.ln2.weight"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.ln2.weight"].reshape(1,-1) for x in range(ops.n_layers)])) self.ln2b = (ops.stack( - [w[f"blocks.{x}.ln2.bias"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.ln2.bias"].reshape(1,-1) for x in range(ops.n_layers)])) self.lnxw = (ops.stack( - [w[f"blocks.{x}.att.ln_x.weight"].reshape(self.headsnume,-1) for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.ln_x.weight"].reshape(1,self.headsnume,1,-1) for x in range(ops.n_layers)])) self.lnxb = (ops.stack( - [w[f"blocks.{x}.att.ln_x.bias"].reshape(self.headsnume,-1) for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.ln_x.bias"].reshape(1,self.headsnume,1,-1) for x in range(ops.n_layers)])) self.time_decay = (ops.stack([ - w[f"blocks.{x}.att.time_decay"].double().exp().neg().exp().reshape(self.headsnume,-1,1).repeat(1,1,self.headsize) for x in range(ops.n_layers)], True)) + w[f"blocks.{x}.att.time_decay"].double().exp().neg().exp().reshape(1,self.headsnume,-1,1) for x in range(ops.n_layers)])) self.time_first = (ops.stack([ - w[f"blocks.{x}.att.time_faaaa"].reshape(self.headsnume,-1,1).repeat(1,1,self.headsize) for x in range(ops.n_layers)],True)) + w[f"blocks.{x}.att.time_faaaa"].reshape(1,self.headsnume,-1,1) for x in range(ops.n_layers)])) self.kktk = (ops.stack( - [w[f"blocks.{x}.att.time_mix_k"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.time_mix_k"].reshape(1,-1) for x in range(ops.n_layers)])) self.vvtv = (ops.stack( - [w[f"blocks.{x}.att.time_mix_v"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.time_mix_v"].reshape(1,-1) for x in range(ops.n_layers)])) self.rrtr = (ops.stack( - [w[f"blocks.{x}.att.time_mix_r"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.time_mix_r"].reshape(1,-1) for x in range(ops.n_layers)])) self.ggtg = (ops.stack( - [w[f"blocks.{x}.att.time_mix_g"] for x in range(ops.n_layers)])) + [w[f"blocks.{x}.att.time_mix_g"].reshape(1,-1) for x in range(ops.n_layers)])) self.key = (ops.stack( [w[f"blocks.{x}.att.key.weight"].t() for x in range(ops.n_layers)], exname="_key")) self.value = (ops.stack( @@ -53,9 +53,9 @@ def __init__(self, w): self.outputvv = (ops.stack([ w[f"blocks.{x}.att.output.weight"].t() for x in range(ops.n_layers)], exname="_outputvv")) self.time_mix_k_ffn = (ops.stack([ - w[f"blocks.{x}.ffn.time_mix_k"] for x in range(ops.n_layers)])) + w[f"blocks.{x}.ffn.time_mix_k"].reshape(1,-1) for x in range(ops.n_layers)])) self.time_mix_r_ffn = (ops.stack([ - w[f"blocks.{x}.ffn.time_mix_r"] for x in range(ops.n_layers)])) + w[f"blocks.{x}.ffn.time_mix_r"].reshape(1,-1) for x in range(ops.n_layers)])) self.key_ffn = (ops.stack( [w[f"blocks.{x}.ffn.key.weight"].t() for x in range(ops.n_layers)], exname="_key_ffn")) self.receptance_ffn = (ops.stack([ @@ -89,32 +89,23 @@ def wkv5(self, k,v, r, xx, state): td = self.time_decay[xx] tf = self.time_first[xx] - kreshaped = ops.reshape(k, self.ops.kshape) - vreshaped = ops.reshape(v, self.ops.vshape) - rreshaped = ops.reshape(r, self.ops.rshape) - - kv = ops.matvec(kreshaped, vreshaped) - kkv = ops.multiply(kv, tf) - premat = ops.add(kkv, state) - wkv = ops.matvec(rreshaped, premat) - state = ops.multiply(state, td) - state = ops.add(state, kv) - - return wkv, state + + + return self.ops.wkv5op(k, v, r, td, tf, state) @ops.layerdef def doLayer(self, x, statea, stateb, statec, xx): - xy = ops.layernorm(x, self.ln1w[xx], self.ln1b[xx]) + xy = ops.layernorm(x, self.ln1w[xx], self.ln1b[xx], statea+"out") k = ops.matvec( - ops.lerp(statea, xy, self.kktk[xx]),self.key[xx], True) + ops.lerp(statea, xy, self.kktk[xx]),self.key[xx]) v = ops.matvec(ops.lerp( - statea, xy, self.vvtv[xx]),self.value[xx], True) + statea, xy, self.vvtv[xx]),self.value[xx]) rr = ops.matvec(ops.lerp(statea, xy, self.rrtr[xx]), - self.receptance[xx], True) + self.receptance[xx]) g = ops.matvec( ops.lerp(statea, xy, self.ggtg[xx]),self.gate[xx]) @@ -130,14 +121,15 @@ def doLayer(self, x, statea, stateb, statec, xx): # x = self.output(x * g) lnx = ops.groupnorm(wkv8, self.lnxw[xx], self.lnxb[xx]) - lnxo = ops.reshape(lnx, self.ops.normshape) - mvvo = ops.matvec(ops.multiply(gg, lnxo), + gm = ops.multiply(gg, lnx, f"gateXgroupnorm-Layer{xx}") + + mvvo = ops.matvec(gm, self.outputvv[xx]) mvv = ops.add(mvvo, x) - ddd = ops.layernorm(mvv, self.ln2w[xx], self.ln2b[xx]) + ddd = ops.layernorm(mvv, self.ln2w[xx], self.ln2b[xx], stateb+"out") kml = ops.lerp( stateb, ddd, self.time_mix_k_ffn[xx]) @@ -181,8 +173,8 @@ def forward(self, x, state = None, statec = None): x, ops.convertToFloat16(statea[i]), ops.convertToFloat16(stateb[i]),ops.convertToFloat32(statec[i]), i) ot = ot + ([ops.convertToFloat32(aaa),ops.convertToFloat32(bbb)]) ot2 = ot2 + [ops.convertToFloat32(ccc)] - x = ops.matvec(self.postprocess2,ops.layernorm(x, self.postprocess0, - self.postprocess1)) + x = ops.matvec(ops.layernorm(x, self.postprocess0, + self.postprocess1),self.postprocess2) return ops.convertToFloat32(x), ot, ot2 @@ -196,9 +188,9 @@ def forward(self, x, state = None, statec = None): def convert_model(path, dtype): #delete all .onnx and .bin files import os - for file in os.listdir("."): - if file.endswith(".onnx") or file.endswith(".bin"): - os.remove(file) + # for file in os.listdir("."): + # if file.endswith(".onnx") or file.endswith(".bin"): + # os.remove(file) w = torch.load(path, map_location="cpu") dims = len(w["blocks.0.att.key.weight"]) headsnume, headsize = w[f"blocks.0.att.time_decay"].shape @@ -206,7 +198,7 @@ def convert_model(path, dtype): list(filter(lambda x: "blocks" in x and "ln1.bias" in x, w.keys()))) - ops = opslist.RWKVOnnxOps(layers,dims,dtype=dtype, opsVersion=version.get(), externalData=use_external_data.get(), splitExternalData=splitExternalData.get(), fp32inout=fp32inout.get(), quantized=mybits.get()==8, heads=headsnume) + ops = opslist.RWKVOnnxOps(layers,dims,dtype=dtype, opsVersion=version.get(), externalData=use_external_data.get(), splitExternalData=splitExternalData.get(), fp32inout=fp32inout.get(), quantized=mybits.get()==8, heads=headsnume, useCustomOperator=useCustomOp.get()) RnnRWKV(ops,w) @@ -232,10 +224,12 @@ def convert(): # Define the variables input_path = tk.StringVar() -mybits = tk.IntVar(value=8) +mybits = tk.IntVar(value=32) use_external_data = tk.BooleanVar(value=True) splitExternalData = tk.BooleanVar(value=False) fp32inout = tk.BooleanVar(value=False) +useCustomOp = tk.BooleanVar(value=False) + # version, number either 15/17 version = tk.IntVar(value=15) @@ -248,11 +242,12 @@ def convert(): -bits = tk.OptionMenu(root, mybits, 8, 16, 32) +bits = tk.OptionMenu(root, mybits, 16, 32) check_button3 = tk.Checkbutton(root, text="External Data", variable=use_external_data) check_button4 = tk.Checkbutton(root, text="Split External Data", variable=splitExternalData) check_button5 = tk.Checkbutton(root, text="Float32 inputs/outputs", variable=fp32inout) -input_select = tk.OptionMenu(root, version, 15, 17, 18) +check_button6 = tk.Checkbutton(root, text="Use Custom Op", variable=useCustomOp) +input_select = tk.OptionMenu(root, version, 15, 17, 19) convert_button = tk.Button(root, text="Convert", command=convert) @@ -262,11 +257,13 @@ def convert(): input_entry.grid(row=0, column=1) input_button.grid(row=0, column=2) + bits.grid(row=2, column=0) bitlabel.grid(row=2, column=1) check_button3.grid(row=2, column=2) check_button4.grid(row=2, column=3) check_button5.grid(row=2, column=4) +check_button6.grid(row=2, column=5) opsetlabel.grid(row=3, column=0) input_select.grid(row=3, column=1) diff --git a/customoptools/customop.py b/customoptools/customop.py new file mode 100644 index 0000000..444996d --- /dev/null +++ b/customoptools/customop.py @@ -0,0 +1,22 @@ +from onnxruntime_extensions import ( + onnx_op, PyOp, make_onnx_model, + get_library_path as _get_library_path) + +# register custom op for domain recursal.rwkv + +import wkv5 as customOP + +@onnx_op(op_type="wkv5", + inputs=[ + PyOp.dt_float, + PyOp.dt_float, + PyOp.dt_float, + PyOp.dt_float, + PyOp.dt_float, + PyOp.dt_float], + outputs=[PyOp.dt_float, PyOp.dt_float] + ) +def wkv5(k, v, r, td, tf, state): + + ro, newstate = customOP.wkv5(k, v, r, td, tf, state) + return ro, newstate \ No newline at end of file diff --git a/customoptools/helper.py b/customoptools/helper.py new file mode 100644 index 0000000..8d76b9b --- /dev/null +++ b/customoptools/helper.py @@ -0,0 +1,43 @@ + +def FixCustomModel(filepath): + import onnx + # load model even with external data + file = filepath + model = onnx.load(file, load_external_data=True) + # set imports to custom op "ai.onnx.contrib" + nodes = model.graph.node + + change = False + # get type of node + for i in range(len(nodes)): + if "wkv5" in nodes[i].op_type: + if(model.opset_import[0].domain != "ai.onnx.contrib"): + model.opset_import[0].domain = "ai.onnx.contrib" + + change = True + # set import to custom op + model.graph.node[i].domain = "ai.onnx.contrib" + + if change: + onnx.save_model(model, filepath, save_as_external_data=True, location=file.replace(".onnx", ".bin")) + +def ScrubCustomModel(filepath): + import onnx + # load model even with external data + file = filepath + model = onnx.load(file, load_external_data=True) + + # set domain to default + model.opset_import[0].domain = "ai.onnx" + + nodes = model.graph.node + change = False + # get type of node + for i in range(len(nodes)): + if "wkv5" in nodes[i].op_type: + # set import to custom op + change = True + model.graph.node[i].domain = "" + + if change: + onnx.save_model(model, filepath, save_as_external_data=True, location=file.replace(".onnx", ".bin")) \ No newline at end of file diff --git a/opslist.py b/opslist.py index e708d24..b8969cb 100644 --- a/opslist.py +++ b/opslist.py @@ -3,7 +3,7 @@ class RWKVOnnxOps(): - def __init__(self, layers, embed, opsVersion = 15, externalData = True, splitExternalData = False,fp32inout=True, quantized = False, *args, dtype=None, heads=32, **kwargs): + def __init__(self, layers, embed, opsVersion = 15, externalData = True, splitExternalData = True,fp32inout=True, quantized = False, *args, dtype=None, heads=32, useCustomOperator=True, **kwargs): import onnx self.n_layers = layers self.n_embed = embed @@ -14,8 +14,8 @@ def __init__(self, layers, embed, opsVersion = 15, externalData = True, splitExt nptype = np.float32 if dtype == onnx.TensorProto.FLOAT else np.float16 if dtype == onnx.TensorProto.FLOAT16 else np.float16 if dtype == onnx.TensorProto.BFLOAT16 else np.float32 self.nm = 0 - exportname = f"RWKV_{layers}_{embed}_{'32' if dtype == onnx.TensorProto.FLOAT else '16'}_{opsVersion}.onnx" - externalname = f"RWKV_{layers}_{embed}_{'32' if dtype == onnx.TensorProto.FLOAT else '16'}_{opsVersion}" + exportname = f"RWKV_{layers}_{embed}_{'32' if dtype == onnx.TensorProto.FLOAT else '16'}_{opsVersion}{'_custom' if useCustomOperator else ''}.onnx" + externalname = f"RWKV_{layers}_{embed}_{'32' if dtype == onnx.TensorProto.FLOAT else '16'}_{opsVersion}{'_custom' if useCustomOperator else ''}" # remove old files import os @@ -37,7 +37,7 @@ def initTensor(x, isfp32 = False, exname = ""): if isinstance(x, list): xx = np.array(x).astype(npdtype) else: - xx = x.squeeze().float().cpu().numpy() + xx = x.float().cpu().numpy() # convert to float32 xx = xx.astype(npdtype) rrx = onnx.helper.make_tensor( @@ -150,7 +150,7 @@ def mean(x, dim=None): dim = self.zeroInt name = f"mean_{self.nm}_out" self.nm += 1 - if opsVersion == 18: + if opsVersion >= 18: node = onnx.helper.make_node( 'ReduceMean', @@ -177,6 +177,10 @@ def mean(x, dim=None): def meanvarnorm(x, dim=None): if dim == None: dim = self.zeroInt + + if dtype == onnx.TensorProto.FLOAT16: + x = convertToFloat32(x) + name = f"meanvarnorm_{self.nm}_out" self.nm += 1 node = onnx.helper.make_node( @@ -184,10 +188,11 @@ def meanvarnorm(x, dim=None): inputs=[x], outputs=[name], axes=dim, - keepdims=1 + ) self.NodeList.append(node) - + if dtype == onnx.TensorProto.FLOAT16: + name = convertToFloat16(name) return name self.meanvarnorm = meanvarnorm @@ -227,7 +232,6 @@ def stack(x, fp32 = False, exname = ""): def matvec(x, y, outputfp32 = False): name = f"matvec_{self.nm}_out" - oname = f"matvec_g_{self.nm}_out" self.nm += 1 node = onnx.helper.make_node( 'MatMul', @@ -261,11 +265,12 @@ def prod(x): self.prod = prod - def mul(x, y): + def mul(x, y, opname=""): name = f"mul_{self.nm}_out" self.nm += 1 node = onnx.helper.make_node( 'Mul', + name=opname, inputs=[x, y], outputs=[name] ) @@ -275,21 +280,11 @@ def mul(x, y): self.multiply = mul - def squeeze(x): - name = f"squeeze_{self.nm}_out" - self.nm += 1 - node = onnx.helper.make_node( - 'Squeeze', - inputs=[x], - outputs=[name] - ) - self.NodeList.append(node) - return name - def add(x, y): + def add(x, y, newName = None): - name = f"add_{self.nm}_out" + name = f"add_{self.nm}_out" if newName == None else newName self.nm += 1 node = onnx.helper.make_node( 'Add', @@ -375,8 +370,8 @@ def divide(x, y): self.divide = divide - def layernorm17(x, w, b): - name = f"layernorm_{self.nm}_out" + def layernorm17(x, w, b, newName = None): + name = f"layernorm_{self.nm}_out" if newName == None else newName self.nm += 1 node = onnx.helper.make_node( 'LayerNormalization', @@ -388,21 +383,31 @@ def layernorm17(x, w, b): return name # ort 15 does not support layernorm - def layernorm(x, w, b): - xee2 = self.subtract(x,self.mean(x)) - x2 = self.add(self.sqrt(self.add(self.mean(self.multiply(xee2,xee2)), self.margins16)), self.margins16) - return self.add(self.multiply(w, self.divide(xee2, x2)), b) + def layernorm(x, w, b, newName = None): + # xee2 = self.subtract(x,self.mean(x)) + # x2 = self.add(self.sqrt(self.add(self.mean(self.multiply(xee2,xee2)), self.margins16)), self.margins16) + # xo = self.divide(xee2, x2) + + xo = self.meanvarnorm(x) + + return self.add(self.multiply(w, xo), b, newName) - self.layernorm = layernorm if opsVersion != 17 else layernorm17 + self.layernorm = layernorm if opsVersion < 17 else layernorm17 def groupnorm(x, w, b): - x = self.reshape(x, self.premshape) - xee2 = self.subtract(x,self.mean(x,self.oneInt)) - x2 = self.add(self.sqrt(self.add(self.mean(self.multiply(xee2,xee2),self.oneInt), self.margins32)), self.margins32) - return self.add(self.multiply(w, self.divide(xee2, x2)), b) + # xee2 = self.subtract(x,self.mean(x,self.oneInt)) + # x2 = self.add(self.sqrt(self.add(self.mean(self.multiply(xee2,xee2),self.oneInt), self.margins32)), self.margins32) + # lnx = self.divide(xee2, x2) + lnx = self.meanvarnorm(x, self.oneInt) + xo = self.add(self.multiply(w, lnx), b) + xo = self.reshape(xo, self.normalshape) + return xo def groupnorm18(x, w, b): + + x = self.reshape(x, self.normshape) + name = f"groupnorm_{self.nm}_out" self.nm += 1 node = onnx.helper.make_node( @@ -412,11 +417,14 @@ def groupnorm18(x, w, b): num_groups=heads ) self.NodeList.append(node) + name = self.reshape(name, self.normalshape) return name - self.groupnorm = groupnorm + self.groupnorm = groupnorm if opsVersion != 18 else groupnorm18 + + def getIndex(x, y): name = f"getIndex_{self.nm}_out" @@ -428,7 +436,41 @@ def getIndex(x, y): ) self.NodeList.append(node) - return squeeze(name) + return name + + def wkv5(k, v, r, td, tf, state): + name = f"getIndex_{self.nm}_out" + stateout = state+"out" + self.nm += 1 + node = onnx.helper.make_node( + 'wkv5', + inputs=[k, v, r, td, tf, state], + outputs=[name, stateout], + **dict( + domain="ai.onnx.contrib" + ) if useCustomOperator else dict( + ) + ) + self.NodeList.append(node) + + return name, stateout + + def wkv5compat(k, v, r, td, tf, state): + kreshaped = self.reshape(k, self.kshape) + vreshaped = self.reshape(v, self.vshape) + rreshaped = self.reshape(r, self.rshape) + + kv = self.matvec(kreshaped, vreshaped) + kkv = self.multiply(kv, tf) + premat = self.add(kkv, state) + wkv = self.matvec(rreshaped, premat) + + state2 = self.multiply(state, td) + state3 = self.add(state2, kv, state+"out") + + return wkv, state3 + + self.wkv5op = wkv5 if useCustomOperator else wkv5compat self.stackEmbed = False @@ -478,14 +520,18 @@ def reshape(x, y): self.reshape = reshape - self.kshape = initIntTensor([heads, embed//heads, 1]) - self.vshape = initIntTensor([heads, 1, embed//heads]) - self.rshape = initIntTensor([heads, 1, embed//heads]) - self.normshape = initIntTensor([heads * embed//heads]) - self.zeroInt = initIntTensor([0]) if opsVersion == 18 else [0] - self.oneInt = initIntTensor([1]) if opsVersion == 18 else [1] - self.eight = initTensor([8.0]) - self.premshape = initIntTensor([heads, embed//heads]) + self.kshape = initIntTensor([-1,heads, embed//heads, 1]) + self.vshape = initIntTensor([-1,heads, 1, embed//heads]) + self.rshape = initIntTensor([-1, heads, 1, embed//heads]) + self.postwkvop = initIntTensor([-1, heads, embed//heads, embed//heads]) + self.prematshape = initIntTensor([-1, embed//heads, embed//heads]) + self.normshape = initIntTensor([-1, heads, embed//heads]) + self.normalshape = initIntTensor([-1, embed]) + self.pregnshape = initIntTensor([-1, heads, embed//heads]) + self.zeroInt = initIntTensor([1]) if opsVersion == 18 else [1] + self.oneInt = initIntTensor([3]) if opsVersion == 18 else [3] + self.eight = initTensor([[8.0]]) + self.premshape = initIntTensor([-1, heads, embed//heads]) def maximum(x, y): name = f"maximum_{self.nm}_out" @@ -504,12 +550,12 @@ def maximum(x, y): self.getIndex = getIndex # convert to float32 - self.emptyState = np.array((([[0.00]*embed, [0.00]*embed]))*layers) + self.emptyState = np.array((([[[0.00]*embed]*1, [[0.00]*embed]*1]))*layers) self.emptyState = np.array(self.emptyState) # emptwkv state is n_layers,32,64,64 hs = embed//heads - self.emptyWkvState = np.array(([[[[0.0]*hs]*hs]*heads]*layers)) + self.emptyWkvState = np.array(([1*[[[[0.0]*hs]*hs]*heads]]*layers)) if dtype == onnx.TensorProto.FLOAT16 and not fp32inout: self.emptyState = self.emptyState.astype(np.float16) @@ -521,14 +567,14 @@ def ppm(x): import onnx inputtensor = onnx.helper.make_tensor_value_info("input0", onnx.TensorProto.INT32, - [1]), "input0" + [-1]), "input0" - emptyState = list(map(lambda x: (onnx.helper.make_tensor_value_info("instate"+str(x), + emptyState = list(map(lambda x: (onnx.helper.make_tensor_value_info("state"+str(x), onnx.TensorProto.FLOAT if fp32inout else dtype, - [embed]), "instate"+str(x)), range((2)*layers))) - emptystate2 = list(map(lambda x: (onnx.helper.make_tensor_value_info("instatewkv"+str(x), + [-1,embed]), "state"+str(x)), range((2)*layers))) + emptystate2 = list(map(lambda x: (onnx.helper.make_tensor_value_info("statewkv"+str(x), onnx.TensorProto.FLOAT if fp32inout else dtype, - [heads, hs, hs]), "instatewkv"+str(x)), range(layers))) + [-1,heads, hs, hs]), "statewkv"+str(x)), range(layers))) outs = x.forward( inputtensor[1], list(map(lambda x: x[1], emptyState)), list(map(lambda x: x[1], emptystate2))) print(self.TensorList.__len__()) @@ -536,13 +582,13 @@ def ppm(x): print(outs) logits = onnx.helper.make_tensor_value_info(outs[0], onnx.TensorProto.FLOAT if fp32inout else dtype, - [65536]) + [-1,65536]) state = list(map(lambda x: onnx.helper.make_tensor_value_info(x, onnx.TensorProto.FLOAT if fp32inout else dtype, - [embed]), outs[1])) + [-1, embed]), outs[1])) state2 = list(map(lambda x: onnx.helper.make_tensor_value_info(x, onnx.TensorProto.FLOAT if fp32inout else dtype, - [heads, hs, hs]), outs[2])) + [-1, heads, hs, hs]), outs[2])) # Create the graph (GraphProto) graph_def = onnx.helper.make_graph( @@ -566,8 +612,11 @@ def ppm(x): modelDef = onnx.helper.make_model( graph_def, producer_name="rwkvstic", - - + **dict( + opset_imports=[onnx.helper.make_opsetid("ai.onnx.contrib", opsVersion)]) + if useCustomOperator else + dict( + ) ) @@ -579,25 +628,17 @@ def ppm(x): onnx.save(modelDef, exportname) del modelDef + + if(not useCustomOperator): + onnx.checker.check_model(exportname) + onnx.shape_inference.infer_shapes_path(exportname, check_type=True, strict_mode=True, data_prop=True) - onnx.checker.check_model(exportname) - onnx.shape_inference.infer_shapes_path(exportname, check_type=True, strict_mode=True) - - if quantized: - import onnx - from onnxruntime.quantization import quantize_dynamic, QuantType - model_fp32 = exportname - model_quant = "quantized_"+exportname - try: - quantized_model = quantize_dynamic(model_fp32, model_quant, per_channel=True, reduce_range=True, use_external_data_format=True) - import os - os.remove(model_fp32) - os.rename(model_quant, model_fp32) - os.remove(externalname+".bin") - except: - print("Quantization failed, chase this line and update the above code to use external data(if you are using a model more than 1b5)") - exit() + + else: + print("skipping model checking") + + # run model print("Model saved to: ", exportname, " and is ready to be run") print("Data type: ", dtype) diff --git a/quant.py b/quant.py index f8740bc..a0e7f65 100644 --- a/quant.py +++ b/quant.py @@ -1,4 +1,43 @@ # for use if the converter crashes before quantization + + import onnx from onnxruntime.quantization import quantize_dynamic, QuantType -quantize_dynamic("RWKV_32_2560_32_15.onnx","RWKV_32_2560_32_15_quant.onnx", per_channel=True, reduce_range=True, use_external_data_format=True) \ No newline at end of file +import customoptools.helper as helper +import os +files = [f for f in os.listdir('.') if os.path.isfile(f)] +files = [f for f in files if f.endswith(".onnx") or f.endswith(".ort")] +import inquirer +model = inquirer.list_input("Select model", choices=files) + +choices = inquirer.checkbox( + "Select quantization options (use space bar to select checkboxes)", choices=["per_channel(slow, more acurate)", "reduce_range(sometimes more accurate)", "use_external_data_format(use if model larger than 2B)"], default=["use_external_data_format(use if model larger than 2B)"]) + +reduce_range = False +per_channel = False +use_external_data_format = False +if "per_channel(slow, more acurate)" in choices: + per_channel = True +if "reduce_range(sometimes more accurate)" in choices: + reduce_range = True +if "use_external_data_format(use if model larger than 2B)" in choices: + use_external_data_format = True + +# choose quantization type (default is QUInt8) // choose 1 +qtype = inquirer.list_input("Select quantization type", choices=[e for e in QuantType], default=QuantType.QUInt8.value ) +qtype = QuantType(qtype) +endoption = f'_{qtype}-{"pc" if per_channel else "npc"}-{"rr" if reduce_range else "norr"}-{"ext" if use_external_data_format else "noext"}.onnx' + +# load custom op +helper.ScrubCustomModel(model) +quantize_dynamic(model,model.replace(".onnx",endoption), per_channel=per_channel, reduce_range=reduce_range, use_external_data_format=use_external_data_format, weight_type=qtype, + op_types_to_quantize=[ + # matmul only + "MatMul", + ], + extra_options={ + + } + ) + +helper.FixCustomModel(model.replace(".onnx",endoption)) \ No newline at end of file diff --git a/runexamples/cpp/.vscode/launch.json b/runexamples/cpp/.vscode/launch.json new file mode 100644 index 0000000..d9b50c5 --- /dev/null +++ b/runexamples/cpp/.vscode/launch.json @@ -0,0 +1,33 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "(gdb) Launch", + "type": "cppdbg", + "request": "launch", + "program": "${workspaceFolder}/out/test", + "args": [], + "stopAtEntry": false, + "cwd": "${workspaceFolder}/out/", + "environment": [], + "externalConsole": false, + "MIMode": "gdb", + "setupCommands": [ + { + "description": "Enable pretty-printing for gdb", + "text": "-enable-pretty-printing", + "ignoreFailures": true + }, + { + "description": "Set Disassembly Flavor to Intel", + "text": "-gdb-set disassembly-flavor intel", + "ignoreFailures": true + } + ] + } + + ] +} \ No newline at end of file diff --git a/runexamples/cpp/build.sh b/runexamples/cpp/build.sh new file mode 100755 index 0000000..f680647 --- /dev/null +++ b/runexamples/cpp/build.sh @@ -0,0 +1,10 @@ +# if out/ does not exist, create it +if [ ! -d "out/" ]; then + mkdir out +fi +# copy the shared library to out/ +cp ./onnx/lib/libonnxruntime.so.1.16.2 out/ +cp ./tokenizer/rwkv_vocab_v20230424.txt out/ + +# compile the test.cpp file, linking the shared library, and setting the LD_LIBRARY_PATH to the same directory as the executable +g++ -std=c++17 -g ./test.cpp ./onnx/lib/libonnxruntime.so -o ./out/RWKV-StoryGenOnnx -I./onnx/include -I./include -L./onnx/lib -l:libonnxruntime.so.1.16.2 -Wl,-rpath=./ diff --git a/runexamples/cpp/customkernal/kernal.h b/runexamples/cpp/customkernal/kernal.h new file mode 100644 index 0000000..5a3e594 --- /dev/null +++ b/runexamples/cpp/customkernal/kernal.h @@ -0,0 +1,149 @@ +#define longint long +// simd +#ifdef __AVX512F__ // This macro is defined if AVX-512 is supported + #include + #define VALUE __m512 + #define SIMD_WIDTH 16 + #define LOAD(x) _mm512_load_ps(x) + #define STORE(x, y) _mm512_store_ps(x, y) + #define SET1(x) _mm512_set1_ps(x) + #define MULTIPLY(x, y) _mm512_mul_ps(x, y) + #define MULTADD(x, y, z) _mm512_fmadd_ps(x, y, z) + // print out the SIMD width + #pragma message("AVX-512 is supported") +#else + // Fallback to AVX2 if AVX-512 is not supported + #ifdef __AVX2__ + #include + #define VALUE __m256 + #define SIMD_WIDTH 8 + #define LOAD(x) _mm256_load_ps(x) + #define STORE(x, y) _mm256_store_ps(x, y) + #define SET1(x) _mm256_set1_ps(x) + #define MULTIPLY(x, y) _mm256_mul_ps(x, y) + #define MULTADD(x, y, z) _mm256_fmadd_ps(x, y, z) + // print out the SIMD width + #pragma message("AVX-2 is supported") + + #else + #if defined(__ARM_NEON) || defined(__ARM_NEON__) + #include + #define VALUE float32x4_t + #define SIMD_WIDTH 4 // NEON typically operates on 128-bit registers (4 floats) + #define LOAD(x) vld1q_f32(x) + #define STORE(x, y) vst1q_f32(x, y) + #define SET1(x) vdupq_n_f32(x) + #define MULTIPLY(x, y) vmulq_f32(x, y) + #define MULTADD(x, y, z) vmlaq_f32(z, x, y) + // Print out the SIMD width + #pragma message("ARM NEON is supported") + #else + #pragma message("No SIMD is supported") + #define VALUE float + #define SIMD_WIDTH 1 + #define LOAD(x) (x)[0] + #define STORE(x, y) (x)[0] = y + #define SET1(x) x + #define MULTIPLY(x, y) x * y + #define MULTADD(x, y, z) x * y + z + #endif + + #endif + +#endif + + +void forward_cpu(longint B, longint T, longint C, longint H, float* ss, float* rr, float* kk, float* vv, float* ww, float* uu, float* out) { + + + + // 1d tensor + longint tsize = B*H*(C/H); + // 2d tensor + longint ttsize = B*H*(C/H)*(C/H); + + // 1d + longint bsize = H*(C/H); + // 2d + longint bbsize = H*(C/H)*(C/H); + + // 1d + longint hsize = (C/H); + // 2d + longint hhsize = (C/H)*(C/H); + + for (longint t = 0; t < T; t++) { + + longint timeoffset = t * tsize; + + for (longint bb = 0; bb < B; bb++) { + + + longint btimeoffset = timeoffset + bb * bsize; + longint bbhsize = bb * bbsize; + + for (longint hh = 0; hh < H; hh++) { + longint hoffset = hh * hsize; + longint bhofseti = btimeoffset + hoffset; + longint bbhhsize = bbhsize + hh * hhsize; + + for (longint i = 0; i < C/H; i++) { + + longint iind = bhofseti + i; + longint hoffseti = hoffset + i; + longint bbhhofseti = bbhhsize + i * hsize; + + //auto kkk = kk[iind]; + VALUE kkk = SET1(kk[iind]); + VALUE uuu = SET1(uu[hoffseti]); + VALUE rrr = SET1(rr[iind]); + VALUE www = SET1(ww[hoffseti]); + + + + + for (longint j = 0; j < C/H; j+=SIMD_WIDTH) { + longint jind = bhofseti + j; + longint sind = bbhhofseti + j; + + + + // atu = k[t,bb,hh,i]*v[t,bb,hh,j] + VALUE vvv = LOAD(&vv[jind]); + + // multiply kkk and vvv + VALUE atu = MULTIPLY(vvv,kkk); + + VALUE sss = LOAD(&ss[sind]); + + // out[t,bb,hh,j] += r[t,bb,hh,i]*(s[bb,hh,i,j] + atu*u[hh,i] ) + VALUE sssatuuuu = MULTADD(atu,uuu,sss); + + VALUE outtt = LOAD(&out[jind]); + + printf("Batch: %ld\n", i); + + STORE(&out[jind], MULTADD(sssatuuuu,rrr,outtt)); + + // s[bb,hh,i,j] = s[bb,hh,i,j] * w[hh,i] + atu + STORE(&ss[sind], MULTADD(sss,www,atu)); + } + + } + } + } + } + + +} + + + +// PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { +// m.def("forward_cpu", &forward_cpu, "CPU forward"); +// } + +// TORCH_LIBRARY(wkv5, m) { +// m.def("forward_cpu", forward_cpu); +// } + diff --git a/runexamples/cpp/customkernal/numpy.c b/runexamples/cpp/customkernal/numpy.c new file mode 100644 index 0000000..eb2e3cb --- /dev/null +++ b/runexamples/cpp/customkernal/numpy.c @@ -0,0 +1,254 @@ +#define longint long +// simd +#ifdef __AVX512F__ // This macro is defined if AVX-512 is supported + #include + #define VALUE __m512 + #define SIMD_WIDTH 16 + #define LOAD(x) _mm512_loadu_ps(x) + #define STORE(x, y) _mm512_storeu_ps(x, y) + #define SET1(x) _mm512_set1_ps(x) + #define MULTIPLY(x, y) _mm512_mul_ps(x, y) + #define MULTADD(x, y, z) _mm512_fmadd_ps(x, y, z) + // print out the SIMD width + #pragma message("AVX-512 is supported") +#else + // Fallback to AVX2 if AVX-512 is not supported + #ifdef __AVX2__ + #include + #define VALUE __m256 + #define SIMD_WIDTH 8 + #define LOAD(x) _mm256_load_ps(x) + #define STORE(x, y) _mm256_store_ps(x, y) + #define SET1(x) _mm256_set1_ps(x) + #define MULTIPLY(x, y) _mm256_mul_ps(x, y) + #define MULTADD(x, y, z) _mm256_fmadd_ps(x, y, z) + // print out the SIMD width + #pragma message("AVX-2 is supported") + + #else + #if defined(__ARM_NEON) || defined(__ARM_NEON__) + #include + #define VALUE float32x4_t + #define SIMD_WIDTH 4 // NEON typically operates on 128-bit registers (4 floats) + #define LOAD(x) vld1q_f32(x) + #define STORE(x, y) vst1q_f32(x, y) + #define SET1(x) vdupq_n_f32(x) + #define MULTIPLY(x, y) vmulq_f32(x, y) + #define MULTADD(x, y, z) vmlaq_f32(z, x, y) + // Print out the SIMD width + #pragma message("ARM NEON is supported") + #else + #pragma message("No SIMD is supported") + #define VALUE float + #define SIMD_WIDTH 1 + #define LOAD(x) (x)[0] + #define STORE(x, y) (x)[0] = y + #define SET1(x) x + #define MULTIPLY(x, y) x * y + #define MULTADD(x, y, z) x * y + z + #endif + + #endif + +#endif + + +void forward_cpu(longint B, longint T, longint C, longint H, float* ss, float* rr, float* kk, float* vv, float* ww, float* uu, float* out) { + + + + // 1d tensor + longint tsize = B*H*(C/H); + // 2d tensor + longint ttsize = B*H*(C/H)*(C/H); + + // 1d + longint bsize = H*(C/H); + // 2d + longint bbsize = H*(C/H)*(C/H); + + // 1d + longint hsize = (C/H); + // 2d + longint hhsize = (C/H)*(C/H); + + for (longint t = 0; t < T; t++) { + + longint timeoffset = t * tsize; + + for (longint bb = 0; bb < B; bb++) { + + + longint btimeoffset = timeoffset + bb * bsize; + longint bbhsize = bb * bbsize; + + for (longint hh = 0; hh < H; hh++) { + longint hoffset = hh * hsize; + longint bhofseti = btimeoffset + hoffset; + longint bbhhsize = bbhsize + hh * hhsize; + + for (longint i = 0; i < C/H; i++) { + + longint iind = bhofseti + i; + longint hoffseti = hoffset + i; + longint bbhhofseti = bbhhsize + i * hsize; + + //auto kkk = kk[iind]; + VALUE kkk = SET1(kk[iind]); + VALUE uuu = SET1(uu[hoffseti]); + VALUE rrr = SET1(rr[iind]); + VALUE www = SET1(ww[hoffseti]); + + + + + for (longint j = 0; j < C/H; j+=SIMD_WIDTH) { + longint jind = bhofseti + j; + longint sind = bbhhofseti + j; + + + + // atu = k[t,bb,hh,i]*v[t,bb,hh,j] + VALUE vvv = LOAD(&vv[jind]); + + // multiply kkk and vvv + VALUE atu = MULTIPLY(vvv,kkk); + + + + VALUE sss = LOAD(&ss[sind]); + + + // out[t,bb,hh,j] += r[t,bb,hh,i]*(s[bb,hh,i,j] + atu*u[hh,i] ) + VALUE sssatuuuu = MULTADD(atu,uuu,sss); + + VALUE outtt = LOAD(&out[jind]); + + STORE(&out[jind], MULTADD(sssatuuuu,rrr,outtt)); + + // s[bb,hh,i,j] = s[bb,hh,i,j] * w[hh,i] + atu + STORE(&ss[sind], MULTADD(sss,www,atu)); + } + + } + } + } + } + + +} + + +#include +#include +#include "numpy/ndarraytypes.h" +#include "numpy/ufuncobject.h" +#include "numpy/npy_3kcompat.h" + +// Module method definitions +static PyObject* wkvworld_c(PyObject *self, PyObject *args) { + + Py_RETURN_NONE; +} + + +static PyObject* wkvnumpy_c(PyObject *dummy, PyObject *args) +{ + + PyObject *KK=NULL; + PyObject *VV=NULL; + PyObject *RR=NULL; + PyObject *TD=NULL; + PyObject *TF=NULL; + PyObject *STATE=NULL; + + int nd; + + if (!PyArg_ParseTuple(args, "OOOOOO", &KK, &VV, &RR, &TD, &TF, &STATE)) + return NULL; + + /* + * my code starts here + */ + + npy_intp *sp=PyArray_SHAPE(STATE); + + long Batch = sp[0]; + long Time = 1; + long Head = sp[1]; + long Headsize = sp[2]; + long Channel = Head * Headsize; + + // asume rank 4 + // printf("array dimentsion: %ld %ld %ld %ld\n",*sp, *(sp+1), *(sp+2), *(sp+3)); + + float* ss = (float*)PyArray_DATA(STATE); + float* rr = (float*)PyArray_DATA(RR); + float* kk = (float*)PyArray_DATA(KK); + float* vv = (float*)PyArray_DATA(VV); + float* td = (float*)PyArray_DATA(TD); + float* tf = (float*)PyArray_DATA(TF); + + // allocate output + npy_intp out_dims[4] = {Batch, Head, 1, Headsize}; + PyObject *OUT = PyArray_SimpleNew(4, out_dims, NPY_FLOAT); + float* out = (float*)PyArray_DATA(OUT); + // fill with 0 + for (int i = 0; i < Batch * Head * Headsize; i+=SIMD_WIDTH) { + STORE(&out[i], SET1(0)); + } + + // allocate new STATE, copy from old one + npy_intp state_dims[4] = {Batch, Head, Headsize, Headsize}; + PyObject *STATE_NEW = PyArray_SimpleNew(4, state_dims, NPY_FLOAT); + // get mutable pointer + float* ss_new = (float*)PyArray_DATA(STATE_NEW); + + for (int i = 0; i < Batch * Head * Headsize * Headsize; i+=SIMD_WIDTH) { + STORE(&ss_new[i], LOAD(&ss[i])); + } + + + + + + + forward_cpu(Batch, Time, Channel, Head, ss_new, rr, kk, vv, td, tf, out); + // ss_new[0] = 0.9; + /// return touple of both output and new state + + PyObject *ret = PyTuple_New(2); + PyTuple_SetItem(ret, 0, OUT); + PyTuple_SetItem(ret, 1, STATE_NEW); + return ret; +} + + +static PyMethodDef methods[] = { + { + "wkvpython", wkvworld_c, METH_VARARGS, + "Print 'hello xxx'" + }, + { + "wkv5", wkvnumpy_c, METH_VARARGS, + "numpy function tester", 6 + + }, + {NULL, NULL, 0, NULL} +}; + + +static struct PyModuleDef wkvdefinition = { + PyModuleDef_HEAD_INIT, + "wkv5", + "A Python module that allows for fast wkv5 operation", + -1, + methods +}; + + +PyMODINIT_FUNC PyInit_wkv5(void) { + Py_Initialize(); + import_array(); + return PyModule_Create(&wkvdefinition); +} \ No newline at end of file diff --git a/runexamples/cpp/include/NumCpp.hpp b/runexamples/cpp/include/NumCpp.hpp new file mode 100644 index 0000000..05c38eb --- /dev/null +++ b/runexamples/cpp/include/NumCpp.hpp @@ -0,0 +1,73 @@ +/// @section Description +/// A Templatized Header Only C++ Implementation of the Python Numpy Library +/// +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// +/// @section License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// @section Testing +/// **C++ Standards:** +/// C++14 +/// C++17 +/// C++2a +/// +/// **Compilers:** +/// Visual Studio: 2017, 2019 +/// GNU: 6.5, 7.5, 8.4, 9.3, 10.1 +/// Clang: 6, 7, 8, 9, 10 +/// +/// **Boost Versions:** +/// 1.68, 1.70, 1.72, and 1.73 +/// +#pragma once +#define NUMCPP_NO_USE_BOOST +#include "NumCpp/Coordinates.hpp" +#include "NumCpp/Core.hpp" +#include "NumCpp/DateTime.hpp" +#include "NumCpp/Filter.hpp" +#include "NumCpp/Functions.hpp" +#include "NumCpp/ImageProcessing.hpp" +#include "NumCpp/Integrate.hpp" +#include "NumCpp/Linalg.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Polynomial.hpp" +#include "NumCpp/PythonInterface.hpp" +#include "NumCpp/Random.hpp" +#include "NumCpp/Roots.hpp" +#include "NumCpp/Rotations.hpp" +#include "NumCpp/Special.hpp" +#include "NumCpp/Utils.hpp" +#include "NumCpp/Vector.hpp" + +/// \example GaussNewtonNlls.cpp +/// Example for using the linalg::gaussNewtonNlls function +/// +/// \example InterfaceWithEigen.cpp +/// Example for interfaceing with Eigen Matrix +/// +/// \example InterfaceWithOpenCV.cpp +/// Example for interfaceing with OpenCV Mat +/// +/// \example ReadMe.cpp +/// Examples from the Quick Start Guide in README.md at [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// diff --git a/runexamples/cpp/include/NumCpp/Coordinates.hpp b/runexamples/cpp/include/NumCpp/Coordinates.hpp new file mode 100644 index 0000000..32d523a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for holding and working with coordinates in either Ra/Dec or cartesian formats +/// +#pragma once + +#include "NumCpp/Coordinates/Coordinate.hpp" +#include "NumCpp/Coordinates/Dec.hpp" +#include "NumCpp/Coordinates/RA.hpp" +#include "NumCpp/Coordinates/degreeSeperation.hpp" +#include "NumCpp/Coordinates/radianSeperation.hpp" diff --git a/runexamples/cpp/include/NumCpp/Coordinates/Coordinate.hpp b/runexamples/cpp/include/NumCpp/Coordinates/Coordinate.hpp new file mode 100644 index 0000000..ca209ef --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates/Coordinate.hpp @@ -0,0 +1,354 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Coordinate Object +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Coordinates/Dec.hpp" +#include "NumCpp/Coordinates/RA.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::coordinates +{ + //================================================================================ + /// Holds a full coordinate object + class Coordinate + { + public: + //============================================================================ + /// Default Constructor + /// + Coordinate() = default; + + //============================================================================ + /// Constructor + /// + /// @param inRaDegrees + /// @param inDecDegrees + /// + Coordinate(double inRaDegrees, double inDecDegrees) : + ra_(inRaDegrees), + dec_(inDecDegrees) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inRaHours + /// @param inRaMinutes + /// @param inRaSeconds + /// @param inSign + /// @param inDecDegreesWhole + /// @param inDecMinutes + /// @param inDecSeconds + /// + Coordinate(uint8 inRaHours, + uint8 inRaMinutes, + double inRaSeconds, + Sign inSign, + uint8 inDecDegreesWhole, + uint8 inDecMinutes, + double inDecSeconds) : + ra_(inRaHours, inRaMinutes, inRaSeconds), + dec_(inSign, inDecDegreesWhole, inDecMinutes, inDecSeconds) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inRA + /// @param inDec + /// + Coordinate(const RA& inRA, const Dec& inDec) noexcept : + ra_(inRA), + dec_(inDec) + { + polarToCartesian(); + } + + //============================================================================ + /// Constructor + /// + /// @param inX + /// @param inY + /// @param inZ + /// + Coordinate(double inX, double inY, double inZ) : + x_(inX), + y_(inY), + z_(inZ) + { + cartesianToPolar(); + } + + //============================================================================ + /// Constructor + /// + /// @param inCartesianVector + /// + Coordinate(const NdArray& inCartesianVector) + { + if (inCartesianVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("NdArray input must be of length 3."); + } + + x_ = inCartesianVector[0]; + y_ = inCartesianVector[1]; + z_ = inCartesianVector[2]; + + cartesianToPolar(); + } + + //============================================================================ + /// Returns the Dec object + /// + /// @return Dec + /// + [[nodiscard]] const Dec& dec() const noexcept + { + return dec_; + } + + //============================================================================ + /// Returns the RA object + /// + /// @return RA + /// + [[nodiscard]] const RA& ra() const noexcept + { + return ra_; + } + + //============================================================================ + /// Returns the cartesian x value + /// + /// @return x + /// + [[nodiscard]] double x() const noexcept + { + return x_; + } + + //============================================================================ + /// Returns the cartesian y value + /// + /// @return y + /// + [[nodiscard]] double y() const noexcept + { + return y_; + } + + //============================================================================ + /// Returns the cartesian z value + /// + /// @return z + /// + [[nodiscard]] double z() const noexcept + { + return z_; + } + + //============================================================================ + /// Returns the cartesian xyz triplet as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray xyz() const + { + NdArray out = { x_, y_, z_ }; + return out; + } + + //============================================================================ + /// Returns the degree seperation between the two Coordinates + /// + /// @param inOtherCoordinate + /// + /// @return degrees + /// + [[nodiscard]] double degreeSeperation(const Coordinate& inOtherCoordinate) const + { + return rad2deg(radianSeperation(inOtherCoordinate)); + } + + //============================================================================ + /// Returns the degree seperation between the Coordinate + /// and the input vector + /// + /// @param inVector + /// + /// @return degrees + /// + [[nodiscard]] double degreeSeperation(const NdArray& inVector) const + { + return rad2deg(radianSeperation(inVector)); + } + + //============================================================================ + /// Returns the radian seperation between the two Coordinates + /// + /// @param inOtherCoordinate + /// + /// @return radians + /// + [[nodiscard]] double radianSeperation(const Coordinate& inOtherCoordinate) const + { + return std::acos(dot(xyz(), inOtherCoordinate.xyz()).item()); + } + + //============================================================================ + /// Returns the radian seperation between the Coordinate + /// and the input vector + /// + /// @param inVector + /// + /// @return radians + /// + [[nodiscard]] double radianSeperation(const NdArray& inVector) const + { + if (inVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be of length 3."); + } + + return std::acos(dot(xyz(), inVector.flatten()).item()); + } + + //============================================================================ + /// Returns coordinate as a string representation + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + std::string returnStr; + returnStr = ra_.str(); + returnStr += dec_.str(); + returnStr += "Cartesian = " + xyz().str(); + return returnStr; + } + + //============================================================================ + /// Prints the Coordinate object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const Coordinate& inRhs) const noexcept + { + return ra_ == inRhs.ra_ && dec_ == inRhs.dec_; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const Coordinate& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inCoord + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Coordinate& inCoord) + { + inStream << inCoord.str(); + return inStream; + } + + private: + //====================================Attributes============================== + RA ra_{}; + Dec dec_{}; + double x_{ 1. }; + double y_{ 0. }; + double z_{ 0. }; + + //============================================================================ + /// Converts polar coordinates to cartesian coordinates + /// + void cartesianToPolar() + { + double degreesRa = rad2deg(std::atan2(y_, x_)); + if (degreesRa < 0) + { + degreesRa += 360; + } + ra_ = RA(degreesRa); + + const double r = std::sqrt(utils::sqr(x_) + utils::sqr(y_) + utils::sqr(z_)); + const double degreesDec = rad2deg(std::asin(z_ / r)); + dec_ = Dec(degreesDec); + } + + //============================================================================ + /// Converts polar coordinates to cartesian coordinates + /// + void polarToCartesian() noexcept + { + const double raRadians = deg2rad(ra_.degrees()); + const double decRadians = deg2rad(dec_.degrees()); + + x_ = std::cos(raRadians) * std::cos(decRadians); + y_ = std::sin(raRadians) * std::cos(decRadians); + z_ = std::sin(decRadians); + } + }; +} // namespace nc::coordinates diff --git a/runexamples/cpp/include/NumCpp/Coordinates/Dec.hpp b/runexamples/cpp/include/NumCpp/Coordinates/Dec.hpp new file mode 100644 index 0000000..5d3fdee --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates/Dec.hpp @@ -0,0 +1,232 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Declination object +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::coordinates +{ + //================================================================================ + /// Struct Enum for positive or negative Dec angle + enum class Sign + { + NEGATIVE = 0, + POSITIVE + }; + + //================================================================================ + /// Holds a Declination object + class Dec + { + public: + //============================================================================ + /// Default Constructor + /// + Dec() = default; + + //============================================================================ + /// Constructor + /// + /// @param inDegrees + /// + explicit Dec(double inDegrees) : + degrees_(inDegrees), + radians_(deg2rad(inDegrees)) + { + if (inDegrees < -90 || inDegrees > 90) + { + THROW_INVALID_ARGUMENT_ERROR("input degrees must be of the range [-90, 90]"); + } + + sign_ = degrees_ < 0 ? Sign::NEGATIVE : Sign::POSITIVE; + const double absDegrees = std::abs(degrees_); + degreesWhole_ = static_cast(std::floor(absDegrees)); + + const double decMinutes = (absDegrees - static_cast(degreesWhole_)) * 60.; + minutes_ = static_cast(std::floor(decMinutes)); + seconds_ = (decMinutes - static_cast(minutes_)) * 60.; + } + + //============================================================================ + /// Constructor + /// + /// @param inSign + /// @param inDegrees + /// @param inMinutes + /// @param inSeconds + /// + Dec(Sign inSign, uint8 inDegrees, uint8 inMinutes, double inSeconds) noexcept : + sign_(inSign), + degreesWhole_(inDegrees), + minutes_(inMinutes), + seconds_(inSeconds) + { + degrees_ = static_cast(degreesWhole_) + static_cast(minutes_) / 60. + seconds_ / 3600.; + degrees_ *= sign_ == Sign::NEGATIVE ? -1 : 1; + + radians_ = deg2rad(degrees_); + } + + //============================================================================ + /// Get the sign of the degrees (positive or negative) + /// + /// @return Sign + /// + [[nodiscard]] Sign sign() const noexcept + { + return sign_; + } + + //============================================================================ + /// Get the degrees value + /// + /// @return degrees + /// + [[nodiscard]] double degrees() const noexcept + { + return degrees_; + } + + //============================================================================ + /// Get the radians value + /// + /// @return minutes + /// + [[nodiscard]] double radians() const noexcept + { + return radians_; + } + + //============================================================================ + /// Get the whole degrees value + /// + /// @return whole degrees + /// + [[nodiscard]] uint8 degreesWhole() const noexcept + { + return degreesWhole_; + } + + //============================================================================ + /// Get the minute value + /// + /// @return minutes + /// + [[nodiscard]] uint8 minutes() const noexcept + { + return minutes_; + } + + //============================================================================ + /// Get the seconds value + /// + /// @return seconds + /// + [[nodiscard]] double seconds() const noexcept + { + return seconds_; + } + + //============================================================================ + /// Return the dec object as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string strSign = sign_ == Sign::NEGATIVE ? "-" : "+"; + std::string out = "Dec dms: " + strSign + utils::num2str(degreesWhole_) + " degrees, " + + utils::num2str(minutes_) + " minutes, "; + out += utils::num2str(seconds_) + " seconds\nDec degrees = " + utils::num2str(degrees_) + '\n'; + return out; + } + + //============================================================================ + /// Prints the Dec object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const Dec& inRhs) const noexcept + { + return utils::essentiallyEqual(degrees_, inRhs.degrees_); + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const Dec& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inDec + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Dec& inDec) + { + inStream << inDec.str(); + return inStream; + } + + private: + //====================================Attributes============================== + Sign sign_{ Sign::POSITIVE }; + uint8 degreesWhole_{ 0 }; + uint8 minutes_{ 0 }; + double seconds_{ 0. }; + double degrees_{ 0. }; + double radians_{ 0. }; + }; +} // namespace nc::coordinates diff --git a/runexamples/cpp/include/NumCpp/Coordinates/RA.hpp b/runexamples/cpp/include/NumCpp/Coordinates/RA.hpp new file mode 100644 index 0000000..5a53bb7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates/RA.hpp @@ -0,0 +1,204 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Right Ascension object +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::coordinates +{ + //================================================================================ + /// Holds a right ascension object + class RA + { + public: + //============================================================================ + /// Default Constructor + /// + RA() = default; + + //============================================================================ + /// Constructor + /// + /// @param inDegrees + /// + explicit RA(double inDegrees) : + degrees_(inDegrees), + radians_(deg2rad(inDegrees)) + { + if (inDegrees < 0 || inDegrees >= 360) + { + THROW_INVALID_ARGUMENT_ERROR("input degrees must be of the range [0, 360)"); + } + + hours_ = static_cast(std::floor(degrees_ / 15.)); + const double decMinutes = (degrees_ - static_cast(hours_) * 15.) * 4.; + minutes_ = static_cast(std::floor(decMinutes)); + seconds_ = static_cast((decMinutes - static_cast(minutes_)) * 60.); + } + + //============================================================================ + /// Constructor + /// + /// @param inHours + /// @param inMinutes + /// @param inSeconds + /// + RA(uint8 inHours, uint8 inMinutes, double inSeconds) + noexcept : + hours_(inHours), + minutes_(inMinutes), + seconds_(inSeconds) + { + degrees_ = static_cast(hours_) * 15. + static_cast(minutes_) / 4. + seconds_ / 240.; + radians_ = deg2rad(degrees_); + } + + //============================================================================ + /// Get the radians value + /// + /// @return radians + /// + [[nodiscard]] double radians() const noexcept + { + return radians_; + } + + //============================================================================ + /// Get the degrees value + /// + /// @return degrees + /// + [[nodiscard]] double degrees() const noexcept + { + return degrees_; + } + + //============================================================================ + /// Get the hour value + /// + /// @return hours + /// + [[nodiscard]] uint8 hours() const noexcept + { + return hours_; + } + + //============================================================================ + /// Get the minute value + /// + /// @return minutes + /// + [[nodiscard]] uint8 minutes() const noexcept + { + return minutes_; + } + + //============================================================================ + /// Get the seconds value + /// + /// @return seconds + /// + [[nodiscard]] double seconds() const noexcept + { + return seconds_; + } + + //============================================================================ + /// Return the RA object as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = + "RA hms: " + utils::num2str(hours_) + " hours, " + utils::num2str(minutes_) + " minutes, "; + out += utils::num2str(seconds_) + " seconds\nRA degrees: " + utils::num2str(degrees_) + '\n'; + return out; + } + + //============================================================================ + /// Prints the RA object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator==(const RA& inRhs) const noexcept + { + return utils::essentiallyEqual(degrees_, inRhs.degrees_); + } + + //============================================================================ + /// Not equality operator + /// + /// @param inRhs + /// + /// @return bool + /// + bool operator!=(const RA& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + /// Ostream operator + /// + /// @param inStream + /// @param inRa + /// + friend std::ostream& operator<<(std::ostream& inStream, const RA& inRa) + { + inStream << inRa.str(); + return inStream; + } + + private: + //====================================Attributes============================== + uint8 hours_{ 0 }; + uint8 minutes_{ 0 }; + double seconds_{ 0. }; + double degrees_{ 0. }; + double radians_{ 0. }; + }; +} // namespace nc::coordinates diff --git a/runexamples/cpp/include/NumCpp/Coordinates/degreeSeperation.hpp b/runexamples/cpp/include/NumCpp/Coordinates/degreeSeperation.hpp new file mode 100644 index 0000000..1ab4cdd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates/degreeSeperation.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Degree seperation between the two Coordinates +/// +#pragma once + +#include "NumCpp/Coordinates/Coordinate.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::coordinates +{ + //============================================================================ + /// Returns the degree seperation between the two Coordinates + /// + /// @param inCoordinate1 + /// @param inCoordinate2 + /// + /// @return degrees + /// + inline double degreeSeperation(const Coordinate& inCoordinate1, const Coordinate& inCoordinate2) + { + return inCoordinate1.degreeSeperation(inCoordinate2); + } + + //============================================================================ + /// Returns the degree seperation between the Coordinate + /// and the input vector + /// + /// @param inVector1 + /// @param inVector2 + /// + /// @return degrees + /// + inline double degreeSeperation(const NdArray& inVector1, const NdArray& inVector2) + { + const Coordinate inCoord1(inVector1); + return inCoord1.degreeSeperation(inVector2); + } +} // namespace nc::coordinates diff --git a/runexamples/cpp/include/NumCpp/Coordinates/radianSeperation.hpp b/runexamples/cpp/include/NumCpp/Coordinates/radianSeperation.hpp new file mode 100644 index 0000000..d0e5162 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Coordinates/radianSeperation.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Radian seperation between the two Coordinates +/// +#pragma once + +#include "NumCpp/Coordinates/Coordinate.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::coordinates +{ + //============================================================================ + /// Returns the radian seperation between the two Coordinates + /// + /// @param inCoordinate1 + /// @param inCoordinate2 + /// + /// @return radians + /// + inline double radianSeperation(const Coordinate& inCoordinate1, const Coordinate& inCoordinate2) + { + return inCoordinate1.radianSeperation(inCoordinate2); + } + + //============================================================================ + /// Returns the radian seperation between the Coordinate + /// and the input vector + /// + /// @param inVector1 + /// @param inVector2 + /// + /// @return radians + /// + inline double radianSeperation(const NdArray& inVector1, const NdArray& inVector2) + { + const Coordinate inCoord1(inVector1); + return inCoord1.radianSeperation(inVector2); + } +} // namespace nc::coordinates diff --git a/runexamples/cpp/include/NumCpp/Core.hpp b/runexamples/cpp/include/NumCpp/Core.hpp new file mode 100644 index 0000000..3d513c1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core.hpp @@ -0,0 +1,37 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NumCpp Core classes, functions, and typedefs +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/DataCube.hpp" +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Version.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Timer.hpp" +#include "NumCpp/Core/Types.hpp" diff --git a/runexamples/cpp/include/NumCpp/Core/Constants.hpp b/runexamples/cpp/include/NumCpp/Core/Constants.hpp new file mode 100644 index 0000000..45dab76 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Constants.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds usefull constants +/// +#pragma once + +#include +#include +#include + +namespace nc::constants +{ + constexpr double c = 3.e8; ///< speed of light + constexpr double e = 2.718281828459045; ///< eulers number + constexpr double inf = std::numeric_limits::infinity(); ///< infinity + constexpr double pi = 3.141592653589793238462643383279502884; ///< Pi + const double nan = std::nan("1"); ///< NaN + constexpr auto j = std::complex(0, 1); // sqrt(-1) unit imaginary number + + constexpr double DAYS_PER_WEEK = 7; ///< Number of days in a week + constexpr double MINUTES_PER_HOUR = 60; ///< Number of minutes in an hour + constexpr double SECONDS_PER_MINUTE = 60; ///< Number of seconds in a minute + constexpr double MILLISECONDS_PER_SECOND = 1000; ///< Number of milliseconds in a second + constexpr double SECONDS_PER_HOUR = MINUTES_PER_HOUR * SECONDS_PER_MINUTE; ///< Number of seconds in an hour + constexpr double HOURS_PER_DAY = 24; ///< Number of hours in a day + constexpr double MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR; ///< Number of minutes in a day + constexpr double SECONDS_PER_DAY = MINUTES_PER_DAY * SECONDS_PER_MINUTE; ///< Number of seconds in a day + constexpr double MILLISECONDS_PER_DAY = + SECONDS_PER_DAY * MILLISECONDS_PER_SECOND; ///< Number of milliseconds in a day + constexpr double SECONDS_PER_WEEK = SECONDS_PER_DAY * DAYS_PER_WEEK; ///< Number of seconds in a week +} // namespace nc::constants diff --git a/runexamples/cpp/include/NumCpp/Core/DataCube.hpp b/runexamples/cpp/include/NumCpp/Core/DataCube.hpp new file mode 100644 index 0000000..b7f38a8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/DataCube.hpp @@ -0,0 +1,827 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Convience container for holding a uniform array of NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //================================================================================ + /// Convenience container for holding a uniform array of NdArrays + template + class DataCube + { + public: + //================================Typedefs================================== + using iterator = typename std::deque>::iterator; + using const_iterator = typename std::deque>::const_iterator; + + //============================================================================ + /// Default Constructor + /// + DataCube() = default; + + //============================================================================ + /// Constructor, preallocates to the input size + /// + /// @param inSize + /// + explicit DataCube(uint32 inSize) + { + cube_.reserve(inSize); + } + + //============================================================================ + /// Access method, with bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + NdArray& at(uint32 inIndex) + { + return cube_.at(inIndex); + } + + //============================================================================ + /// Const access method, with bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + [[nodiscard]] const NdArray& at(uint32 inIndex) const + { + return cube_.at(inIndex); + } + + //============================================================================ + /// Returns a reference to the last 2d "slice" of the cube in the z-axis + /// + /// @return NdArray& + /// + NdArray& back() noexcept + { + return cube_.back(); + } + + //============================================================================ + /// Returns an iterator to the first 2d z "slice" of the cube. + /// + /// @return iterator + /// + [[nodiscard]] iterator begin() noexcept + { + return cube_.begin(); + } + + //============================================================================ + /// Returns an const_iterator to the first 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return cube_.cbegin(); + } + + //============================================================================ + /// Returns an const_iterator to the first 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin() const noexcept + { + return cube_.cbegin(); + } + + //============================================================================ + /// Outputs the DataCube as a .bin file + /// + /// @param inFilename + /// + void dump(const std::string& inFilename) const + { + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("bin"); + } + + std::ofstream ofile(f.c_str(), std::ios::binary); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Could not open the input file:\n\t" + inFilename); + } + + for (auto& ndarray : cube_) + { + ofile.write(reinterpret_cast(ndarray.data()), ndarray.size() * sizeof(dtype)); + } + + ofile.close(); + } + + //============================================================================ + /// Tests whether or not the container is empty + /// + /// @return bool + /// + bool isempty() noexcept + { + return cube_.empty(); + } + + //============================================================================ + /// Returns an iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return iterator + /// + [[nodiscard]] iterator end() noexcept + { + return cube_.end(); + } + + //============================================================================ + /// Returns an const_iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return cube_.cend(); + } + + //============================================================================ + /// Returns an const_iterator to 1 past the last 2d z "slice" of the cube. + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend() const noexcept + { + return cube_.cend(); + } + + //============================================================================ + /// Returns a reference to the front 2d "slice" of the cube in the z-axis + /// + /// @return NdArray& + /// + NdArray& front() noexcept + { + return cube_.front(); + } + + //============================================================================ + /// Returns the x/y shape of the cube + /// + /// @return Shape + /// + [[nodiscard]] const Shape& shape() const noexcept + { + return elementShape_; + } + + //============================================================================ + /// Returns the size of the z-axis of the cube + /// + /// @return size + /// + [[nodiscard]] uint32 sizeZ() const noexcept + { + return static_cast(cube_.size()); + } + + //============================================================================ + /// Removes the last z "slice" of the cube + /// + void pop_back() noexcept + { + cube_.pop_back(); + } + + //============================================================================ + /// Adds a new z "slice" to the end of the cube + /// + /// @param inArray + /// + void push_back(const NdArray& inArray) + { + const Shape inputShape = inArray.shape(); + + if (elementShape_.rows == 0 && elementShape_.cols == 0) + { + // initialize to the first input array size + elementShape_.rows = inputShape.rows; + elementShape_.cols = inputShape.cols; + } + + if (inputShape != elementShape_) + { + THROW_INVALID_ARGUMENT_ERROR("element arrays must all be the same shape"); + } + + cube_.push_back(inArray); + } + + //============================================================================ + /// Slices the z dimension of the cube + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inIndex) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + NdArray returnArray(1, sizeZ()); + + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray[i] = cube_[i][inIndex]; + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inIndex, Slice inSliceZ) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + NdArray returnArray(1, inSliceZ.numElements(sizeZ())); + + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray[idx++] = cube_[i][inIndex]; + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inRow, int32 inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(1, sizeZ()); + + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray[i] = cube_[i](inRow, inCol); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inRow, int32 inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(1, inSliceZ.numElements(sizeZ())); + + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray[idx++] = cube_[i](inRow, inCol); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(Slice inRow, int32 inCol) const + { + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(inRow.numElements(elementShape_.rows), sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray.put(returnArray.rSlice(), i, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(Slice inRow, int32 inCol, Slice inSliceZ) const + { + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + NdArray returnArray(inRow.numElements(elementShape_.rows), inSliceZ.numElements(sizeZ())); + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray.put(returnArray.rSlice(), idx++, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAll(int32 inRow, Slice inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + NdArray returnArray(inCol.numElements(elementShape_.cols), sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnArray.put(returnArray.rSlice(), i, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZ(int32 inRow, Slice inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + NdArray returnArray(inCol.numElements(elementShape_.cols), inSliceZ.numElements(sizeZ())); + uint32 idx = 0; + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnArray.put(returnArray.rSlice(), idx++, cube_[i](inRow, inCol)); + } + + return returnArray; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @return DataCube + /// + DataCube sliceZAll(Slice inRow, Slice inCol) const + { + DataCube returnCube(sizeZ()); + for (uint32 i = 0; i < sizeZ(); ++i) + { + returnCube.push_back(cube_[i](inRow, inCol)); + } + + return returnCube; + } + + //============================================================================ + /// Slices the z dimension of the cube with NO bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return DataCube + /// + DataCube sliceZ(Slice inRow, Slice inCol, Slice inSliceZ) const + { + DataCube returnCube(inSliceZ.numElements(sizeZ())); + for (int32 i = inSliceZ.start; i < inSliceZ.stop; i += inSliceZ.step) + { + returnCube.push_back(cube_[i](inRow, inCol)); + } + + return returnCube; + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inIndex) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + if (static_cast(inIndex) >= elementShape_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + return sliceZAll(inIndex); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inIndex: the flattend 2d index (row, col) to slice + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inIndex, Slice inSliceZ) const + { + if (inIndex < 0) + { + inIndex += elementShape_.size(); + } + + if (static_cast(inIndex) >= elementShape_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("inIndex exceeds matrix dimensions."); + } + + return sliceZ(inIndex, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inRow, int32 inCol) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inRow, int32 inCol, Slice inSliceZ) const + { + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(Slice inRow, int32 inCol) const + { + auto numRows = inRow.numElements(elementShape_.rows); + if (numRows > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(Slice inRow, int32 inCol, Slice inSliceZ) const + { + auto numRows = inRow.numElements(elementShape_.rows); + if (numRows > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol < 0) + { + inCol += elementShape_.cols; + } + + if (static_cast(inCol) >= elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZAllat(int32 inRow, Slice inCol) const + { + auto numCols = inCol.numElements(elementShape_.cols); + if (numCols > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return NdArray + /// + [[nodiscard]] NdArray sliceZat(int32 inRow, Slice inCol, Slice inSliceZ) const + { + auto numCols = inCol.numElements(elementShape_.cols); + if (numCols > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + if (inRow < 0) + { + inRow += elementShape_.rows; + } + + if (static_cast(inRow) >= elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @return DataCube + /// + DataCube sliceZAllat(Slice inRow, Slice inCol) const + { + if (inRow.numElements(elementShape_.rows) > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol.numElements(elementShape_.cols) > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + return sliceZAll(inRow, inCol); + } + + //============================================================================ + /// Slices the z dimension of the cube with bounds checking + /// + /// @param inRow + /// @param inCol + /// @param inSliceZ: the slice dimensions of the z-axis + /// @return DataCube + /// + DataCube sliceZat(Slice inRow, Slice inCol, Slice inSliceZ) const + { + if (inRow.numElements(elementShape_.rows) > elementShape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("inRow exceeds matrix dimensions."); + } + + if (inCol.numElements(elementShape_.cols) > elementShape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("inCol exceeds matrix dimensions."); + } + + auto numElements = inSliceZ.numElements(sizeZ()); + if (numElements > sizeZ()) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions."); + } + + return sliceZ(inRow, inCol, inSliceZ); + } + + //============================================================================ + /// Access operator, no bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + NdArray& operator[](uint32 inIndex) noexcept + { + return cube_[inIndex]; + } + + //============================================================================ + /// Const access operator, no bounds checking. Returns the 2d z "slice" element of the cube. + /// + /// @param inIndex + /// + /// @return NdArray + /// + const NdArray& operator[](uint32 inIndex) const noexcept + { + return cube_[inIndex]; + } + + private: + //================================Attributes================================== + std::vector> cube_{}; + Shape elementShape_{ 0, 0 }; + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/DtypeInfo.hpp b/runexamples/cpp/include/NumCpp/Core/DtypeInfo.hpp new file mode 100644 index 0000000..546dca4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/DtypeInfo.hpp @@ -0,0 +1,198 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds info about the dtype +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc +{ + //================================================================================ + /// Holds info about the dtype + template + class DtypeInfo + { + public: + //============================================================================ + /// For integer types: number of non-sign bits in the representation. + /// For floating types : number of digits(in radix base) in the mantissa + /// + /// @return number of bits + /// + static constexpr int bits() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::digits; + } + + //============================================================================ + /// Machine epsilon (the difference between 1 and the least + /// value greater than 1 that is representable). + /// + /// @return dtype + /// + static constexpr dtype epsilon() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::epsilon(); + } + + //============================================================================ + /// True if type is integer. + /// + /// @return bool + /// + static constexpr bool isInteger() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_integer; + } + + //============================================================================ + /// True if type is signed. + /// + /// @return bool + /// + static constexpr bool isSigned() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_signed; + } + + //============================================================================ + /// Returns the minimum value of the dtype + /// + /// @return min value + /// + static constexpr dtype min() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::min(); + } + + //============================================================================ + /// Returns the maximum value of the dtype + /// + /// @return max value + /// + static constexpr dtype max() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::max(); + } + }; + + //================================================================================ + /// Holds info about the std::complex + template + class DtypeInfo> + { + public: + //============================================================================ + /// For integer types: number of non-sign bits in the representation. + /// For floating types : number of digits(in radix base) in the mantissa + /// + /// @return number of bits + /// + static constexpr int bits() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::digits; + } + + //============================================================================ + /// Machine epsilon (the difference between 1 and the least + /// value greater than 1 that is representable). + /// + /// @return dtype + /// + static constexpr std::complex epsilon() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::epsilon(), DtypeInfo::epsilon() }; + } + + //============================================================================ + /// True if type is integer. + /// + /// @return bool + /// + static constexpr bool isInteger() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_integer; + } + + //============================================================================ + /// True if type is signed. + /// + /// @return bool + /// + static constexpr bool isSigned() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::numeric_limits::is_signed; + } + + //============================================================================ + /// Returns the minimum value of the dtype + /// + /// @return min value + /// + static constexpr std::complex min() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::min(), DtypeInfo::min() }; + } + + //============================================================================ + /// Returns the maximum value of the dtype + /// + /// @return max value + /// + static constexpr std::complex max() noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return { DtypeInfo::max(), DtypeInfo::max() }; + } + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/Endian.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/Endian.hpp new file mode 100644 index 0000000..0d99a99 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/Endian.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for determining and swaping endianess +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::endian +{ + //============================================================================ + // Function Description: + /// Determines the endianess of the system + /// + /// @return bool true if the system is little endian + /// + inline bool isLittleEndian() noexcept + { + union + { + uint32 i{}; + std::array c; + } fourBytes = { 0x01020304 }; // NOLINT(cppcoreguidelines-avoid-magic-numbers) + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) + return fourBytes.c[0] == 4; + } + + //============================================================================ + // Function Description: + /// Swaps the bytes of the input value + /// + /// @param value + /// @return byte swapped value + /// + template + dtype byteSwap(dtype value) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + static_assert(CHAR_BIT == 8, "CHAR_BIT != 8"); // NOLINT(cppcoreguidelines-avoid-magic-numbers) + + union + { + dtype value; + std::array value8; + } source, dest; + + source.value = value; + + for (std::size_t k = 0; k < sizeof(dtype); ++k) + { + dest.value8[k] = source.value8[sizeof(dtype) - k - 1]; + } + + return dest.value; + } +} // namespace nc::endian diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/Error.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/Error.hpp new file mode 100644 index 0000000..d948b6f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/Error.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Standard NumCpp errors +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define THROW_INVALID_ARGUMENT_ERROR(msg) \ + nc::error::throwError(__FILE__, __func__, __LINE__, msg) +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define THROW_RUNTIME_ERROR(msg) nc::error::throwError(__FILE__, __func__, __LINE__, msg) + +namespace nc::error +{ + //============================================================================ + /// Makes the full error message string + /// + /// @param file: the file + /// @param function: the function + /// @param line: the line of the file + /// @param msg: the message to throw (default "") + /// + template + void throwError(const std::string& file, const std::string& function, uint32 line, const std::string& msg = "") + { + std::string errMsg = + "File: " + file + "\n\tFunction: " + function + "\n\tLine: " + std::to_string(line) + "\n\tError: " + msg; + std::cerr << errMsg; + throw ErrorType(errMsg); + } +} // namespace nc::error diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp new file mode 100644 index 0000000..be7b4d6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/StaticAsserts.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Some helper routines for checking types +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_VALID_DTYPE(dtype) \ + static_assert(nc::is_valid_dtype_v, "Template type is not a valid dtype for NdArray") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_ARITHMETIC(dtype) \ + static_assert(std::is_arithmetic_v, "Can only be used with arithmetic types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_INTEGER(dtype) static_assert(std::is_integral_v, "Can only be used with integer types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_UNSIGNED_INTEGER(dtype) \ + static_assert(std::is_integral_v && std::is_unsigned_v, "Can only be used with integer types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_FLOAT(dtype) static_assert(std::is_floating_point_v, "Can only be used with float types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_COMPLEX(dtype) static_assert(nc::is_complex_v, "Can only be used with std::complex types") + +// NOLINTNEXTLINE(cppcoreguidelines-macro-usage) +#define STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype) \ + static_assert(std::is_arithmetic_v || nc::is_complex_v, \ + "Can only be used with arithmetic types or std::complex types") diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp new file mode 100644 index 0000000..9de0f38 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/StdComplexOperators.hpp @@ -0,0 +1,117 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Additional operator for std::complex +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Less than operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs < rhs + /// + template + bool operator<(const std::complex& lhs, const std::complex& rhs) noexcept + { + if (!utils::essentiallyEqual(lhs.real(), rhs.real())) + { + return lhs.real() < rhs.real(); + } + + return lhs.imag() < rhs.imag(); + } + + //============================================================================ + // Method Description: + /// Less than or equal operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs <= rhs + /// + template + bool operator<=(const std::complex& lhs, const std::complex& rhs) noexcept + { + if (!utils::essentiallyEqual(lhs.real(), rhs.real())) + { + return lhs.real() <= rhs.real(); + } + + return lhs.imag() <= rhs.imag(); + } + + //============================================================================ + // Method Description: + /// Greater than operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs > rhs + /// + template + bool operator>(const std::complex& lhs, const std::complex& rhs) noexcept + { + return !(lhs <= rhs); + } + + //============================================================================ + // Method Description: + /// Greater than or equal operator for std::complex + /// + /// @param lhs + /// @param rhs + /// @return bool true if lhs >= rhs + /// + template + bool operator>=(const std::complex& lhs, const std::complex& rhs) noexcept + { + return !(lhs < rhs); + } + + //============================================================================ + // Method Description: + /// Greater than or equal operator for std::complex + /// + /// @param value + /// @return std::complex + /// + template + std::complex complex_cast(const std::complex& value) noexcept + { + STATIC_ASSERT_ARITHMETIC(Out); + + return std::complex(static_cast(value.real()), static_cast(value.imag())); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp new file mode 100644 index 0000000..c444f4d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/StlAlgorithms.hpp @@ -0,0 +1,857 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Macro to define whether or not c++17 parallel algorithm policies are supported +/// +#pragma once + +#include +#include +#include +#include + +#if defined(__cpp_lib_parallel_algorithm) && defined(NUMCPP_USE_MULTITHREAD) +#define PARALLEL_ALGORITHMS_SUPPORTED +#define CONDITIONAL_NO_EXCEPT +#include +#else +#define CONDITIONAL_NO_EXCEPT noexcept +#endif + +namespace nc::stl_algorithms +{ + //============================================================================ + // Method Description: + /// Tests if all of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool all_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::all_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Tests if any of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool any_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::any_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Copies from one container to another + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @return OutputIt + /// + template + OutputIt copy(InputIt first, InputIt last, OutputIt destination) CONDITIONAL_NO_EXCEPT + { + return std::copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination); + } + + //============================================================================ + // Method Description: + /// Counts the values in the range + /// + /// @param first: the first iterator of container + /// @param last: the last iterator of container + /// @param value: the initial value + /// @return count + /// + template + typename std::iterator_traits::difference_type + count(InputIt first, InputIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::count( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Test if two ranges are equal + /// + /// @param first1: the first iterator of first container + /// @param last1: the last iterator of first container + /// @param first2: the first iterator of second container + /// @return bool + /// + template + bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2) CONDITIONAL_NO_EXCEPT + { + return std::equal( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2); + } + + //============================================================================ + // Method Description: + /// Test if two ranges are equal + /// + /// @param first1: the first iterator of first container + /// @param last1: the last iterator of first container + /// @param first2: the first iterator of second container + /// @param p: binary predicate to compare the elements + /// @return bool + /// + template + bool equal(InputIt1 first1, InputIt1 last1, InputIt2 first2, BinaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::equal( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + p); + } + + //============================================================================ + // Method Description: + /// Fills the range with the value + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param value: the function to apply to the input iterators + /// + template + void fill(ForwardIt first, ForwardIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::fill( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Returns the first element in the range [first, last) + /// that satisfies specific criteria: + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param value: the value to find + /// @return InputIt + /// + template + InputIt find(InputIt first, InputIt last, const T& value) CONDITIONAL_NO_EXCEPT + { + return std::find( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + value); + } + + //============================================================================ + // Method Description: + /// Runs the function on each element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param f: the function to apply to the input iterators + /// + template + void for_each(InputIt first, InputIt last, UnaryFunction f) + { + std::for_each( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + f); + } + + //============================================================================ + // Method Description: + /// Returns true if the array is sorted + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return bool true if sorted + /// + template + bool is_sorted(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::is_sorted( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns true if the array is sorted + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: comparitor function + /// @return bool true if sorted + /// + template + bool is_sorted(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::is_sorted( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Returns the maximum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return ForwordIt + /// + template + ForwardIt max_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::max_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns the maximum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return ForwordIt + /// + template + ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::max_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Returns the minimum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return ForwardIt + template + ForwardIt min_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::min_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Returns the minimum element of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return ForwordIt + /// + template + ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::min_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Runs the minimum and maximum elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @return std::pair + /// + template + std::pair minmax_element(ForwardIt first, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + return std::minmax_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Runs the minimum and maximum elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// @return std::pair + /// + template + std::pair minmax_element(ForwardIt first, ForwardIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::minmax_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Tests if none of the elements of a range satisy a predicate + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param p: unary predicate function + /// @return bool + /// + template + bool none_of(InputIt first, InputIt last, UnaryPredicate p) CONDITIONAL_NO_EXCEPT + { + return std::none_of( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + p); + } + + //============================================================================ + // Method Description: + /// Sorts up to the nth element + /// + /// @param first: the first iterator of the range + /// @param nth: the element that should be sorted + /// @param last: the last iterator of the range + /// + template + void nth_element(RandomIt first, RandomIt nth, RandomIt last) CONDITIONAL_NO_EXCEPT + { + std::nth_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + nth, + last); + } + + //============================================================================ + // Method Description: + /// Sorts up to the nth element + /// + /// @param first: the first iterator of the range + /// @param nth: the element that should be sorted + /// @param last: the last iterator of the range + /// @param comp: the comparitor function + /// + template + void nth_element(RandomIt first, RandomIt nth, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + std::nth_element( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + nth, + last, + comp); + } + + //============================================================================ + // Method Description: + /// replaces a value in the range with another value + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param oldValue: the value to replace + /// @param newValue: the replacement value + /// + template + void replace(ForwardIt first, ForwardIt last, const T& oldValue, const T& newValue) CONDITIONAL_NO_EXCEPT + { + std::replace( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + oldValue, + newValue); + } + + //============================================================================ + // Method Description: + /// reverses the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void reverse(BidirIt first, BidirIt last) CONDITIONAL_NO_EXCEPT + { + std::reverse( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Rotates the elements of a range + /// + /// @param first: the first iterator of the range + /// @param firstN: the element that should appear at the beginning of the rotated range + /// @param last: the last iterator of the range + /// + template + void rotate(ForwardIt first, ForwardIt firstN, ForwardIt last) CONDITIONAL_NO_EXCEPT + { + std::rotate( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + firstN, + last); + } + + //============================================================================ + // Method Description: + /// finds the difference of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_difference(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + { + return std::set_difference( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the difference of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt set_difference(InputIt1 first1, + InputIt1 last1, + InputIt2 first2, + InputIt2 last2, + OutputIt destination, + Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::set_difference( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// finds the intersection of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_intersection(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + CONDITIONAL_NO_EXCEPT + { + return std::set_intersection( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the intersection of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt set_intersection(InputIt1 first1, + InputIt1 last1, + InputIt2 first2, + InputIt2 last2, + OutputIt destination, + Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::set_intersection( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// finds the union of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination) + CONDITIONAL_NO_EXCEPT + { + return std::set_union( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination); + } + + //============================================================================ + // Method Description: + /// finds the union of two ranges + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param last2: the first iterator of the destination + /// @param destination: the function to apply to the input iterators + /// @param comp: comparitor function + /// @return OutputIt + /// + template + OutputIt + set_union(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt destination, Compare comp) + CONDITIONAL_NO_EXCEPT + { + return std::set_union( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + last2, + destination, + comp); + } + + //============================================================================ + // Method Description: + /// Sorts the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void sort(RandomIt first, RandomIt last) CONDITIONAL_NO_EXCEPT + { + return std::sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Sorts the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// + template + void sort(RandomIt first, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + return std::sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Sorts the range preserving order + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// + template + void stable_sort(RandomIt first, RandomIt last) CONDITIONAL_NO_EXCEPT + { + std::stable_sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last); + } + + //============================================================================ + // Method Description: + /// Sorts the range preserving order + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param comp: the comparitor function + /// + template + void stable_sort(RandomIt first, RandomIt last, Compare comp) CONDITIONAL_NO_EXCEPT + { + std::stable_sort( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + comp); + } + + //============================================================================ + // Method Description: + /// Transforms the elements of the range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @param unaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt transform(InputIt first, InputIt last, OutputIt destination, UnaryOperation unaryFunction) + { + return std::transform( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination, + unaryFunction); + } + + //============================================================================ + // Method Description: + /// Transforms the elements of the range + /// + /// @param first1: the first iterator of the source + /// @param last1: the last iterator of the source + /// @param first2: the first iterator of the second source + /// @param destination: the first iterator of the destination + /// @param unaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + OutputIt + transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt destination, BinaryOperation unaryFunction) + { + return std::transform( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first1, + last1, + first2, + destination, + unaryFunction); + } + + //============================================================================ + // Method Description: + /// Copies the unique elements of a range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @return OutputIt + /// + template + constexpr OutputIt unique_copy(InputIt first, InputIt last, OutputIt destination) CONDITIONAL_NO_EXCEPT + { + return std::unique_copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination); + } + + //============================================================================ + // Method Description: + /// Copies the unique elements of a range + /// + /// @param first: the first iterator of the source + /// @param last: the last iterator of the source + /// @param destination: the first iterator of the destination + /// @param binaryFunction: the function to apply to the input iterators + /// @return OutputIt + /// + template + constexpr OutputIt unique_copy(InputIt first, InputIt last, OutputIt destination, BinaryPredicate binaryFunction) + CONDITIONAL_NO_EXCEPT + { + return std::unique_copy( +#ifdef PARALLEL_ALGORITHMS_SUPPORTED + std::execution::par_unseq, +#endif + first, + last, + destination, + binaryFunction); + } +} // namespace nc::stl_algorithms diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp new file mode 100644 index 0000000..fe81cf9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/TypeTraits.hpp @@ -0,0 +1,206 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Some helper routines for checking types +/// +#pragma once + +#include +#include + +namespace nc +{ + //============================================================================ + // Class Description: + /// Template class for determining if all of the types are arithmetic + /// + template + struct all_arithmetic; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are arithmetic + /// + template + struct all_arithmetic + { + static constexpr bool value = std::is_arithmetic::value && all_arithmetic::value; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are arithmetic + /// + template + struct all_arithmetic + { + static constexpr bool value = std::is_arithmetic::value; + }; + + //============================================================================ + // Class Description: + /// all_arithmetic helper + /// + template + constexpr bool all_arithmetic_v = all_arithmetic::value; + + //============================================================================ + // Class Description: + /// Template class for determining if all of the types are the same as another type + /// + template + struct all_same; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are the same as another type + /// + template + struct all_same + { + static constexpr bool value = std::is_same::value && all_same::value; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if all of the types are the same as another type + /// + template + struct all_same + { + static constexpr bool value = std::is_same::value; + }; + + //============================================================================ + // Class Description: + /// all_same helper + /// + template + constexpr bool all_same_v = all_same::value; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid dtype for NdArray + /// + template + struct is_valid_dtype + { + static constexpr bool value = + std::is_default_constructible::value && std::is_nothrow_copy_constructible::value && + std::is_nothrow_move_constructible::value && std::is_nothrow_copy_assignable::value && + std::is_nothrow_move_assignable::value && std::is_nothrow_destructible::value && + !std::is_void::value && !std::is_pointer::value && !std::is_array::value && + !std::is_union::value && !std::is_function::value && !std::is_abstract::value; + }; + + //============================================================================ + // Class Description: + /// is_valid_dtype helper + /// + template + constexpr bool is_valid_dtype_v = is_valid_dtype::value; + + // Forward declare + template + class NdArray; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index type for NdArray + /// + template + struct is_ndarray_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index typefor NdArray + /// + + template + struct is_ndarray_int> + { + static constexpr bool value = std::is_integral_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_int_v = is_ndarray_int::value; + + //============================================================================ + // Class Description: + /// is_ndarray_int + /// + template + using ndarray_int_concept = std::enable_if_t, int>; + + //============================================================================ + // Class Description: + /// Template class for determining if type is std::complex<> + /// + template + struct is_complex + { + static constexpr bool value = false; + }; + + //============================================================================ + // Class Description: + /// Template class specialization for determining if type is std::complex<> + /// + template + struct is_complex> + { + static constexpr bool value = true; + }; + + //============================================================================ + // Class Description: + /// is_complex helper + /// + template + constexpr bool is_complex_v = is_complex::value; + + //============================================================================ + // Class Description: + /// type trait to test if one value is larger than another at compile time + /// + template + struct greaterThan + { + static constexpr bool value = Value1 > Value2; + }; + + //============================================================================ + // Class Description: + /// greaterThan helper + /// + template + constexpr bool greaterThan_v = greaterThan::value; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Internal/Version.hpp b/runexamples/cpp/include/NumCpp/Core/Internal/Version.hpp new file mode 100644 index 0000000..998a5df --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Internal/Version.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Library version +/// +#pragma once + +namespace nc +{ + // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + constexpr char VERSION[] = "2.10.1"; ///< Current NumCpp version number +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Shape.hpp b/runexamples/cpp/include/NumCpp/Core/Shape.hpp new file mode 100644 index 0000000..05dc89d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Shape.hpp @@ -0,0 +1,163 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A Shape Class for NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + //================================================================================ + /// A Shape Class for NdArrays + class Shape + { + public: + //====================================Attributes============================== + uint32 rows{ 0 }; + uint32 cols{ 0 }; + + //============================================================================ + /// Constructor + /// + constexpr Shape() = default; + + //============================================================================ + /// Constructor + /// + /// @param inSquareSize + /// + constexpr explicit Shape(uint32 inSquareSize) noexcept : + rows(inSquareSize), + cols(inSquareSize) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inRows + /// @param inCols + /// + constexpr Shape(uint32 inRows, uint32 inCols) noexcept : + rows(inRows), + cols(inCols) + { + } + + //============================================================================ + /// Equality operator + /// + /// @param inOtherShape + /// + /// @return bool + /// + bool operator==(const Shape& inOtherShape) const noexcept + { + return rows == inOtherShape.rows && cols == inOtherShape.cols; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inOtherShape + /// + /// @return bool + /// + bool operator!=(const Shape& inOtherShape) const noexcept + { + return !(*this == inOtherShape); + } + + //============================================================================ + /// Returns the size of the shape + /// + /// @return size + /// + [[nodiscard]] uint32 size() const noexcept + { + return rows * cols; + } + + //============================================================================ + /// Returns whether the shape is null (constructed with the + /// default constructor). + /// + /// @return bool + /// + [[nodiscard]] bool isnull() const noexcept + { + return rows == 0 && cols == 0; + } + + //============================================================================ + /// Returns whether the shape is square or not. + /// + /// @return bool + /// + [[nodiscard]] bool issquare() const noexcept + { + return rows == cols; + } + + //============================================================================ + /// Returns the shape as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "[" + utils::num2str(rows) + ", " + utils::num2str(cols) + "]\n"; + return out; + } + + //============================================================================ + /// Prints the shape to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// IO operator for the Shape class + /// + /// @param inOStream + /// @param inShape + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Shape& inShape) + { + inOStream << inShape.str(); + return inOStream; + } + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Slice.hpp b/runexamples/cpp/include/NumCpp/Core/Slice.hpp new file mode 100644 index 0000000..1372573 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Slice.hpp @@ -0,0 +1,239 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A Class for slicing into NdArrays +/// + +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + //================================================================================ + /// A Class for slicing into NdArrays + class Slice + { + public: + //====================================Attributes============================== + int32 start{ 0 }; + int32 stop{ 1 }; + int32 step{ 1 }; + + //============================================================================ + /// Constructor + /// + constexpr Slice() = default; + + //============================================================================ + /// Constructor + /// + /// @param inStop (index not included) + /// + constexpr explicit Slice(int32 inStop) noexcept : + stop(inStop) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inStart + /// @param inStop (index not included) + /// + constexpr Slice(int32 inStart, int32 inStop) noexcept : + start(inStart), + stop(inStop) + { + } + + //============================================================================ + /// Constructor + /// + /// @param inStart + /// @param inStop (not included) + /// @param inStep + /// + constexpr Slice(int32 inStart, int32 inStop, int32 inStep) noexcept : + start(inStart), + stop(inStop), + step(inStep) + { + } + + //============================================================================ + /// Equality operator + /// + /// @param inOtherSlice + /// + /// @return bool + /// + bool operator==(const Slice& inOtherSlice) const noexcept + { + return start == inOtherSlice.start && stop == inOtherSlice.stop && step == inOtherSlice.step; + } + + //============================================================================ + /// Not equality operator + /// + /// @param inOtherSlice + /// + /// @return bool + /// + bool operator!=(const Slice& inOtherSlice) const noexcept + { + return !(*this == inOtherSlice); + } + + //============================================================================ + /// Prints the shape to the console + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = + "[" + utils::num2str(start) + ":" + utils::num2str(stop) + ":" + utils::num2str(step) + "]\n"; + return out; + } + + //============================================================================ + /// Prints the shape to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + /// Make the slice all positive and does some error checking + /// + /// @param inArraySize + /// + void makePositiveAndValidate(uint32 inArraySize) + { + /// convert the start value + if (start < 0) + { + start += static_cast(inArraySize); + } + if (start > static_cast(inArraySize - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid start value for array of size " + utils::num2str(inArraySize)); + } + + /// convert the stop value + if (stop < 0) + { + stop += static_cast(inArraySize); + } + if (stop > static_cast(inArraySize)) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid stop value for array of size " + utils::num2str(inArraySize)); + } + + /// do some error checking + if (start < stop) + { + if (step < 0) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid slice values [" + utils::num2str(start) + ", " + + utils::num2str(stop) + ", " + utils::num2str(step) + ']'); + } + } + + if (stop < start) + { + if (step > 0) + { + THROW_INVALID_ARGUMENT_ERROR("Invalid slice values [" + utils::num2str(start) + ", " + + utils::num2str(stop) + ", " + utils::num2str(step) + ']'); + } + + /// otherwise flip things around for my own sanity + std::swap(start, stop); + step *= -1; + } + } + + //============================================================================ + /// Returns the number of elements that the slice contains. + /// be aware that this method will also make the slice all + /// positive! + /// + /// @param inArraySize + /// + uint32 numElements(uint32 inArraySize) + { + makePositiveAndValidate(inArraySize); + + uint32 num = 0; + for (int32 i = start; i < stop; i += step) + { + ++num; + } + return num; + } + + //============================================================================ + /// Returns the indices that coorespond to the slice + /// be aware that this method will also make the slice all + /// positive! + /// + /// @param inArrayDimSize: the size of the dimension that is being sliced + /// + std::vector toIndices(uint32 inArrayDimSize) + { + std::vector indices; + indices.reserve(numElements(inArrayDimSize)); + for (int32 i = start; i < stop; i += step) + { + indices.push_back(static_cast(i)); + } + return indices; + } + + //============================================================================ + /// IO operator for the Slice class + /// + /// @param inOStream + /// @param inSlice + /// + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Slice& inSlice) + { + inOStream << inSlice.str(); + return inOStream; + } + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Timer.hpp b/runexamples/cpp/include/NumCpp/Core/Timer.hpp new file mode 100644 index 0000000..e42cafc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Timer.hpp @@ -0,0 +1,162 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A timer class for timing code execution +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc +{ + //================================================================================ + /// A timer class for timing code execution + template + class Timer + { + public: + //==============================Typedefs====================================== + using ChronoClock = std::chrono::high_resolution_clock; + using TimePoint = std::chrono::time_point; + + //============================================================================ + // Method Description: + /// Constructor + /// + Timer() : + start_(ChronoClock::now()) + { + setUnits(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inName + /// + explicit Timer(const std::string& inName) : + name_(inName + " "), + start_(ChronoClock::now()) + { + setUnits(); + } + + //============================================================================ + // Method Description: + /// Sets/changes the timer name + /// + /// @param inName + /// + void setName(const std::string& inName) + { + name_ = inName + " "; + } + + //============================================================================ + // Method Description: + /// Sleeps the current thread + /// + /// @param length: the length of time to sleep + /// + void sleep(uint32 length) + { + std::this_thread::sleep_for(TimeUnit(length)); + } + + //============================================================================ + // Method Description: + /// Starts the timer + /// + void tic() noexcept + { + start_ = ChronoClock::now(); + } + + //============================================================================ + // Method Description: + /// Stops the timer + /// + /// @param printElapsedTime: bool whether or not to print the elapsed time to + /// the console + /// @return ellapsed time in specified time units + /// + TimeUnit toc(bool printElapsedTime = true) + { + const auto duration = std::chrono::duration_cast(ChronoClock::now() - start_); + + if (printElapsedTime) + { + std::cout << name_ << "Elapsed Time = " << duration.count() << unit_ << std::endl; + } + + return duration; + } + + private: + //==============================Attributes==================================== + std::string name_{ "" }; + std::string unit_{ "" }; + TimePoint start_{}; + + void setUnits() + { + if constexpr (std::is_same_v) + { + unit_ = " hours"; + } + else if constexpr (std::is_same_v) + { + unit_ = " minutes"; + } + else if constexpr (std::is_same_v) + { + unit_ = " seconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " milliseconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " microseconds"; + } + else if constexpr (std::is_same_v) + { + unit_ = " nanoseconds"; + } + else + { + unit_ = " time units of some sort"; + } + } + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Core/Types.hpp b/runexamples/cpp/include/NumCpp/Core/Types.hpp new file mode 100644 index 0000000..9d484a5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Core/Types.hpp @@ -0,0 +1,61 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Usefull types +/// +#pragma once + +#include + +namespace nc +{ + //====================================Typedefs==================================== + using int64 = std::int64_t; + using int32 = std::int32_t; + using int16 = std::int16_t; + using int8 = std::int8_t; + using uint64 = std::uint64_t; + using uint32 = std::uint32_t; + using uint16 = std::uint16_t; + using uint8 = std::uint8_t; + + //================================================================================ + /// Enum To describe an axis + enum class Axis + { + NONE = 0, + ROW, + COL + }; + + //================================================================================ + /// Enum for endianess + enum class Endian + { + NATIVE = 0, + BIG, + LITTLE + }; +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/DateTime.hpp b/runexamples/cpp/include/NumCpp/DateTime.hpp new file mode 100644 index 0000000..a0f0968 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/DateTime.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// NumCpp DateTime module +/// +#pragma once + +#include "NumCpp/DateTime/Clock.hpp" +#include "NumCpp/DateTime/DateTime.hpp" diff --git a/runexamples/cpp/include/NumCpp/DateTime/Clock.hpp b/runexamples/cpp/include/NumCpp/DateTime/Clock.hpp new file mode 100644 index 0000000..a712777 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/DateTime/Clock.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include +#include + +namespace nc +{ + /** + * @brief Clock Type + */ + using Clock = std::chrono::system_clock; + + /** + * @brief Duration Type + */ + using Duration = std::chrono::nanoseconds; + + /** + * @brief TimePoint Type + */ + using TimePoint = std::chrono::time_point; + + /** + * @brief Output stream operator for the Duration type + * + * @param os: the output stream + * @param duration: the Duration + * @returns std::ostream + */ + inline std::ostream& operator<<(std::ostream& os, Duration duration) + { + os << duration.count() << " nanoseconds"; + return os; + } + + /** + * @brief Output stream operator for the TimePoint type + * + * @param os: the output stream + * @param timepoint: the TimePoint + * @returns std::ostream + */ + inline std::ostream& operator<<(std::ostream& os, const TimePoint& timepoint) + { + os << timepoint.time_since_epoch() << " nanoseconds since epoch"; + return os; + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/DateTime/DateTime.hpp b/runexamples/cpp/include/NumCpp/DateTime/DateTime.hpp new file mode 100644 index 0000000..2836f33 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/DateTime/DateTime.hpp @@ -0,0 +1,578 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// DateTime module +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "boost/date_time/posix_time/posix_time.hpp" + +#include "NumCpp/DateTime/Clock.hpp" + +namespace nc +{ + //================================================================================ + // Class Description: + /// Date Time class for working with iso formatted date times + class DateTime + { + public: + static constexpr int MAX_MONTH = 12; + static constexpr int MAX_DAY = 31; + static constexpr int MAX_HOUR = 23; + static constexpr int MAX_MINUTE = 59; + static constexpr int MAX_SECOND = 59; + + //============================================================================ + // Method Description: + /// Constructor + /// + DateTime() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param tp: a timepoint object + /// + explicit DateTime(const TimePoint& tp) + { + auto tpSubSeconds = std::chrono::duration_cast(tp.time_since_epoch()); + auto fractionalSecond = static_cast(tpSubSeconds.count() % Duration::period::den) / + static_cast(Duration::period::den); + auto time = Clock::to_time_t(std::chrono::time_point_cast(tp)); + std::tm tm{}; +#ifdef _MSC_VER + gmtime_s(&tm, &time); +#else + gmtime_r(&time, &tm); +#endif + + setYear(tm.tm_year + TM_EPOCH_YEAR); + setMonth(tm.tm_mon + 1); + setDay(tm.tm_mday); + setHour(tm.tm_hour); + setMinute(tm.tm_min); + setSecond(tm.tm_sec); + setFractionalSecond(fractionalSecond); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param timestamp: an iso formatted datetime string (0001-01-01T00:00:00.00000Z) + /// + explicit DateTime(const std::string& timestamp) : + DateTime(strToTimepoint(timestamp)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + ///@param year: year value + ///@param month: month value + ///@param day: day value + ///@param hour: hour value + ///@param minute: minute value + ///@param second: second value + ///@param fractionalSecond: fractionalSecond value + /// + DateTime(int year, int month, int day, int hour, int minute, int second, double fractionalSecond = 0.0) noexcept + : + year_(year), + month_(month), + day_(day), + hour_(hour), + minute_(minute), + second_(second), + fractionalSecond_(fractionalSecond) + { + } + + //============================================================================ + // Method Description: + ///@brief year getter + /// + ///@return int + /// + [[nodiscard]] int year() const noexcept + { + return year_; + } + + //============================================================================ + // Method Description: + ///@brief year setter + /// + ///@param year: year value + /// + void setYear(int year) + { + if (year < 0) + { + throw std::invalid_argument("input year must be greater than zero"); + } + year_ = year; + } + + //============================================================================ + // Method Description: + ///@brief month getter + /// + ///@return int + /// + [[nodiscard]] int month() const noexcept + { + return month_; + } + + //============================================================================ + // Method Description: + ///@brief month setter + /// + ///@param month: month value + /// + void setMonth(int month) + { + if (month < 1) + { + throw std::invalid_argument("input month must be greater than one"); + } + if (month > MAX_MONTH) + { + throw std::invalid_argument("input month must be less than DateTime::MAX_MONTH"); + } + month_ = month; + } + + //============================================================================ + // Method Description: + ///@brief day getter + /// + ///@return int + /// + [[nodiscard]] int day() const noexcept + { + return day_; + } + + //============================================================================ + // Method Description: + ///@brief day setter + /// + ///@param day: day value + /// + void setDay(int day) + { + if (day < 1) + { + throw std::invalid_argument("input day must be greater than one"); + } + if (day > MAX_DAY) + { + throw std::invalid_argument("input day must be less than DateTime::MAX_DAY"); + } + day_ = day; + } + + //============================================================================ + // Method Description: + ///@brief hour getter + /// + ///@return int + /// + [[nodiscard]] int hour() const noexcept + { + return hour_; + } + + //============================================================================ + // Method Description: + ///@brief hour setter + /// + ///@param hour: hour value + /// + void setHour(int hour) + { + if (hour < 0) + { + throw std::invalid_argument("input hour must be greater than zero"); + } + if (hour > MAX_HOUR) + { + throw std::invalid_argument("input hour must be less than DateTime::MAX_HOUR"); + } + hour_ = hour; + } + + //============================================================================ + // Method Description: + ///@brief minute getter + /// + ///@return int + /// + [[nodiscard]] int minute() const noexcept + { + return minute_; + } + + //============================================================================ + // Method Description: + ///@brief minute setter + /// + ///@param minute: minute value + /// + void setMinute(int minute) + { + if (minute < 0) + { + throw std::invalid_argument("input minute must be greater than zero"); + } + if (minute > MAX_MINUTE) + { + throw std::invalid_argument("input minute must be less than DateTime::MAX_MINUTE"); + } + minute_ = minute; + } + + //============================================================================ + // Method Description: + ///@brief second getter + /// + ///@return int + /// + [[nodiscard]] int second() const noexcept + { + return second_; + } + + //============================================================================ + // Method Description: + ///@brief second setter + /// + ///@param second: second value + /// + void setSecond(int second) + { + if (second < 0) + { + throw std::invalid_argument("input second must be greater than zero"); + } + if (second > MAX_SECOND) + { + throw std::invalid_argument("input second must be less than DateTime::MAX_SECOND"); + } + second_ = second; + } + + //============================================================================ + // Method Description: + ///@brief fractionalSecond getter + /// + ///@return double + /// + [[nodiscard]] double fractionalSecond() const noexcept + { + return fractionalSecond_; + } + + //============================================================================ + // Method Description: + ///@brief fractionalSecond setter + /// + ///@param fractionalSecond: fractionalSecond value + /// + void setFractionalSecond(double fractionalSecond) + { + if (fractionalSecond < 0. || fractionalSecond >= 1.) + { + throw std::invalid_argument("input fractionalSecond must be in the range [0, 1)"); + } + fractionalSecond_ = fractionalSecond; + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to a TimePoint + /// + ///@returns TimePoint + /// + [[nodiscard]] TimePoint toTimePoint() const + { + std::tm t{}; + t.tm_year = year_ - TM_EPOCH_YEAR; + t.tm_mon = month_ - 1; // tm is 0 based months + t.tm_mday = day_; + t.tm_hour = hour_; + t.tm_min = minute_; + t.tm_sec = second_; + auto timePoint = Clock::from_time_t( +#ifdef _MSC_VER + _mkgmtime +#else + timegm +#endif + (&t)); + return std::chrono::time_point_cast(timePoint) + + std::chrono::nanoseconds(static_cast(fractionalSecond_ * SECONDS_TO_NANOSECONDS)); + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to an iso string + /// + ///@returns std::string + /// + [[nodiscard]] std::string toStr() const + { + const auto timePoint = toTimePoint(); + const auto timeSinceEpoch = timePoint.time_since_epoch().count(); + time_t secondsFromEpoch = timeSinceEpoch / Duration::period::den; + const auto fractionalSeconds = static_cast(timeSinceEpoch % Duration::period::den) / + static_cast(Duration::period::den); + + std::tm tm{}; +#ifdef _MSC_VER + gmtime_s(&tm, &secondsFromEpoch); +#else + gmtime_r(&secondsFromEpoch, &tm); +#endif + + std::stringstream ss; + if (fractionalSeconds > 0) + { + const auto format = "%Y-%m-%dT%H:%M:%S.%msZ"; + std::stringstream ssFractionalSecond; + ssFractionalSecond.precision(NANO_SECOND_PRECESION); + ssFractionalSecond << std::fixed << fractionalSeconds; + auto fractionalSecondStr = ssFractionalSecond.str(); + // strip of the preceding "0." and any trailing zeros + fractionalSecondStr = fractionalSecondStr.substr(2, fractionalSecondStr.size()); + fractionalSecondStr = fractionalSecondStr.substr(0, fractionalSecondStr.find_last_not_of('0') + 1); + const auto fractionalSecondsFormat = std::regex_replace(format, std::regex("%ms"), fractionalSecondStr); + ss << std::put_time(&tm, fractionalSecondsFormat.c_str()); + } + else + { + const auto format = "%Y-%m-%dT%H:%M:%SZ"; + ss << std::put_time(&tm, format); + } + + return ss.str(); + } + + //============================================================================ + // Method Description: + ///@brief Factory static method for returning a DateTime object + /// cooresponding to the system clock now. + /// + ///@returns DateTime + /// + [[nodiscard]] static DateTime now() noexcept + { + return DateTime(Clock::now()); + } + + //============================================================================ + // Method Description: + ///@brief Converts the struct to an iso string + ///@param timestamp: an iso formatted datetime string (0001-01-01T00:00:00.00000Z) + ///@returns Timepoint + /// + static TimePoint strToTimepoint(const std::string& timestamp) + { + const std::regex regexIsoTime{ R"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(.\d+)?Z)" }; + if (!std::regex_match(timestamp, regexIsoTime)) + { + throw std::invalid_argument("Invalid iso timestamp format"); + } + + auto convertedTime = boost::posix_time::ptime{}; + try + { + convertedTime = boost::posix_time::from_iso_extended_string(timestamp.substr(0, timestamp.size() - 1)); + } + catch (...) + { + throw std::invalid_argument("Invalid iso timestamp format"); + } + + const auto fromEpoch = convertedTime - POSIX_EPOCH; + return TimePoint{ Duration{ fromEpoch.total_nanoseconds() } }; + } + + private: + static constexpr int TM_EPOCH_YEAR = 1900; + static constexpr int POSIX_EPOCH_YEAR = 1970; + static inline const std::string POSIX_EPOCH_STR{ "1970-01-01T00:00:00" }; + static inline const boost::posix_time::ptime POSIX_EPOCH{ boost::posix_time::from_iso_extended_string( + POSIX_EPOCH_STR) }; + static constexpr double SECONDS_TO_NANOSECONDS = 1e9; + static constexpr int NANO_SECOND_PRECESION = 9; + + /// years since 1 + int year_{ POSIX_EPOCH_YEAR }; + /// [1, 12] + int month_{ 1 }; + /// [1, 31] + int day_{ 1 }; + /// [0, 23] + int hour_{ 0 }; + /// [0, 59] + int minute_{ 0 }; + /// [0, 59] + int second_{ 0 }; + /// [0, 1) + double fractionalSecond_{ 0.0 }; + }; + + //============================================================================ + // Method Description: + ///@brief Equality operator for DateTime + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator==(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() == rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Non Equality operator for DateTime + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator!=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return !(lhs == rhs); + } + + //============================================================================ + // Method Description: + ///@brief Less than operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator<(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() < rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Less than or equal operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator<=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() <= rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Greater than operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator>(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() > rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Greater than or equal operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline bool operator>=(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() >= rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + ///@brief Subtraction operator + /// + ///@param lhs: the left hand side value + ///@param rhs: the right hand side value + ///@returns bool + /// + [[nodiscard]] inline Duration operator-(const DateTime& lhs, const DateTime& rhs) noexcept + { + return lhs.toTimePoint() - rhs.toTimePoint(); + } + + //============================================================================ + // Method Description: + /// @brief Stream operator + /// + /// @param os: the output stream + /// @param datetime: the datetime object + /// @returns ostream + /// + inline std::ostream& operator<<(std::ostream& os, const DateTime& datetime) noexcept + { + os << "DateTime:\n"; + os << "\tyear: " << datetime.year() << '\n'; + os << "\tmonth: " << datetime.month() << '\n'; + os << "\tday: " << datetime.day() << '\n'; + os << "\thour: " << datetime.hour() << '\n'; + os << "\tminute: " << datetime.minute() << '\n'; + os << "\tsecond: " << datetime.second() << '\n'; + os << "\tfractionalSecond: " << datetime.fractionalSecond() << '\n'; + return os; + } +} // namespace nc + +#endif diff --git a/runexamples/cpp/include/NumCpp/Filter.hpp b/runexamples/cpp/include/NumCpp/Filter.hpp new file mode 100644 index 0000000..0bb6df3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Image and signal filtering module +/// +#pragma once + +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/convolve1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp" +#include "NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/laplace.hpp" +#include "NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/medianFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/rankFilter.hpp" +#include "NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp" diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp new file mode 100644 index 0000000..608a7cb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundaryType + /// @param inKernalSize + /// @param inConstantValue (default 0) + /// @return NdArray + /// + template + NdArray addBoundary1d(const NdArray& inImage, + Boundary inBoundaryType, + uint32 inKernalSize, + dtype inConstantValue = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inKernalSize % 2 == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input kernal size must be an odd value."); + } + + const uint32 boundarySize = inKernalSize / 2; // integer division + + switch (inBoundaryType) + { + case Boundary::REFLECT: + { + return reflect1d(inImage, boundarySize); + } + case Boundary::CONSTANT: + { + return constant1d(inImage, boundarySize, inConstantValue); + } + case Boundary::NEAREST: + { + return nearest1d(inImage, boundarySize); + } + case Boundary::MIRROR: + { + return mirror1d(inImage, boundarySize); + } + case Boundary::WRAP: + { + return wrap1d(inImage, boundarySize); + } + default: + { + // This can't actually happen but just adding to get rid of compiler warning + THROW_INVALID_ARGUMENT_ERROR("ERROR!"); + } + } + + return NdArray(); // get rid of compiler warning + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp new file mode 100644 index 0000000..c373a2a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/constant1d.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Constant boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Constant boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @param inConstantValue + /// @return NdArray + /// + template + NdArray constant1d(const NdArray& inImage, uint32 inBoundarySize, dtype inConstantValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inConstantValue); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inConstantValue); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp new file mode 100644 index 0000000..c6b97b5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/mirror1d.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Mirror boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Mirror boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray mirror1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), fliplr(inImage[Slice(1, inBoundarySize + 1)])); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), + fliplr(inImage[Slice(-static_cast(inBoundarySize) - 1, -1)])); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp new file mode 100644 index 0000000..e52f739 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/nearest1d.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Nearest boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Nearest boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray nearest1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inImage.front()); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inImage.back()); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp new file mode 100644 index 0000000..1794286 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/reflect1d.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Reflects the boundaries +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Reflects the boundaries + /// + /// @param inImage + /// @param inBoundarySize + /// + /// @return NdArray + /// + template + NdArray reflect1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), fliplr(inImage[Slice(0, inBoundarySize)])); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), + fliplr(inImage[Slice(-static_cast(inBoundarySize), inImage.size())])); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp new file mode 100644 index 0000000..cc8d331 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/trimBoundary1d.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// trims the boundary off to make the image back to the original size +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// trims the boundary off to make the image back to the original size + /// + /// @param inImageWithBoundary + /// @param inSize + /// @return NdArray + /// + template + NdArray trimBoundary1d(const NdArray& inImageWithBoundary, uint32 inSize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + uint32 boundarySize = inSize / 2; // integer division + uint32 imageSize = inImageWithBoundary.size() - boundarySize * 2; + + return inImageWithBoundary[Slice(boundarySize, boundarySize + imageSize)]; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp new file mode 100644 index 0000000..041433e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries1d/wrap1d.hpp @@ -0,0 +1,63 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary1d +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary1d + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray wrap1d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 outSize = inImage.size() + inBoundarySize * 2; + + NdArray outArray(1, outSize); + outArray.put(Slice(inBoundarySize, inBoundarySize + inImage.size()), inImage); + + // left + outArray.put(Slice(0, inBoundarySize), inImage[Slice(inImage.size() - inBoundarySize, inImage.size())]); + + // right + outArray.put(Slice(inImage.size() + inBoundarySize, outSize), inImage[Slice(0, inBoundarySize)]); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp new file mode 100644 index 0000000..30247ec --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundaryType + /// @param inKernalSize + /// @param inConstantValue (default 0) + /// @return NdArray + /// + template + NdArray addBoundary2d(const NdArray& inImage, + Boundary inBoundaryType, + uint32 inKernalSize, + dtype inConstantValue = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inKernalSize % 2 == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input kernal size must be an odd value."); + } + + const uint32 boundarySize = inKernalSize / 2; // integer division + + switch (inBoundaryType) + { + case Boundary::REFLECT: + { + return reflect2d(inImage, boundarySize); + } + case Boundary::CONSTANT: + { + return constant2d(inImage, boundarySize, inConstantValue); + } + case Boundary::NEAREST: + { + return nearest2d(inImage, boundarySize); + } + case Boundary::MIRROR: + { + return mirror2d(inImage, boundarySize); + } + case Boundary::WRAP: + { + return wrap2d(inImage, boundarySize); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp new file mode 100644 index 0000000..8ba96ae --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/constant2d.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Constant boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Constant boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @param inConstantValue + /// @return NdArray + /// + template + NdArray constant2d(const NdArray& inImage, uint32 inBoundarySize, dtype inConstantValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + fillCorners(outArray, inBoundarySize, inConstantValue); + + outArray.put(Slice(0, inBoundarySize), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inConstantValue); /// bottom + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inConstantValue); /// top + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(0, inBoundarySize), + inConstantValue); /// left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + inConstantValue); /// right + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp new file mode 100644 index 0000000..2edd38f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// extends the corner values +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// extends the corner values + /// + /// @param inArray + /// @param inBorderWidth + /// + template + void fillCorners(NdArray& inArray, uint32 inBorderWidth) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + const auto numRows = static_cast(inShape.rows); + const auto numCols = static_cast(inShape.cols); + + // top left + inArray.put(Slice(0, inBorderWidth), Slice(0, inBorderWidth), inArray(inBorderWidth, inBorderWidth)); + + // top right + inArray.put(Slice(0, inBorderWidth), + Slice(numCols - inBorderWidth, numCols), + inArray(inBorderWidth, numCols - inBorderWidth - 1)); + + // bottom left + inArray.put(Slice(numRows - inBorderWidth, numRows), + Slice(0, inBorderWidth), + inArray(numRows - inBorderWidth - 1, inBorderWidth)); + + // bottom right + inArray.put(Slice(numRows - inBorderWidth, numRows), + Slice(numCols - inBorderWidth, numCols), + inArray(numRows - inBorderWidth - 1, numCols - inBorderWidth - 1)); + } + + //============================================================================ + // Method Description: + /// extends the corner values + /// + /// @param inArray + /// @param inBorderWidth + /// @param inFillValue + /// + template + void fillCorners(NdArray& inArray, uint32 inBorderWidth, dtype inFillValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + const auto numRows = static_cast(inShape.rows); + const auto numCols = static_cast(inShape.cols); + + // top left + inArray.put(Slice(0, inBorderWidth), Slice(0, inBorderWidth), inFillValue); + + // top right + inArray.put(Slice(0, inBorderWidth), Slice(numCols - inBorderWidth, numCols), inFillValue); + + // bottom left + inArray.put(Slice(numRows - inBorderWidth, numRows), Slice(0, inBorderWidth), inFillValue); + + // bottom right + inArray.put(Slice(numRows - inBorderWidth, numRows), Slice(numCols - inBorderWidth, numCols), inFillValue); + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp new file mode 100644 index 0000000..449f949 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/mirror2d.hpp @@ -0,0 +1,109 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Mirror boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Mirror boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray mirror2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inBoundarySize - row, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - row - 2, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col, + inImage(Slice(0, inShape.rows), inBoundarySize - col)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - col - 2)); + } + + // now fill in the corners + NdArray lowerLeft = + flipud(outArray(Slice(inBoundarySize + 1, 2 * inBoundarySize + 1), Slice(0, inBoundarySize))); + NdArray lowerRight = flipud(outArray(Slice(inBoundarySize + 1, 2 * inBoundarySize + 1), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize - 1; + NdArray upperLeft = + flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize))); + NdArray upperRight = flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), lowerRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + upperRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp new file mode 100644 index 0000000..13b9afc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/nearest2d.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Nearest boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Nearest boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray nearest2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + fillCorners(outArray, inBoundarySize); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, Slice(inBoundarySize, inBoundarySize + inShape.cols), inImage(0, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - 1, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), col, inImage(Slice(0, inShape.rows), 0)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - 1)); + } + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp new file mode 100644 index 0000000..c1fdde0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/reflect2d.hpp @@ -0,0 +1,110 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Reflects the boundaries +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Reflects the boundaries + /// + /// @param inImage + /// @param inBoundarySize + /// + /// @return NdArray + /// + template + NdArray reflect2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + for (uint32 row = 0; row < inBoundarySize; ++row) + { + // bottom + outArray.put(row, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inBoundarySize - row - 1, Slice(0, inShape.cols))); + + // top + outArray.put(row + inBoundarySize + inShape.rows, + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(inShape.rows - row - 1, Slice(0, inShape.cols))); + } + + for (uint32 col = 0; col < inBoundarySize; ++col) + { + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col, + inImage(Slice(0, inShape.rows), inBoundarySize - col - 1)); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + col + inBoundarySize + inShape.cols, + inImage(Slice(0, inShape.rows), inShape.cols - col - 1)); + } + + // now fill in the corners + NdArray lowerLeft = + flipud(outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(0, inBoundarySize))); + NdArray lowerRight = flipud( + outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols))); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize; + NdArray upperLeft = + flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize))); + NdArray upperRight = flipud(outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols))); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), lowerRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + upperRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp new file mode 100644 index 0000000..68930be --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/trimBoundary2d.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// trims the boundary off to make the image back to the original size +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// trims the boundary off to make the image back to the original size + /// + /// @param inImageWithBoundary + /// @param inSize + /// @return NdArray + /// + template + NdArray trimBoundary2d(const NdArray& inImageWithBoundary, uint32 inSize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + Shape inShape = inImageWithBoundary.shape(); + uint32 boundarySize = inSize / 2; /// integer division + + inShape.rows -= boundarySize * 2; + inShape.cols -= boundarySize * 2; + + return inImageWithBoundary(Slice(boundarySize, boundarySize + inShape.rows), + Slice(boundarySize, boundarySize + inShape.cols)); + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp new file mode 100644 index 0000000..1980cb9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundaries2d/wrap2d.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Wrap boundary +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/fillCorners.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter::boundary +{ + //============================================================================ + // Method Description: + /// Wrap boundary + /// + /// @param inImage + /// @param inBoundarySize + /// @return NdArray + /// + template + NdArray wrap2d(const NdArray& inImage, uint32 inBoundarySize) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inImage.shape(); + Shape outShape(inShape); + outShape.rows += inBoundarySize * 2; + outShape.cols += inBoundarySize * 2; + + NdArray outArray(outShape); + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage); + + // bottom + outArray.put(Slice(0, inBoundarySize), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(Slice(inShape.rows - inBoundarySize, inShape.rows), Slice(0, inShape.cols))); + + // top + outArray.put(Slice(inShape.rows + inBoundarySize, outShape.rows), + Slice(inBoundarySize, inBoundarySize + inShape.cols), + inImage(Slice(0, inBoundarySize), Slice(0, inShape.cols))); + + // left + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(0, inBoundarySize), + inImage(Slice(0, inShape.rows), Slice(inShape.cols - inBoundarySize, inShape.cols))); + + // right + outArray.put(Slice(inBoundarySize, inBoundarySize + inShape.rows), + Slice(inShape.cols + inBoundarySize, outShape.cols), + inImage(Slice(0, inShape.rows), Slice(0, inBoundarySize))); + + // now fill in the corners + NdArray lowerLeft = outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(0, inBoundarySize)); + NdArray lowerRight = + outArray(Slice(inBoundarySize, 2 * inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols)); + + const uint32 upperRowStart = outShape.rows - 2 * inBoundarySize; + NdArray upperLeft = + outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), Slice(0, inBoundarySize)); + NdArray upperRight = outArray(Slice(upperRowStart, upperRowStart + inBoundarySize), + Slice(outShape.cols - inBoundarySize, outShape.cols)); + + outArray.put(Slice(0, inBoundarySize), Slice(0, inBoundarySize), upperLeft); + outArray.put(Slice(0, inBoundarySize), Slice(outShape.cols - inBoundarySize, outShape.cols), upperRight); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), Slice(0, inBoundarySize), lowerLeft); + outArray.put(Slice(outShape.rows - inBoundarySize, outShape.rows), + Slice(outShape.cols - inBoundarySize, outShape.cols), + lowerRight); + + return outArray; + } +} // namespace nc::filter::boundary diff --git a/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp new file mode 100644 index 0000000..50d8373 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Boundaries/Boundary.hpp @@ -0,0 +1,43 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Boundary condition to apply to the image filter +/// +#pragma once + +namespace nc::filter +{ + //================================================================================ + // Enum Description: + /// Boundary condition to apply to the image filter + enum class Boundary + { + REFLECT = 0, + CONSTANT, + NEAREST, + MIRROR, + WRAP + }; +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp new file mode 100644 index 0000000..41172c9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/complementaryMedianFilter1d.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate a one-dimensional complemenatry median filter. +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate a one-dimensional complemenatry median filter. + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray complementaryMedianFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray inImageArrayCopy(inImageArray); + inImageArrayCopy -= medianFilter1d(inImageArray, inSize, inBoundaryType, inConstantValue); + + return inImageArrayCopy; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp new file mode 100644 index 0000000..7b4fd7f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/convolve1d.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional kernel convolution. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional kernel convolution. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve1d.html#scipy.ndimage.convolve1d + /// + /// @param inImageArray + /// @param inWeights + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray convolve1d(const NdArray& inImageArray, + const NdArray& inWeights, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + const uint32 boundarySize = inWeights.size() / 2; // integer division + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inWeights.size(), inConstantValue); + NdArray output(1, inImageArray.size()); + + NdArray weightsFlat = fliplr(inWeights.flatten()); + + const uint32 endPointRow = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPointRow; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)].flatten(); + + output[i - boundarySize] = dot(window, weightsFlat).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp new file mode 100644 index 0000000..cdd3b34 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/gaussianFilter1d.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate a one-dimensional gaussian filter. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters1d/convolve1d.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/gaussian1d.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate a one-dimensional gaussian filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generic_filter1d.html#scipy.ndimage.generic_filter1d + /// + /// @param inImageArray + /// @param inSigma: Standard deviation for Gaussian kernel + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray gaussianFilter1d(const NdArray& inImageArray, + double inSigma, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero."); + } + + // calculate the kernel size based off of the input sigma value + constexpr uint32 MIN_KERNEL_SIZE = 5; + uint32 kernelSize = + std::max(static_cast(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations + if (kernelSize % 2 == 0) + { + ++kernelSize; // make sure the kernel is an odd size + } + + const auto kernalHalfSize = static_cast(kernelSize / 2); // integer division + + // calculate the gaussian kernel + NdArray kernel(1, kernelSize); + for (double i = 0; i < kernelSize; ++i) + { + kernel[static_cast(i)] = utils::gaussian1d(i - kernalHalfSize, 0., inSigma); + } + + // normalize the kernel + kernel /= kernel.sum().item(); + + // perform the convolution + NdArray output = + convolve1d(inImageArray.template astype(), kernel, inBoundaryType, inConstantValue) + .template astype(); + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp new file mode 100644 index 0000000..7dab32c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/maximumFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional maximum filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional maximum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.maximum_filter1d.html#scipy.ndimage.maximum_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray maximumFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.max().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp new file mode 100644 index 0000000..55177c9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/medianFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional median filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional median filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray medianFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.median().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp new file mode 100644 index 0000000..7912e76 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/minimumFilter1d.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional minumum filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional minumum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.minimum_filter1d.html#scipy.ndimage.minimum_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray minumumFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = window.min().item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp new file mode 100644 index 0000000..0f03fe8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/percentileFilter1d.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional percentile filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional percentile filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.percentile_filter.html#scipy.ndimage.percentile_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inPercentile: percentile [0, 100] + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray percentileFilter1d(const NdArray& inImageArray, + uint32 inSize, + double inPercentile, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = percentile(window, inPercentile).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp new file mode 100644 index 0000000..4d3191d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/rankFilter1d.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional rank filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional rank filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rank_filter.html#scipy.ndimage.rank_filter + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inRank: ([0, inSize^2 - 1]) + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray rankFilter1d(const NdArray& inImageArray, + uint32 inSize, + uint8 inRank, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = sort(window)[inRank]; + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp new file mode 100644 index 0000000..ceb58ad --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters1d/uniformFilter1d.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a one-dimensional uniform filter. +/// +#pragma once + +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries1d/addBoundary1d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a one-dimensional uniform filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter1d.html#scipy.ndimage.uniform_filter1d + /// + /// @param inImageArray + /// @param inSize: linear size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray uniformFilter1d(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary1d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(1, inImageArray.size()); + + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPoint = boundarySize + inImageArray.size(); + + for (uint32 i = boundarySize; i < endPoint; ++i) + { + NdArray window = arrayWithBoundary[Slice(i - boundarySize, i + boundarySize + 1)]; + + output[i - boundarySize] = mean(window).item(); + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp new file mode 100644 index 0000000..39c2343 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/complementaryMedianFilter.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional complemenatry median filter. +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Filter/Filters/Filters2d/medianFilter.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional complemenatry median filter. + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray complementaryMedianFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray inImageArrayCopy(inImageArray); + inImageArrayCopy -= medianFilter(inImageArray, inSize, inBoundaryType, inConstantValue); + + return inImageArrayCopy; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp new file mode 100644 index 0000000..75895b1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/convolve.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional kernel convolution. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Filter/Boundaries/Boundary.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/rot90.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional kernel convolution. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inWeights + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray convolve(const NdArray& inImageArray, + uint32 inSize, + const NdArray& inWeights, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inWeights.size() != utils::sqr(inSize)) + { + THROW_INVALID_ARGUMENT_ERROR("input weights do no match input kernal size."); + } + + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + NdArray weightsFlat = rot90(inWeights, 2).flatten(); + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)) + .flatten(); + + output(row - boundarySize, col - boundarySize) = dot(window, weightsFlat).item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp new file mode 100644 index 0000000..b0bc098 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/gaussianFilter.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional gaussian filter. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/gaussian.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional gaussian filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter.html#scipy.ndimage.gaussian_filter + /// + /// @param inImageArray + /// @param inSigma: Standard deviation for Gaussian kernel + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray gaussianFilter(const NdArray& inImageArray, + double inSigma, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero."); + } + + // calculate the kernel size based off of the input sigma value + constexpr uint32 MIN_KERNEL_SIZE = 5; + uint32 kernelSize = + std::max(static_cast(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations + if (kernelSize % 2 == 0) + { + ++kernelSize; // make sure the kernel is an odd size + } + + const auto kernalHalfSize = static_cast(kernelSize / 2); // integer division + + // calculate the gaussian kernel + NdArray kernel(kernelSize); + for (double row = 0; row < kernelSize; ++row) + { + for (double col = 0; col < kernelSize; ++col) + { + kernel(static_cast(row), static_cast(col)) = + utils::gaussian(row - kernalHalfSize, col - kernalHalfSize, inSigma); + } + } + + // normalize the kernel + kernel /= kernel.sum().item(); + + // perform the convolution + NdArray output = + convolve(inImageArray.template astype(), kernelSize, kernel, inBoundaryType, inConstantValue) + .template astype(); + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp new file mode 100644 index 0000000..f3e396f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/laplace.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculate the 2D laplace filter. +/// +#pragma once + +#include "NumCpp/Filter/Filters/Filters2d/convolve.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculate the 2D laplace filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.laplace.html#scipy.ndimage.laplace + /// + /// @param inImageArray + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray laplace(const NdArray& inImageArray, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray kernel = { { 0, 1, 0 }, { 1, -4, 1 }, { 0, 1, 0 } }; + return convolve(inImageArray, 3, kernel, inBoundaryType, inConstantValue); + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp new file mode 100644 index 0000000..3fad820 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/maximumFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional maximum filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional maximum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.maximum_filter.html#scipy.ndimage.maximum_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray maximumFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.max().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp new file mode 100644 index 0000000..863eed7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/medianFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional median filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional median filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray medianFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.median().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp new file mode 100644 index 0000000..f86ed44 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/minimumFilter.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional minimum filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional minimum filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.minimum_filter.html#scipy.ndimage.minimum_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray minimumFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = window.min().item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp new file mode 100644 index 0000000..2d3341d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/percentileFilter.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional percentile filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional percentile filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.percentile_filter.html#scipy.ndimage.percentile_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inPercentile: percentile [0, 100] + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray percentileFilter(const NdArray& inImageArray, + uint32 inSize, + double inPercentile, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = + percentile(window, inPercentile, Axis::NONE, "nearest").item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp new file mode 100644 index 0000000..1c977d7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/rankFilter.hpp @@ -0,0 +1,90 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional rank filter. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional rank filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rank_filter.html#scipy.ndimage.rank_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inRank: ([0, inSize^2 - 1]) + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray rankFilter(const NdArray& inImageArray, + uint32 inSize, + uint32 inRank, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + if (inRank >= utils::sqr(inSize)) + { + THROW_INVALID_ARGUMENT_ERROR("rank not within filter footprint size."); + } + + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = sort(window)[inRank]; + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp new file mode 100644 index 0000000..e034e8b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Filter/Filters/Filters2d/uniformFilter.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Calculates a multidimensional uniform filter. +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Filter/Boundaries/Boundaries2d/addBoundary2d.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::filter +{ + //============================================================================ + // Method Description: + /// Calculates a multidimensional uniform filter. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter.html#scipy.ndimage.uniform_filter + /// + /// @param inImageArray + /// @param inSize: square size of the kernel to apply + /// @param inBoundaryType: boundary mode (default Reflect) options (reflect, constant, nearest, mirror, wrap) + /// @param inConstantValue: contant value if boundary = 'constant' (default 0) + /// @return NdArray + /// + template + NdArray uniformFilter(const NdArray& inImageArray, + uint32 inSize, + Boundary inBoundaryType = Boundary::REFLECT, + dtype inConstantValue = 0) + { + NdArray arrayWithBoundary = + boundary::addBoundary2d(inImageArray, inBoundaryType, inSize, inConstantValue); + NdArray output(inImageArray.shape()); + + const Shape inShape = inImageArray.shape(); + const uint32 boundarySize = inSize / 2; // integer division + const uint32 endPointRow = boundarySize + inShape.rows; + const uint32 endPointCol = boundarySize + inShape.cols; + + for (uint32 row = boundarySize; row < endPointRow; ++row) + { + for (uint32 col = boundarySize; col < endPointCol; ++col) + { + NdArray window = arrayWithBoundary(Slice(row - boundarySize, row + boundarySize + 1), + Slice(col - boundarySize, col + boundarySize + 1)); + + output(row - boundarySize, col - boundarySize) = mean(window).item(); + } + } + + return output; + } +} // namespace nc::filter diff --git a/runexamples/cpp/include/NumCpp/Functions.hpp b/runexamples/cpp/include/NumCpp/Functions.hpp new file mode 100644 index 0000000..5e6509f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions.hpp @@ -0,0 +1,288 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Methods for interacting with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/abs.hpp" +#include "NumCpp/Functions/add.hpp" +#include "NumCpp/Functions/alen.hpp" +#include "NumCpp/Functions/all.hpp" +#include "NumCpp/Functions/allclose.hpp" +#include "NumCpp/Functions/amax.hpp" +#include "NumCpp/Functions/amin.hpp" +#include "NumCpp/Functions/angle.hpp" +#include "NumCpp/Functions/any.hpp" +#include "NumCpp/Functions/append.hpp" +#include "NumCpp/Functions/applyFunction.hpp" +#include "NumCpp/Functions/applyPoly1d.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/Functions/arccos.hpp" +#include "NumCpp/Functions/arccosh.hpp" +#include "NumCpp/Functions/arcsin.hpp" +#include "NumCpp/Functions/arcsinh.hpp" +#include "NumCpp/Functions/arctan.hpp" +#include "NumCpp/Functions/arctan2.hpp" +#include "NumCpp/Functions/arctanh.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/argsort.hpp" +#include "NumCpp/Functions/argwhere.hpp" +#include "NumCpp/Functions/around.hpp" +#include "NumCpp/Functions/array_equal.hpp" +#include "NumCpp/Functions/array_equiv.hpp" +#include "NumCpp/Functions/asarray.hpp" +#include "NumCpp/Functions/astype.hpp" +#include "NumCpp/Functions/average.hpp" +#include "NumCpp/Functions/bartlett.hpp" +#include "NumCpp/Functions/binaryRepr.hpp" +#include "NumCpp/Functions/bincount.hpp" +#include "NumCpp/Functions/bit_count.hpp" +#include "NumCpp/Functions/bitwise_and.hpp" +#include "NumCpp/Functions/bitwise_not.hpp" +#include "NumCpp/Functions/bitwise_or.hpp" +#include "NumCpp/Functions/bitwise_xor.hpp" +#include "NumCpp/Functions/blackman.hpp" +#include "NumCpp/Functions/byteswap.hpp" +#include "NumCpp/Functions/cbrt.hpp" +#include "NumCpp/Functions/ceil.hpp" +#include "NumCpp/Functions/centerOfMass.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/complex.hpp" +#include "NumCpp/Functions/concatenate.hpp" +#include "NumCpp/Functions/conj.hpp" +#include "NumCpp/Functions/contains.hpp" +#include "NumCpp/Functions/copy.hpp" +#include "NumCpp/Functions/copySign.hpp" +#include "NumCpp/Functions/copyto.hpp" +#include "NumCpp/Functions/corrcoef.hpp" +#include "NumCpp/Functions/cos.hpp" +#include "NumCpp/Functions/cosh.hpp" +#include "NumCpp/Functions/count_nonzero.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Functions/cov_inv.hpp" +#include "NumCpp/Functions/cross.hpp" +#include "NumCpp/Functions/cube.hpp" +#include "NumCpp/Functions/cumprod.hpp" +#include "NumCpp/Functions/cumsum.hpp" +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/Functions/degrees.hpp" +#include "NumCpp/Functions/deleteIndices.hpp" +#include "NumCpp/Functions/diag.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Functions/diagonal.hpp" +#include "NumCpp/Functions/diff.hpp" +#include "NumCpp/Functions/digitize.hpp" +#include "NumCpp/Functions/divide.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/dump.hpp" +#include "NumCpp/Functions/empty.hpp" +#include "NumCpp/Functions/empty_like.hpp" +#include "NumCpp/Functions/endianess.hpp" +#include "NumCpp/Functions/equal.hpp" +#include "NumCpp/Functions/exp.hpp" +#include "NumCpp/Functions/exp2.hpp" +#include "NumCpp/Functions/expm1.hpp" +#include "NumCpp/Functions/extract.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/fillDiagnol.hpp" +#include "NumCpp/Functions/find.hpp" +#include "NumCpp/Functions/fix.hpp" +#include "NumCpp/Functions/flatnonzero.hpp" +#include "NumCpp/Functions/flatten.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/Functions/floor.hpp" +#include "NumCpp/Functions/floor_divide.hpp" +#include "NumCpp/Functions/fmax.hpp" +#include "NumCpp/Functions/fmin.hpp" +#include "NumCpp/Functions/fmod.hpp" +#include "NumCpp/Functions/frombuffer.hpp" +#include "NumCpp/Functions/fromfile.hpp" +#include "NumCpp/Functions/fromfunction.hpp" +#include "NumCpp/Functions/fromiter.hpp" +#include "NumCpp/Functions/fromstring.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/Functions/full_like.hpp" +#include "NumCpp/Functions/gcd.hpp" +#include "NumCpp/Functions/geomspace.hpp" +#include "NumCpp/Functions/gradient.hpp" +#include "NumCpp/Functions/greater.hpp" +#include "NumCpp/Functions/greater_equal.hpp" +#include "NumCpp/Functions/hamming.hpp" +#include "NumCpp/Functions/hammingEncode.hpp" +#include "NumCpp/Functions/hanning.hpp" +#include "NumCpp/Functions/histogram.hpp" +#include "NumCpp/Functions/hsplit.hpp" +#include "NumCpp/Functions/hstack.hpp" +#include "NumCpp/Functions/hypot.hpp" +#include "NumCpp/Functions/identity.hpp" +#include "NumCpp/Functions/imag.hpp" +#include "NumCpp/Functions/inner.hpp" +#include "NumCpp/Functions/insert.hpp" +#include "NumCpp/Functions/interp.hpp" +#include "NumCpp/Functions/intersect1d.hpp" +#include "NumCpp/Functions/invert.hpp" +#include "NumCpp/Functions/isclose.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/Functions/isneginf.hpp" +#include "NumCpp/Functions/isposinf.hpp" +#include "NumCpp/Functions/kaiser.hpp" +#include "NumCpp/Functions/lcm.hpp" +#include "NumCpp/Functions/ldexp.hpp" +#include "NumCpp/Functions/left_shift.hpp" +#include "NumCpp/Functions/less.hpp" +#include "NumCpp/Functions/less_equal.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/Functions/load.hpp" +#include "NumCpp/Functions/log.hpp" +#include "NumCpp/Functions/log10.hpp" +#include "NumCpp/Functions/log1p.hpp" +#include "NumCpp/Functions/log2.hpp" +#include "NumCpp/Functions/logaddexp.hpp" +#include "NumCpp/Functions/logaddexp2.hpp" +#include "NumCpp/Functions/logb.hpp" +#include "NumCpp/Functions/logical_and.hpp" +#include "NumCpp/Functions/logical_not.hpp" +#include "NumCpp/Functions/logical_or.hpp" +#include "NumCpp/Functions/logical_xor.hpp" +#include "NumCpp/Functions/logspace.hpp" +#include "NumCpp/Functions/matmul.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/Functions/maximum.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/Functions/median.hpp" +#include "NumCpp/Functions/meshgrid.hpp" +#include "NumCpp/Functions/min.hpp" +#include "NumCpp/Functions/minimum.hpp" +#include "NumCpp/Functions/mod.hpp" +#include "NumCpp/Functions/multiply.hpp" +#include "NumCpp/Functions/nan_to_num.hpp" +#include "NumCpp/Functions/nanargmax.hpp" +#include "NumCpp/Functions/nanargmin.hpp" +#include "NumCpp/Functions/nancumprod.hpp" +#include "NumCpp/Functions/nancumsum.hpp" +#include "NumCpp/Functions/nanmax.hpp" +#include "NumCpp/Functions/nanmean.hpp" +#include "NumCpp/Functions/nanmedian.hpp" +#include "NumCpp/Functions/nanmin.hpp" +#include "NumCpp/Functions/nanpercentile.hpp" +#include "NumCpp/Functions/nanprod.hpp" +#include "NumCpp/Functions/nans.hpp" +#include "NumCpp/Functions/nans_like.hpp" +#include "NumCpp/Functions/nanstdev.hpp" +#include "NumCpp/Functions/nansum.hpp" +#include "NumCpp/Functions/nanvar.hpp" +#include "NumCpp/Functions/nbytes.hpp" +#include "NumCpp/Functions/negative.hpp" +#include "NumCpp/Functions/newbyteorder.hpp" +#include "NumCpp/Functions/none.hpp" +#include "NumCpp/Functions/nonzero.hpp" +#include "NumCpp/Functions/norm.hpp" +#include "NumCpp/Functions/not_equal.hpp" +#include "NumCpp/Functions/nth_root.hpp" +#include "NumCpp/Functions/ones.hpp" +#include "NumCpp/Functions/ones_like.hpp" +#include "NumCpp/Functions/outer.hpp" +#include "NumCpp/Functions/packbits.hpp" +#include "NumCpp/Functions/pad.hpp" +#include "NumCpp/Functions/partition.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/Functions/place.hpp" +#include "NumCpp/Functions/polar.hpp" +#include "NumCpp/Functions/power.hpp" +#include "NumCpp/Functions/powerf.hpp" +#include "NumCpp/Functions/print.hpp" +#include "NumCpp/Functions/prod.hpp" +#include "NumCpp/Functions/proj.hpp" +#include "NumCpp/Functions/ptp.hpp" +#include "NumCpp/Functions/put.hpp" +#include "NumCpp/Functions/putmask.hpp" +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/Functions/radians.hpp" +#include "NumCpp/Functions/ravel.hpp" +#include "NumCpp/Functions/real.hpp" +#include "NumCpp/Functions/reciprocal.hpp" +#include "NumCpp/Functions/remainder.hpp" +#include "NumCpp/Functions/repeat.hpp" +#include "NumCpp/Functions/replace.hpp" +#include "NumCpp/Functions/reshape.hpp" +#include "NumCpp/Functions/resizeFast.hpp" +#include "NumCpp/Functions/resizeSlow.hpp" +#include "NumCpp/Functions/right_shift.hpp" +#include "NumCpp/Functions/rint.hpp" +#include "NumCpp/Functions/rms.hpp" +#include "NumCpp/Functions/roll.hpp" +#include "NumCpp/Functions/rot90.hpp" +#include "NumCpp/Functions/round.hpp" +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/Functions/select.hpp" +#include "NumCpp/Functions/setdiff1d.hpp" +#include "NumCpp/Functions/shape.hpp" +#include "NumCpp/Functions/sign.hpp" +#include "NumCpp/Functions/signbit.hpp" +#include "NumCpp/Functions/sin.hpp" +#include "NumCpp/Functions/sinc.hpp" +#include "NumCpp/Functions/sinh.hpp" +#include "NumCpp/Functions/size.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/Functions/split.hpp" +#include "NumCpp/Functions/sqrt.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/Functions/stack.hpp" +#include "NumCpp/Functions/stdev.hpp" +#include "NumCpp/Functions/subtract.hpp" +#include "NumCpp/Functions/sum.hpp" +#include "NumCpp/Functions/swap.hpp" +#include "NumCpp/Functions/swapCols.hpp" +#include "NumCpp/Functions/swapRows.hpp" +#include "NumCpp/Functions/swapaxes.hpp" +#include "NumCpp/Functions/take.hpp" +#include "NumCpp/Functions/tan.hpp" +#include "NumCpp/Functions/tanh.hpp" +#include "NumCpp/Functions/tile.hpp" +#include "NumCpp/Functions/toStlVector.hpp" +#include "NumCpp/Functions/tofile.hpp" +#include "NumCpp/Functions/trace.hpp" +#include "NumCpp/Functions/transpose.hpp" +#include "NumCpp/Functions/trapz.hpp" +#include "NumCpp/Functions/tri.hpp" +#include "NumCpp/Functions/trim_zeros.hpp" +#include "NumCpp/Functions/trunc.hpp" +#include "NumCpp/Functions/union1d.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/Functions/unpackbits.hpp" +#include "NumCpp/Functions/unwrap.hpp" +#include "NumCpp/Functions/vander.hpp" +#include "NumCpp/Functions/var.hpp" +#include "NumCpp/Functions/vsplit.hpp" +#include "NumCpp/Functions/vstack.hpp" +#include "NumCpp/Functions/where.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Functions/zeros_like.hpp" diff --git a/runexamples/cpp/include/NumCpp/Functions/abs.hpp b/runexamples/cpp/include/NumCpp/Functions/abs.hpp new file mode 100644 index 0000000..fab0a8c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/abs.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the absolute value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.absolute.html + /// + /// @param inValue + /// @return value + /// + template + auto abs(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::abs(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the absolute value element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.absolute.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto abs(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return nc::abs(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/add.hpp b/runexamples/cpp/include/NumCpp/Functions/add.hpp new file mode 100644 index 0000000..fcd742c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/add.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray add(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray add(const NdArray& inArray, dtype value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray add(dtype value, const NdArray& inArray) + { + return value + inArray; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> add(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> add(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 + inArray2; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> add(const NdArray& inArray, const std::complex& value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> add(const std::complex& value, const NdArray& inArray) + { + return value + inArray; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> add(const NdArray>& inArray, dtype value) + { + return inArray + value; + } + + //============================================================================ + // Method Description: + /// Add arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.add.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> add(dtype value, const NdArray>& inArray) + { + return value + inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/alen.hpp b/runexamples/cpp/include/NumCpp/Functions/alen.hpp new file mode 100644 index 0000000..4cc8c69 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/alen.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the length of the first dimension of the input array. + /// + /// @param inArray + /// @return length uint16 + /// + template + uint32 alen(const NdArray& inArray) noexcept + { + return inArray.shape().rows; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/all.hpp b/runexamples/cpp/include/NumCpp/Functions/all.hpp new file mode 100644 index 0000000..6245d32 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/all.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether all array elements along a given axis evaluate to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.all.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray all(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.all(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/allclose.hpp b/runexamples/cpp/include/NumCpp/Functions/allclose.hpp new file mode 100644 index 0000000..0bb3409 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/allclose.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/abs.hpp" +#include "NumCpp/Functions/all.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns True if two arrays are element-wise equal within a tolerance. + /// inTolerance must be a positive number + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.allclose.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inTolerance: (Optional, default 1e-5) + /// @return bool + /// + template + bool allclose(const NdArray& inArray1, const NdArray& inArray2, double inTolerance = 1e-5) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array dimensions are not consistant."); + } + + for (uint32 i = 0; i < inArray1.size(); ++i) + { + if (std::abs(inArray1[i] - inArray2[i]) > inTolerance) + { + return false; + } + } + + return true; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/amax.hpp b/runexamples/cpp/include/NumCpp/Functions/amax.hpp new file mode 100644 index 0000000..b4d9dc7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/amax.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.amax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return max value + /// + template + NdArray amax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.max(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/amin.hpp b/runexamples/cpp/include/NumCpp/Functions/amin.hpp new file mode 100644 index 0000000..4b0980e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/amin.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or minimum along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.amin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return min value + /// + template + NdArray amin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.min(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/angle.hpp b/runexamples/cpp/include/NumCpp/Functions/angle.hpp new file mode 100644 index 0000000..f42d3cb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/angle.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the angle of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.angle.html + /// + /// @param inValue + /// @return value + /// + template + auto angle(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::arg(inValue); + } + + //============================================================================ + // Method Description: + /// Return the angle of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.angle.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto angle(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return angle(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/any.hpp b/runexamples/cpp/include/NumCpp/Functions/any.hpp new file mode 100644 index 0000000..699b9c5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/any.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether any array element along a given axis evaluates to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.any.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray any(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.any(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/append.hpp b/runexamples/cpp/include/NumCpp/Functions/append.hpp new file mode 100644 index 0000000..5b28fb2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/append.hpp @@ -0,0 +1,113 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Append values to the end of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.append.html + /// + /// @param inArray + /// @param inAppendValues + /// @param inAxis (Optional, default NONE): The axis along which values are appended. + /// If axis is not given, both inArray and inAppendValues + /// are flattened before use. + /// @return NdArray + /// + template + NdArray append(const NdArray& inArray, const NdArray& inAppendValues, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray(1, inArray.size() + inAppendValues.size()); + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), returnArray.begin()); + stl_algorithms::copy(inAppendValues.cbegin(), + inAppendValues.cend(), + returnArray.begin() + inArray.size()); + + return returnArray; + } + case Axis::ROW: + { + const Shape inShape = inArray.shape(); + const Shape appendShape = inAppendValues.shape(); + if (inShape.cols != appendShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR( + "all the input array dimensions except for the concatenation axis must match exactly"); + } + + NdArray returnArray(inShape.rows + appendShape.rows, inShape.cols); + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), returnArray.begin()); + stl_algorithms::copy(inAppendValues.cbegin(), + inAppendValues.cend(), + returnArray.begin() + inArray.size()); + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + const Shape appendShape = inAppendValues.shape(); + if (inShape.rows != appendShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR( + "all the input array dimensions except for the concatenation axis must match exactly"); + } + + NdArray returnArray(inShape.rows, inShape.cols + appendShape.cols); + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + stl_algorithms::copy(inArray.cbegin(row), inArray.cend(row), returnArray.begin(row)); + stl_algorithms::copy(inAppendValues.cbegin(row), + inAppendValues.cend(row), + returnArray.begin(row) + inShape.cols); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/applyFunction.hpp b/runexamples/cpp/include/NumCpp/Functions/applyFunction.hpp new file mode 100644 index 0000000..0bf16c4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/applyFunction.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Apply the input function element wise to the input + /// array in place. + /// + /// @param inArray + /// @param inFunc + /// @return NdArray + /// + template + void applyFunction(NdArray& inArray, const std::function& inFunc) + { + stl_algorithms::transform(inArray.begin(), inArray.end(), inArray.begin(), inFunc); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/applyPoly1d.hpp b/runexamples/cpp/include/NumCpp/Functions/applyPoly1d.hpp new file mode 100644 index 0000000..962116e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/applyPoly1d.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/applyFunction.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Polynomial/Poly1d.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Apply polynomial elemnt wise to the input values. + /// + /// @param inArray + /// @param inPoly + /// @return NdArray + /// + template + void applyPoly1d(NdArray& inArray, const polynomial::Poly1d& inPoly) + { + applyFunction(inArray, inPoly); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arange.hpp b/runexamples/cpp/include/NumCpp/Functions/arange.hpp new file mode 100644 index 0000000..fea0207 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arange.hpp @@ -0,0 +1,148 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inStart + /// @param inStop + /// @param inStep: (Optional, defaults to 1) + /// @return NdArray + /// + template + NdArray arange(dtype inStart, dtype inStop, dtype inStep = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inStep > 0 && inStop < inStart) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must be larger than the start value for positive step."); + } + + if (inStep < 0 && inStop > inStart) + { + THROW_INVALID_ARGUMENT_ERROR("start value must be larger than the stop value for negative step."); + } + + std::vector values; + + dtype theValue = inStart; + auto counter = dtype{ 1 }; + + if (inStep > 0) + { + while (theValue < inStop) + { + values.push_back(theValue); + theValue = inStart + inStep * counter++; + } + } + else + { + while (theValue > inStop) + { + values.push_back(theValue); + theValue = inStart + inStep * counter++; + } + } + + return NdArray(values); + } + + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inStop: start is 0 and step is 1 + /// @return NdArray + /// + template + NdArray arange(dtype inStop) + { + if (inStop <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must ge greater than 0."); + } + + return arange(0, inStop, 1); + } + + //============================================================================ + // Method Description: + /// Return evenly spaced values within a given interval. + /// + /// Values are generated within the half - open interval[start, stop) + /// (in other words, the interval including start but excluding stop). + /// For integer arguments the function is equivalent to the Python built - in + /// range function, but returns an ndarray rather than a list. + /// + /// When using a non - integer step, such as 0.1, the results will often + /// not be consistent.It is better to use linspace for these cases. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arange.html + /// + /// @param inSlice + /// @return NdArray + /// + template + NdArray arange(const Slice& inSlice) + { + return arange(inSlice.start, inSlice.stop, inSlice.step); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arccos.hpp b/runexamples/cpp/include/NumCpp/Functions/arccos.hpp new file mode 100644 index 0000000..9996370 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arccos.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse cosine + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccos.html + /// + /// @param inValue + /// @return value + /// + template + auto arccos(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::acos(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse cosine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccos.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arccos(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arccos(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arccosh.hpp b/runexamples/cpp/include/NumCpp/Functions/arccosh.hpp new file mode 100644 index 0000000..53b20e6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arccosh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic cosine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccosh.html + /// + /// @param inValue + /// @return value + /// + template + auto arccosh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::acosh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic cosine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arccosh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arccosh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arccosh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arcsin.hpp b/runexamples/cpp/include/NumCpp/Functions/arcsin.hpp new file mode 100644 index 0000000..2e39f7e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arcsin.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsin.html + /// + /// @param inValue + /// @return value + /// + template + auto arcsin(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::asin(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsin.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arcsin(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arcsin(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arcsinh.hpp b/runexamples/cpp/include/NumCpp/Functions/arcsinh.hpp new file mode 100644 index 0000000..1763ba7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arcsinh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsinh.html + /// + /// @param inValue + /// @return value + /// + template + auto arcsinh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::asinh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arcsinh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arcsinh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arcsinh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arctan.hpp b/runexamples/cpp/include/NumCpp/Functions/arctan.hpp new file mode 100644 index 0000000..5f61bb8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arctan.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan.html + /// + /// @param inValue + /// @return value + /// + template + auto arctan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::atan(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arctan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arctan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arctan2.hpp b/runexamples/cpp/include/NumCpp/Functions/arctan2.hpp new file mode 100644 index 0000000..0e2ebf0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arctan2.hpp @@ -0,0 +1,86 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan2.html + /// + /// @param inY + /// @param inX + /// @return value + /// + template + auto arctan2(dtype inY, dtype inX) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::atan2(inY, inX); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctan2.html + /// + /// @param inY + /// @param inX + /// @return NdArray + /// + template + auto arctan2(const NdArray& inY, const NdArray& inX) + { + if (inX.shape() != inY.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inY.shape()); + stl_algorithms::transform( + inY.cbegin(), + inY.cend(), + inX.cbegin(), + returnArray.begin(), + [](dtype y, dtype x) noexcept -> auto{ return arctan2(y, x); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/arctanh.hpp b/runexamples/cpp/include/NumCpp/Functions/arctanh.hpp new file mode 100644 index 0000000..f89a48c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/arctanh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctanh.html + /// + /// @param inValue + /// @return value + /// + template + auto arctanh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::atanh(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric inverse hyperbolic tangent, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.arctanh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto arctanh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return arctanh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/argmax.hpp b/runexamples/cpp/include/NumCpp/Functions/argmax.hpp new file mode 100644 index 0000000..a7179de --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/argmax.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the maximum values along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argmax(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/argmin.hpp b/runexamples/cpp/include/NumCpp/Functions/argmin.hpp new file mode 100644 index 0000000..adb4984 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/argmin.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the minimum values along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argmin(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/argsort.hpp b/runexamples/cpp/include/NumCpp/Functions/argsort.hpp new file mode 100644 index 0000000..667febb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/argsort.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices that would sort an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argsort.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray argsort(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.argsort(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/argwhere.hpp b/runexamples/cpp/include/NumCpp/Functions/argwhere.hpp new file mode 100644 index 0000000..2e4d090 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/argwhere.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the indices of array elements that are non-zero, grouped by element. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.argwhere.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray argwhere(const NdArray& inArray) + { + return inArray.flatnonzero(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/around.hpp b/runexamples/cpp/include/NumCpp/Functions/around.hpp new file mode 100644 index 0000000..796b697 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/around.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.around.html + /// + /// @param inValue + /// @param inNumDecimals: (Optional, default = 0) + /// @return value + /// + template + dtype around(dtype inValue, uint8 inNumDecimals = 0) + { + NdArray value = { inValue }; + return value.round(inNumDecimals).item(); + } + + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.around.html + /// + /// @param inArray + /// @param inNumDecimals: (Optional, default = 0) + /// @return NdArray + /// + template + NdArray around(const NdArray& inArray, uint8 inNumDecimals = 0) + { + return inArray.round(inNumDecimals); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/array_equal.hpp b/runexamples/cpp/include/NumCpp/Functions/array_equal.hpp new file mode 100644 index 0000000..86af313 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/array_equal.hpp @@ -0,0 +1,56 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/array_equiv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// True if two arrays have the same shape and elements, False otherwise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.array_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return bool + /// + template + bool array_equal(const NdArray& inArray1, const NdArray& inArray2) noexcept + { + if (inArray1.shape() != inArray2.shape()) + { + return false; + } + + return array_equiv(inArray1, inArray2); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/array_equiv.hpp b/runexamples/cpp/include/NumCpp/Functions/array_equiv.hpp new file mode 100644 index 0000000..b5acfdd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/array_equiv.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns True if input arrays are shape consistent and all elements equal. + /// + /// Shape consistent means they are either the same shape, or one input array + /// can be broadcasted to create the same shape as the other one. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.array_equiv.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return bool + /// + template + bool array_equiv(const NdArray& inArray1, const NdArray& inArray2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inArray1.size() != inArray2.size()) + { + return false; + } + + if (DtypeInfo::isInteger()) + { + return stl_algorithms::equal(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin()); + } + + const auto comparitor = [](dtype value1, dtype value2) noexcept -> bool + { return utils::essentiallyEqual(value1, value2); }; + + return stl_algorithms::equal(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), comparitor); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/asarray.hpp b/runexamples/cpp/include/NumCpp/Functions/asarray.hpp new file mode 100644 index 0000000..bc3d379 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/asarray.hpp @@ -0,0 +1,320 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert the list initializer to an array. + /// eg: NdArray myArray = NC::asarray({1,2,3}); + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::initializer_list inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the list initializer to an array. + /// eg: NdArray myArray = NC::asarray({{1,2,3}, {4, 5, 6}}); + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template + NdArray asarray(std::initializer_list> inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the std::array to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::array& inArray, bool copy = true) + { + return NdArray(inArray, copy); + } + + //============================================================================ + // Method Description: + /// Convert the std::array to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template + NdArray asarray(std::array, Dim0Size>& inArray, bool copy = true) + { + return NdArray(inArray, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(std::vector& inVector, bool copy = true) + { + return NdArray(inVector, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @return NdArray + /// + template + NdArray asarray(const std::vector>& inVector) + { + return NdArray(inVector); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// @return NdArray + /// + template + NdArray asarray(std::vector>& inVector, bool copy = true) + { + return NdArray(inVector, copy); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inDeque + /// @return NdArray + /// + template, int> = 0> + NdArray asarray(const std::deque& inDeque) + { + return NdArray(inDeque); + } + + //============================================================================ + // Method Description: + /// Convert the vector to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inDeque + /// @return NdArray + /// + template + NdArray asarray(const std::deque>& inDeque) + { + return NdArray(inDeque); + } + + //============================================================================ + // Method Description: + /// Convert the set to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inSet + /// @return NdArray + /// + template + NdArray asarray(const std::set& inSet) + { + return NdArray(inSet); + } + + //============================================================================ + // Method Description: + /// Convert the list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param inList + /// @return NdArray + /// + template + NdArray asarray(const std::list& inList) + { + return NdArray(inList); + } + + //============================================================================ + // Method Description: + /// Convert the forward_list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param iterBegin + /// @param iterEnd + /// @return NdArray + /// + template + auto asarray(Iterator iterBegin, Iterator iterEnd) + { + return NdArray::value_type>(iterBegin, iterEnd); + } + + //============================================================================ + // Method Description: + /// Convert the forward_list to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param iterBegin + /// @param iterEnd + /// @return NdArray + /// + template + NdArray asarray(const dtype* iterBegin, const dtype* iterEnd) + { + return NdArray(iterBegin, iterEnd); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param size: the number of elements in the array + /// @return NdArray + /// + template + NdArray asarray(const dtype* ptr, uint32 size) + { + return NdArray(ptr, size); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// @return NdArray + /// + template + NdArray asarray(const dtype* ptr, uint32 numRows, uint32 numCols) + { + return NdArray(ptr, numRows, numCols); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param size: the number of elements in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// @return NdArray + /// + template::value, int> = 0> + NdArray asarray(dtype* ptr, uint32 size, BoolType takeOwnership) noexcept + { + return NdArray(ptr, size, takeOwnership); + } + + //============================================================================ + // Method Description: + /// Convert the c-style array to an array. Makes a copy of the data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.asarray.html + /// + /// @param ptr to array + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// @return NdArray + /// + template::value, int> = 0> + NdArray asarray(dtype* ptr, uint32 numRows, uint32 numCols, BoolType takeOwnership) noexcept + { + return NdArray(ptr, numRows, numCols, takeOwnership); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/astype.hpp b/runexamples/cpp/include/NumCpp/Functions/astype.hpp new file mode 100644 index 0000000..6a2f74b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/astype.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray astype(const NdArray inArray) + { + return inArray.template astype(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/average.hpp b/runexamples/cpp/include/NumCpp/Functions/average.hpp new file mode 100644 index 0000000..b177389 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/average.hpp @@ -0,0 +1,214 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + auto average(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return mean(inArray, inAxis); + } + + //============================================================================ + // Method Description: + /// Compute the weighted average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inWeights + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray average(const NdArray& inArray, const NdArray& inWeights, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + if (inWeights.shape() != inArray.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weight values are not consistant."); + } + + NdArray weightedArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inWeights.cbegin(), + weightedArray.begin(), + std::multiplies()); // NOLINT(modernize-use-transparent-functors) + + double sum = std::accumulate(weightedArray.begin(), weightedArray.end(), 0.); + NdArray returnArray = { sum /= inWeights.template astype().sum().item() }; + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray.shape(); + if (inWeights.size() != arrayShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weights value are not consistant."); + } + + double weightSum = inWeights.template astype().sum().item(); + NdArray returnArray(1, arrayShape.rows); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + NdArray weightedArray(1, arrayShape.cols); + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row), + inWeights.cbegin(), + weightedArray.begin(), + std::multiplies()); // NOLINT(modernize-use-transparent-functors) + + double sum = std::accumulate(weightedArray.begin(), weightedArray.end(), 0.); + returnArray(0, row) = sum / weightSum; + } + + return returnArray; + } + case Axis::ROW: + { + return average(inArray.transpose(), inWeights, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Compute the weighted average along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.average.html + /// + /// @param inArray + /// @param inWeights + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray> + average(const NdArray>& inArray, const NdArray& inWeights, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto multiplies = [](const std::complex& lhs, dtype rhs) -> std::complex + { return complex_cast(lhs) * static_cast(rhs); }; + + switch (inAxis) + { + case Axis::NONE: + { + if (inWeights.shape() != inArray.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weight values are not consistant."); + } + + NdArray> weightedArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inWeights.cbegin(), + weightedArray.begin(), + multiplies); + + std::complex sum = + std::accumulate(weightedArray.begin(), weightedArray.end(), std::complex(0.)); + NdArray> returnArray = { sum /= inWeights.template astype().sum().item() }; + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray.shape(); + if (inWeights.size() != arrayShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array and weights value are not consistant."); + } + + double weightSum = inWeights.template astype().sum().item(); + NdArray> returnArray(1, arrayShape.rows); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + NdArray> weightedArray(1, arrayShape.cols); + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row), + inWeights.cbegin(), + weightedArray.begin(), + multiplies); + + const std::complex sum = + std::accumulate(weightedArray.begin(), weightedArray.end(), std::complex(0.)); + returnArray(0, row) = sum / weightSum; + } + + return returnArray; + } + case Axis::ROW: + { + return average(inArray.transpose(), inWeights, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bartlett.hpp b/runexamples/cpp/include/NumCpp/Functions/bartlett.hpp new file mode 100644 index 0000000..a3e12df --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bartlett.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Bartlett window is very similar to a triangular window, except that the end + /// points are at zero. It is often used in signal processing for tapering a signal, + /// without generating too much ripple in the frequency domain. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.bartlett.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray bartlett(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto mMinus1Over2 = (mDouble - 1.) / 2.; + const auto mMinus1Over2Inv = 1. / mMinus1Over2; + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = mMinus1Over2Inv * (mMinus1Over2 - std::abs(n - mMinus1Over2)); + } + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/binaryRepr.hpp b/runexamples/cpp/include/NumCpp/Functions/binaryRepr.hpp new file mode 100644 index 0000000..b4f47f0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/binaryRepr.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the binary representation of the input number as a string. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.binary_repr.html + /// + /// @param inValue + /// @return std::string + /// + template + std::string binaryRepr(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::bitset::bits()>(inValue).to_string(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bincount.hpp b/runexamples/cpp/include/NumCpp/Functions/bincount.hpp new file mode 100644 index 0000000..15c0c50 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bincount.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Count number of occurrences of each value in array of non-negative ints. + /// Negative values will be counted in the zero bin. + /// + /// The number of bins(of size 1) is one larger than the largest value in x. + /// If minlength is specified, there will be at least this number of bins in + /// the output array(though it will be longer if necessary, depending on the + /// contents of x).Each bin gives the number of occurrences of its index value + /// in x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bincount.html + /// + /// @param inArray + /// @param inMinLength + /// @return NdArray + /// + template + NdArray bincount(const NdArray& inArray, uint16 inMinLength = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + dtype maxValue = inArray.max().item(); + if (maxValue < 0) + { + // no positive values so just return an empty array + return NdArray(0); + } + + if (maxValue + 1 > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR( + "array values too large, will result in gigantic array that will take up alot of memory..."); + } + + const uint16 outArraySize = std::max(static_cast(maxValue + 1), inMinLength); + NdArray clippedArray = inArray.clip(0, maxValue); + + NdArray outArray(1, outArraySize); + outArray.zeros(); + std::for_each(clippedArray.cbegin(), + clippedArray.cend(), + [&outArray](dtype value) noexcept -> void { ++outArray[value]; }); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Count number of occurrences of each value in array of non-negative ints. + /// Negative values will be counted in the zero bin. + /// + /// The number of bins(of size 1) is one larger than the largest value in x. + /// If minlength is specified, there will be at least this number of bins in + /// the output array(though it will be longer if necessary, depending on the + /// contents of x).Each bin gives the number of occurrences of its index value + /// in x.If weights is specified the input array is weighted by it, i.e. if a + /// value n is found at position i, out[n] += weight[i] instead of out[n] += 1. + /// Weights array shall be of the same shape as inArray. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bincount.html + /// + /// @param inArray + /// @param inWeights + /// @param inMinLength + /// @return NdArray + /// + template + NdArray bincount(const NdArray& inArray, const NdArray& inWeights, uint16 inMinLength = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inArray.shape() != inWeights.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("weights array must be the same shape as the input array."); + } + + dtype maxValue = inArray.max().item(); + if (maxValue < 0) + { + // no positive values so just return an empty array + return NdArray(0); + } + + if (maxValue + 1 > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR( + "array values too large, will result in gigantic array that will take up alot of memory..."); + } + + const uint16 outArraySize = std::max(static_cast(maxValue + 1), inMinLength); + NdArray clippedArray = inArray.clip(0, maxValue); + + NdArray outArray(1, outArraySize); + outArray.zeros(); + uint32 counter = 0; + std::for_each(clippedArray.cbegin(), + clippedArray.cend(), + [&outArray, &inWeights, &counter](dtype value) noexcept -> void + { outArray[value] += inWeights[counter++]; }); + + return outArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bit_count.hpp b/runexamples/cpp/include/NumCpp/Functions/bit_count.hpp new file mode 100644 index 0000000..4ec2560 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bit_count.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Computes the number of 1-bits in an integer + /// + /// @param inValue + /// @return value + /// + template + constexpr int bit_count(dtype inValue) noexcept + { + STATIC_ASSERT_UNSIGNED_INTEGER(dtype); + + int count = 0; + for (int bit = 0; bit < DtypeInfo::bits(); ++bit) + { + count += static_cast((inValue & (dtype{ 1 } << bit)) >> bit); + } + + return count; + } + + //============================================================================ + // Method Description: + /// Computes the number of 1-bits in an integer + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray bit_count(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> int { return bit_count(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bitwise_and.hpp b/runexamples/cpp/include/NumCpp/Functions/bitwise_and.hpp new file mode 100644 index 0000000..b14ed54 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bitwise_and.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise AND of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_and.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_and(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 & inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bitwise_not.hpp b/runexamples/cpp/include/NumCpp/Functions/bitwise_not.hpp new file mode 100644 index 0000000..d2513cf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bitwise_not.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise NOT the input array element-wise. + /// + /// inArray + /// @return NdArray + /// + template + NdArray bitwise_not(const NdArray& inArray) + { + return ~inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bitwise_or.hpp b/runexamples/cpp/include/NumCpp/Functions/bitwise_or.hpp new file mode 100644 index 0000000..ec5cf55 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bitwise_or.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise OR of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_or.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_or(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 | inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/bitwise_xor.hpp b/runexamples/cpp/include/NumCpp/Functions/bitwise_xor.hpp new file mode 100644 index 0000000..14381c0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/bitwise_xor.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the bit-wise XOR of two arrays element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.bitwise_xor.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray bitwise_xor(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 ^ inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/blackman.hpp b/runexamples/cpp/include/NumCpp/Functions/blackman.hpp new file mode 100644 index 0000000..57c96f5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/blackman.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Blackman window is a taper formed by using the first three terms of a summation of + /// cosines. It was designed to have close to the minimal leakage possible. It is close to + /// optimal, only slightly worse than a Kaiser window. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.blackman.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray blackman(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble, m, true)) + { + const auto nOverM = n / mDouble; + result[i++] = + 0.42 - 0.5 * std::cos(2. * constants::pi * nOverM) + 0.08 * std::cos(4. * constants::pi * nOverM); + } + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/byteswap.hpp b/runexamples/cpp/include/NumCpp/Functions/byteswap.hpp new file mode 100644 index 0000000..4226637 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/byteswap.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the bytes of the array elements + /// swapped. + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray byteswap(const NdArray& inArray) + { + NdArray returnArray(inArray); + returnArray.byteswap(); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cbrt.hpp b/runexamples/cpp/include/NumCpp/Functions/cbrt.hpp new file mode 100644 index 0000000..a1b4ab0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cbrt.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cube-root of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cbrt.html + /// + /// @param inValue + /// @return value + /// + template + double cbrt(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::cbrt(static_cast(inValue)); + } + + //============================================================================ + // Method Description: + /// Return the cube-root of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cbrt.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray cbrt(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> double { return cbrt(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/ceil.hpp b/runexamples/cpp/include/NumCpp/Functions/ceil.hpp new file mode 100644 index 0000000..9668bbb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ceil.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the ceiling of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ceil.html + /// + /// @param inValue + /// @return value + /// + template + dtype ceil(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::ceil(inValue); + } + + //============================================================================ + // Method Description: + /// Return the ceiling of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ceil.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray ceil(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return ceil(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/centerOfMass.hpp b/runexamples/cpp/include/NumCpp/Functions/centerOfMass.hpp new file mode 100644 index 0000000..e28baab --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/centerOfMass.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the center of mass of the array values along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE which is a 2d center of mass) + /// @return NdArray: if axis is NONE then a 1x2 array of the centroid row/col is returned. + /// + template + NdArray centerOfMass(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape shape = inArray.shape(); + + switch (inAxis) + { + case Axis::NONE: + { + double inten = 0.; + double rowCenter = 0.; + double colCenter = 0.; + + for (uint32 row = 0; row < shape.rows; ++row) + { + for (uint32 col = 0; col < shape.cols; ++col) + { + const auto pixelValue = static_cast(inArray(row, col)); + + inten += pixelValue; + rowCenter += pixelValue * static_cast(row); + colCenter += pixelValue * static_cast(col); + } + } + + rowCenter /= inten; + colCenter /= inten; + + return { rowCenter, colCenter }; + } + case Axis::ROW: + { + NdArray returnArray(1, shape.cols); + returnArray.zeros(); + + const NdArray inten = inArray.template astype().sum(inAxis); + + for (uint32 colIdx = 0; colIdx < shape.cols; ++colIdx) + { + for (uint32 rowIdx = 0; rowIdx < shape.rows; ++rowIdx) + { + returnArray(0, colIdx) += + static_cast(inArray(rowIdx, colIdx)) * static_cast(rowIdx); + } + + returnArray(0, colIdx) /= inten[colIdx]; + } + + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape.rows); + returnArray.zeros(); + + const NdArray inten = inArray.template astype().sum(inAxis); + + for (uint32 rowIdx = 0; rowIdx < shape.rows; ++rowIdx) + { + for (uint32 colIdx = 0; colIdx < shape.cols; ++colIdx) + { + returnArray(0, rowIdx) += + static_cast(inArray(rowIdx, colIdx)) * static_cast(colIdx); + } + + returnArray(0, rowIdx) /= inten[rowIdx]; + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/clip.hpp b/runexamples/cpp/include/NumCpp/Functions/clip.hpp new file mode 100644 index 0000000..1b93b3f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/clip.hpp @@ -0,0 +1,88 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Clip (limit) the value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.clip.html + /// + /// @param inValue + /// @param inMinValue + /// @param inMaxValue + /// @return NdArray + /// + template + dtype clip(dtype inValue, dtype inMinValue, dtype inMaxValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + +#ifdef __cpp_lib_clamp + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + return std::clamp(inValue, inMinValue, inMaxValue, comparitor); +#else + if (inValue < inMinValue) + { + return inMinValue; + } + else if (inValue > inMaxValue) + { + return inMaxValue; + } + + return inValue; +#endif + } + + //============================================================================ + // Method Description: + /// Clip (limit) the values in an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.clip.html + /// + /// @param inArray + /// @param inMinValue + /// @param inMaxValue + /// @return NdArray + /// + template + NdArray clip(const NdArray& inArray, dtype inMinValue, dtype inMaxValue) + { + return inArray.clip(inMinValue, inMaxValue); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/column_stack.hpp b/runexamples/cpp/include/NumCpp/Functions/column_stack.hpp new file mode 100644 index 0000000..8dbb4cb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/column_stack.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Stack 1-D arrays as columns into a 2-D array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.column_stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @return NdArray + /// + template + NdArray column_stack(const std::initializer_list>& inArrayList) + { + // first loop through to calculate the final size of the array + Shape finalShape; + for (auto& ndarray : inArrayList) + { + if (finalShape.isnull()) + { + finalShape = ndarray.shape(); + } + else if (ndarray.shape().rows != finalShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays must have the same number of rows."); + } + else + { + finalShape.cols += ndarray.shape().cols; + } + } + + // now that we know the final size, contruct the output array + NdArray returnArray(finalShape); + uint32 colStart = 0; + for (auto& ndarray : inArrayList) + { + const Shape theShape = ndarray.shape(); + for (uint32 row = 0; row < theShape.rows; ++row) + { + for (uint32 col = 0; col < theShape.cols; ++col) + { + returnArray(row, colStart + col) = ndarray(row, col); + } + } + colStart += theShape.cols; + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/complex.hpp b/runexamples/cpp/include/NumCpp/Functions/complex.hpp new file mode 100644 index 0000000..f826dcb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/complex.hpp @@ -0,0 +1,116 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @return value + /// + template + auto complex(dtype inReal) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::complex(inReal); + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @param inImag: the imaginary component of the complex number + /// @return value + /// + template + auto complex(dtype inReal, dtype inImag) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::complex(inReal, inImag); + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @return NdArray + /// + template + auto complex(const NdArray& inReal) + { + NdArray returnArray(inReal.shape()); + stl_algorithms::transform( + inReal.cbegin(), + inReal.cend(), + returnArray.begin(), + [](dtype real) -> auto{ return nc::complex(real); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns a std::complex from the input real and imag components + /// + /// @param inReal: the real component of the complex number + /// @param inImag: the imaginary component of the complex number + /// @return NdArray + /// + template + auto complex(const NdArray& inReal, const NdArray& inImag) + { + if (inReal.shape() != inImag.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("Input real array must be the same shape as input imag array"); + } + + NdArray returnArray(inReal.shape()); + stl_algorithms::transform( + inReal.cbegin(), + inReal.cend(), + inImag.cbegin(), + returnArray.begin(), + [](dtype real, dtype imag) -> auto{ return nc::complex(real, imag); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/concatenate.hpp b/runexamples/cpp/include/NumCpp/Functions/concatenate.hpp new file mode 100644 index 0000000..9174194 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/concatenate.hpp @@ -0,0 +1,88 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/row_stack.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Join a sequence of arrays along an existing axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.concatenate.html + /// + /// @param inArrayList + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray concatenate(const std::initializer_list>& inArrayList, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + uint32 finalSize = 0; + for (auto& ndarray : inArrayList) + { + finalSize += ndarray.size(); + } + + NdArray returnArray(1, finalSize); + uint32 offset = 0; + for (auto& ndarray : inArrayList) + { + stl_algorithms::copy(ndarray.cbegin(), ndarray.cend(), returnArray.begin() + offset); + offset += ndarray.size(); + } + + return returnArray; + } + case Axis::ROW: + { + return row_stack(inArrayList); + } + case Axis::COL: + { + return column_stack(inArrayList); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/conj.hpp b/runexamples/cpp/include/NumCpp/Functions/conj.hpp new file mode 100644 index 0000000..f13ed7f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/conj.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the complex conjugate of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.conj.html + /// + /// @param inValue + /// @return value + /// + template + auto conj(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::conj(inValue); + } + + //============================================================================ + // Method Description: + /// Return the complex conjugate of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.conj.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto conj(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::conj(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/contains.hpp b/runexamples/cpp/include/NumCpp/Functions/contains.hpp new file mode 100644 index 0000000..bbb7c0c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/contains.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// returns whether or not a value is included the array + /// + /// @param inArray + /// @param inValue + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray contains(const NdArray& inArray, dtype inValue, Axis inAxis = Axis::NONE) + { + return inArray.contains(inValue, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/copy.hpp b/runexamples/cpp/include/NumCpp/Functions/copy.hpp new file mode 100644 index 0000000..da6e6b2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/copy.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return an array copy of the given object. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copy.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray copy(const NdArray& inArray) + { + return NdArray(inArray); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/copySign.hpp b/runexamples/cpp/include/NumCpp/Functions/copySign.hpp new file mode 100644 index 0000000..883428d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/copySign.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change the sign of x1 to that of x2, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copysign.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray copySign(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [](dtype inValue1, dtype inValue2) -> dtype + { return inValue2 < dtype{ 0 } ? std::abs(inValue1) * -1 : std::abs(inValue1); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/copyto.hpp b/runexamples/cpp/include/NumCpp/Functions/copyto.hpp new file mode 100644 index 0000000..bf005f4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/copyto.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Copies values from one array to another + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.copyto.html + /// + /// @param inDestArray + /// @param inSrcArray + /// @return NdArray + /// + template + NdArray& copyto(NdArray& inDestArray, const NdArray& inSrcArray) + { + inDestArray = inSrcArray; + return inDestArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/corrcoef.hpp b/runexamples/cpp/include/NumCpp/Functions/corrcoef.hpp new file mode 100644 index 0000000..364a36d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/corrcoef.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Functions/empty_like.hpp" +#include "NumCpp/Functions/sqrt.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return Pearson product-moment correlation coefficients. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @return NdArray + /// + template + NdArray corrcoef(const NdArray& x) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto covariance = cov(x); + auto normalizedCovariance = empty_like(covariance); + for (decltype(covariance.numRows()) i = 0; i < covariance.numRows(); ++i) + { + for (decltype(covariance.numCols()) j = 0; j < covariance.numCols(); ++j) + { + normalizedCovariance(i, j) = covariance(i, j) / sqrt(covariance(i, i) * covariance(j, j)); + } + } + + return normalizedCovariance; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cos.hpp b/runexamples/cpp/include/NumCpp/Functions/cos.hpp new file mode 100644 index 0000000..f4d2e7d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cos.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Cosine + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cos.html + /// + /// @param inValue + /// @return value + /// + template + auto cos(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::cos(inValue); + } + + //============================================================================ + // Method Description: + /// Cosine element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cos.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto cos(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return cos(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cosh.hpp b/runexamples/cpp/include/NumCpp/Functions/cosh.hpp new file mode 100644 index 0000000..ec99e8b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cosh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Hyperbolic Cosine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cosh.html + /// + /// @param inValue + /// @return value + /// + template + auto cosh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::cosh(inValue); + } + + //============================================================================ + // Method Description: + /// Hyperbolic Cosine element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cosh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto cosh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return cosh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/count_nonzero.hpp b/runexamples/cpp/include/NumCpp/Functions/count_nonzero.hpp new file mode 100644 index 0000000..f00d3ca --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/count_nonzero.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Counts the number of non-zero values in the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.count_nonzero.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray count_nonzero(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + NdArray count = { inArray.size() - + static_cast( + stl_algorithms::count(inArray.cbegin(), inArray.cend(), dtype{ 0 })) }; + return count; + } + case Axis::COL: + { + Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(0, row) = + inShape.cols - + static_cast(stl_algorithms::count(inArray.cbegin(row), inArray.cend(row), dtype{ 0 })); + } + + return returnArray; + } + case Axis::ROW: + { + return count_nonzero(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cov.hpp b/runexamples/cpp/include/NumCpp/Functions/cov.hpp new file mode 100644 index 0000000..13c2606 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cov.hpp @@ -0,0 +1,93 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Estimate a covariance matrix. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.cov.html + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @param bias: Default normalization (false) is by (N - 1), where N is the number of observations + /// given (unbiased estimate). If bias is True, then normalization is by N. + /// @return NdArray + /// + template + NdArray cov(const NdArray& x, bool bias = false) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto varMeans = mean(x, Axis::COL); + const auto numVars = x.numRows(); + const auto numObs = x.numCols(); + const auto normilizationFactor = bias ? static_cast(numObs) : static_cast(numObs - 1); + using IndexType = typename std::remove_const::type; + + // upper triangle + auto covariance = NdArray(numVars); + for (IndexType i = 0; i < numVars; ++i) + { + const auto var1Mean = varMeans[i]; + + for (IndexType j = i; j < numVars; ++j) + { + const auto var2Mean = varMeans[j]; + + double sum = 0.; + for (IndexType iObs = 0; iObs < numObs; ++iObs) + { + sum += (x(i, iObs) - var1Mean) * (x(j, iObs) - var2Mean); + } + + covariance(i, j) = sum / normilizationFactor; + } + } + + // fill in the rest of the symmetric matrix + for (IndexType j = 0; j < numVars; ++j) + { + for (IndexType i = j + 1; i < numVars; ++i) + { + covariance(i, j) = covariance(j, i); + } + } + + return covariance; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cov_inv.hpp b/runexamples/cpp/include/NumCpp/Functions/cov_inv.hpp new file mode 100644 index 0000000..5478211 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cov_inv.hpp @@ -0,0 +1,55 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/cov.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Estimate an inverse covariance matrix, aka the concentration matrix + /// + /// @param x: A 1-D or 2-D array containing multiple variables and observations. + /// Each row of x represents a variable, and each column a single observation + /// of all those variables. + /// @param bias: Default normalization (false) is by (N - 1), where N is the number of observations + /// given (unbiased estimate). If bias is True, then normalization is by N. + /// @return NdArray + /// + template + NdArray cov_inv(const NdArray& x, bool bias = false) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return linalg::inv(cov(x, bias)); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cross.hpp b/runexamples/cpp/include/NumCpp/Functions/cross.hpp new file mode 100644 index 0000000..ab267e4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cross.hpp @@ -0,0 +1,171 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cross product of two (arrays of) vectors. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cross.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cross(const NdArray& inArray1, const NdArray& inArray2, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("the input array dimensions are not consistant."); + } + + switch (inAxis) + { + case Axis::NONE: + { + const uint32 arraySize = inArray1.size(); + if (arraySize != inArray2.size() || arraySize < 2 || arraySize > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + NdArray in1 = inArray1.flatten(); + NdArray in2 = inArray2.flatten(); + + switch (arraySize) + { + case 2: + { + NdArray returnArray = { in1[0] * in2[1] - in1[1] * in2[0] }; + return returnArray; + } + case 3: + { + dtype i = in1[1] * in2[2] - in1[2] * in2[1]; + dtype j = -(in1[0] * in2[2] - in1[2] * in2[0]); + dtype k = in1[0] * in2[1] - in1[1] * in2[0]; + + NdArray returnArray = { i, j, k }; + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented array size."); + return {}; // get rid of compiler warning + } + } + } + case Axis::ROW: + { + const Shape arrayShape = inArray1.shape(); + if (arrayShape != inArray2.shape() || arrayShape.rows < 2 || arrayShape.rows > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + Shape returnArrayShape; + returnArrayShape.cols = arrayShape.cols; + if (arrayShape.rows == 2) + { + returnArrayShape.rows = 1; + } + else + { + returnArrayShape.rows = 3; + } + + NdArray returnArray(returnArrayShape); + for (uint32 col = 0; col < arrayShape.cols; ++col) + { + const auto theCol = static_cast(col); + NdArray vec1 = inArray1(inArray1.rSlice(), { theCol, theCol + 1 }); + NdArray vec2 = inArray2(inArray2.rSlice(), { theCol, theCol + 1 }); + NdArray vecCross = cross(vec1, vec2, Axis::NONE); + + returnArray.put({ 0, static_cast(returnArrayShape.rows) }, { theCol, theCol + 1 }, vecCross); + } + + return returnArray; + } + case Axis::COL: + { + const Shape arrayShape = inArray1.shape(); + if (arrayShape != inArray2.shape() || arrayShape.cols < 2 || arrayShape.cols > 3) + { + THROW_INVALID_ARGUMENT_ERROR( + "incompatible dimensions for cross product (dimension must be 2 or 3)"); + } + + Shape returnArrayShape; + returnArrayShape.rows = arrayShape.rows; + if (arrayShape.cols == 2) + { + returnArrayShape.cols = 1; + } + else + { + returnArrayShape.cols = 3; + } + + NdArray returnArray(returnArrayShape); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + const auto theRow = static_cast(row); + NdArray vec1 = inArray1({ theRow, theRow + 1 }, inArray1.cSlice()); + NdArray vec2 = inArray2({ theRow, theRow + 1 }, inArray2.cSlice()); + NdArray vecCross = cross(vec1, vec2, Axis::NONE); + + returnArray.put({ theRow, theRow + 1 }, { 0, static_cast(returnArrayShape.cols) }, vecCross); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cube.hpp b/runexamples/cpp/include/NumCpp/Functions/cube.hpp new file mode 100644 index 0000000..e0f9335 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cube.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/cube.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Cubes the input + /// + /// @param inValue + /// @return cubed value + /// + template + constexpr dtype cube(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return utils::cube(inValue); + } + + //============================================================================ + // Method Description: + /// Cubes the elements of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray cube(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return cube(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cumprod.hpp b/runexamples/cpp/include/NumCpp/Functions/cumprod.hpp new file mode 100644 index 0000000..e230cf3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cumprod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative product of elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cumprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cumprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.cumprod(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/cumsum.hpp b/runexamples/cpp/include/NumCpp/Functions/cumsum.hpp new file mode 100644 index 0000000..dedf9c8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/cumsum.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.cumsum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray cumsum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.cumsum(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/deg2rad.hpp b/runexamples/cpp/include/NumCpp/Functions/deg2rad.hpp new file mode 100644 index 0000000..a73435e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/deg2rad.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.deg2rad.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto deg2rad(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue * constants::pi / 180.; + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.deg2rad.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto deg2rad(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return deg2rad(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/degrees.hpp b/runexamples/cpp/include/NumCpp/Functions/degrees.hpp new file mode 100644 index 0000000..14a6462 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/degrees.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/rad2deg.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.degrees.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto degrees(dtype inValue) noexcept + { + return rad2deg(inValue); + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.degrees.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto degrees(const NdArray& inArray) + { + return rad2deg(inArray); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/deleteIndices.hpp b/runexamples/cpp/include/NumCpp/Functions/deleteIndices.hpp new file mode 100644 index 0000000..ce9d087 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/deleteIndices.hpp @@ -0,0 +1,316 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteFlatIndices(const NdArray& inArray, Indices inIndices) + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + const auto arraySize = inArray.size(); + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arraySize](auto& value) + { + if (value < 0) + { + value += arraySize; + } + }); + } + + auto indices = unique(inIndices); + + std::vector values; + values.reserve(indices.size()); + for (int32 i = 0; i < static_cast(inArray.size()); ++i) + { + if (std::binary_search(indices.begin(), indices.end(), i)) + { + continue; + } + + values.push_back(inArray[i]); + } + + return NdArray(values); + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along the row axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteRowIndices(const NdArray& inArray, Indices inIndices) + { + const auto arrayRows = static_cast(inArray.numRows()); + if constexpr (type_traits::is_ndarray_signed_int_v) + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arrayRows](auto& value) + { + if (value < 0) + { + value += arrayRows; + } + }); + } + + auto indices = unique(inIndices); + + uint32 indicesSize = 0; + std::for_each(indices.begin(), + indices.end(), + [arrayRows, &indicesSize](const auto& value) + { + if constexpr (std::is_signed_v) + { + if (value >= 0 && value < arrayRows) + { + ++indicesSize; + } + } + else + { + if (value < arrayRows) + { + ++indicesSize; + } + } + }); + + const auto arrayCols = static_cast(inArray.numCols()); + NdArray returnArray(arrayRows - indicesSize, arrayCols); + + uint32 rowCounter = 0; + for (int32 row = 0; row < arrayRows; ++row) + { + if (std::binary_search(indices.begin(), indices.end(), row)) + { + continue; + } + + for (int32 col = 0; col < arrayCols; ++col) + { + returnArray(rowCounter, col) = inArray(row, col); + } + + ++rowCounter; + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along the col axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @return NdArray + /// + template = 0> + NdArray deleteColumnIndices(const NdArray& inArray, Indices inIndices) + { + const auto arrayCols = static_cast(inArray.numCols()); + if constexpr (type_traits::is_ndarray_signed_int_v) + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [arrayCols](auto& value) + { + if (value < 0) + { + value += arrayCols; + } + }); + } + + auto indices = unique(inIndices); + + uint32 indicesSize = 0; + std::for_each(indices.begin(), + indices.end(), + [arrayCols, &indicesSize](const auto& value) + { + if constexpr (std::is_signed_v) + { + if (value >= 0 && value < arrayCols) + { + ++indicesSize; + } + } + else + { + if (value < arrayCols) + { + ++indicesSize; + } + } + }); + + const auto arrayRows = static_cast(inArray.numRows()); + NdArray returnArray(arrayRows, arrayCols - indicesSize); + + uint32 colCounter = 0; + for (int32 col = 0; col < arrayCols; ++col) + { + if (std::binary_search(indices.begin(), indices.end(), col)) + { + continue; + } + + for (int32 row = 0; row < arrayRows; ++row) + { + returnArray(row, colCounter) = inArray(row, col); + } + + ++colCounter; + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndices + /// @param inAxis (Optional, default NONE) if NONE the indices will be applied to the flattened array + /// @return NdArray + /// + template = 0> + NdArray deleteIndices(const NdArray& inArray, const Indices& inIndices, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + return detail::deleteFlatIndices(inArray, inIndices); + } + case Axis::ROW: + { + return detail::deleteRowIndices(inArray, inIndices); + } + case Axis::COL: + { + return detail::deleteColumnIndices(inArray, inIndices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndicesSlice + /// @param inAxis (Optional, default NONE) if none the indices will be applied to the flattened array + /// @return NdArray + /// + template + NdArray deleteIndices(const NdArray& inArray, Slice inIndicesSlice, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + inIndicesSlice.makePositiveAndValidate(inArray.size()); + break; + } + case Axis::ROW: + { + inIndicesSlice.makePositiveAndValidate(inArray.numRows()); + break; + } + case Axis::COL: + { + inIndicesSlice.makePositiveAndValidate(inArray.numCols()); + break; + } + } + + std::vector indices; + for (auto i = inIndicesSlice.start; i < inIndicesSlice.stop; i += inIndicesSlice.step) + { + indices.push_back(i); + } + + return deleteIndices(inArray, NdArray(indices.data(), indices.size(), false), inAxis); + } + + //============================================================================ + // Method Description: + /// Return a new array with sub-arrays along an axis deleted. + /// + /// @param inArray + /// @param inIndex + /// @param inAxis (Optional, default NONE) if none the indices will be applied to the flattened array + /// @return NdArray + /// + template + NdArray deleteIndices(const NdArray& inArray, int32 inIndex, Axis inAxis = Axis::NONE) + { + NdArray inIndices = { inIndex }; + return deleteIndices(inArray, inIndices, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/diag.hpp b/runexamples/cpp/include/NumCpp/Functions/diag.hpp new file mode 100644 index 0000000..eaf7952 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/diag.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Functions/diagonal.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Extract a diagonal or construct a diagonal array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diag.html + /// + /// @param inArray + /// @param k Diagonal in question. The default is 0. + /// Use k>0 for diagonals above the main diagonal, and k<0 + /// for diagonals below the main diagonal. + /// + /// @return NdArray + /// + template + NdArray diag(const NdArray& inArray, int32 k = 0) + { + if (inArray.isflat()) + { + return diagflat(inArray, k); + } + + return diagonal(inArray, k, Axis::ROW); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/diagflat.hpp b/runexamples/cpp/include/NumCpp/Functions/diagflat.hpp new file mode 100644 index 0000000..bc5bc6b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/diagflat.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Create a two-dimensional array with the flattened input as a diagonal. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diagflat.html + /// + /// @param inArray + /// @param k Diagonal to set; 0, the default, corresponds to the �main� diagonal, + /// a positive (negative) k giving the number of the diagonal above (below) the main. + /// + /// @return NdArray + /// + template + NdArray diagflat(const NdArray& inArray, int32 k = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto absK = static_cast(std::abs(k)); + NdArray returnArray(inArray.size() + absK); + + const uint32 rowOffset = k < 0 ? absK : 0; + const uint32 colOffset = k > 0 ? absK : 0; + + returnArray.zeros(); + for (uint32 i = 0; i < inArray.size(); ++i) + { + returnArray(i + rowOffset, i + colOffset) = inArray[i]; + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/diagonal.hpp b/runexamples/cpp/include/NumCpp/Functions/diagonal.hpp new file mode 100644 index 0000000..ae73992 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/diagonal.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return specified diagonals. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diagonal.html + /// + /// @param inArray + /// @param inOffset (Defaults to 0) + /// @param inAxis (Optional, default ROW) axis the offset is applied to + /// @return NdArray + /// + template + NdArray diagonal(const NdArray& inArray, int32 inOffset = 0, Axis inAxis = Axis::ROW) + { + return inArray.diagonal(inOffset, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/diff.hpp b/runexamples/cpp/include/NumCpp/Functions/diff.hpp new file mode 100644 index 0000000..75d7cac --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/diff.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the n-th discrete difference along given axis. + /// Unsigned dtypes will give you weird results...obviously. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.diff.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray diff(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + + switch (inAxis) + { + case Axis::NONE: + { + if (inArray.size() < 2) + { + return NdArray(0); + } + + NdArray returnArray(1, inArray.size() - 1); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend() - 1, + inArray.cbegin() + 1, + returnArray.begin(), + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return inValue2 - inValue1; }); + + return returnArray; + } + case Axis::COL: + { + if (inShape.cols < 2) + { + return NdArray(0); + } + + NdArray returnArray(inShape.rows, inShape.cols - 1); + for (uint32 row = 0; row < inShape.rows; ++row) + { + stl_algorithms::transform(inArray.cbegin(row), + inArray.cend(row) - 1, + inArray.cbegin(row) + 1, + returnArray.begin(row), + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return inValue2 - inValue1; }); + } + + return returnArray; + } + case Axis::ROW: + { + return diff(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/digitize.hpp b/runexamples/cpp/include/NumCpp/Functions/digitize.hpp new file mode 100644 index 0000000..b0bcb83 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/digitize.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the indices of the bins to which each value in input array belongs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.digitize.html + /// + /// @param x: Input array to be binned. + /// @param bins: Array of bins. + /// + /// @return NdArray + /// + template + NdArray digitize(const NdArray& x, const NdArray& bins) + { + const auto uniqueBins = unique(bins); + auto result = NdArray(1, x.size()); + result.fill(0); + + typename decltype(result)::size_type idx{ 0 }; + std::for_each(x.begin(), + x.end(), + [&uniqueBins, &result, &idx](const auto value) + { + const auto upperBin = std::upper_bound(uniqueBins.begin(), uniqueBins.end(), value); + result[idx++] = static_cast(std::distance(uniqueBins.begin(), upperBin)); + }); + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/divide.hpp b/runexamples/cpp/include/NumCpp/Functions/divide.hpp new file mode 100644 index 0000000..74ba2c3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/divide.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray divide(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray divide(const NdArray& inArray, dtype value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray divide(dtype value, const NdArray& inArray) + { + return value / inArray; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> divide(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> divide(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 / inArray2; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> divide(const NdArray& inArray, const std::complex& value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> divide(const std::complex& value, const NdArray& inArray) + { + return value / inArray; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> divide(const NdArray>& inArray, dtype value) + { + return inArray / value; + } + + //============================================================================ + // Method Description: + /// divide arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.divide.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> divide(dtype value, const NdArray>& inArray) + { + return value / inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/dot.hpp b/runexamples/cpp/include/NumCpp/Functions/dot.hpp new file mode 100644 index 0000000..44f57d5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/dot.hpp @@ -0,0 +1,163 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray dot(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1.dot(inArray2); + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> dot(const NdArray& inArray1, const NdArray>& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape1 = inArray1.shape(); + const auto shape2 = inArray2.shape(); + + if (shape1 == shape2 && (shape1.rows == 1 || shape1.cols == 1)) + { + const std::complex dotProduct = + std::inner_product(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), std::complex{ 0 }); + NdArray> returnArray = { dotProduct }; + return returnArray; + } + if (shape1.cols == shape2.rows) + { + // 2D array, use matrix multiplication + NdArray> returnArray(shape1.rows, shape2.cols); + auto array2T = inArray2.transpose(); + + for (uint32 i = 0; i < shape1.rows; ++i) + { + for (uint32 j = 0; j < shape2.cols; ++j) + { + returnArray(i, j) = std::inner_product(array2T.cbegin(j), + array2T.cend(j), + inArray1.cbegin(i), + std::complex{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape1.rows) + ", " + utils::num2str(shape1.cols) + "]"; + errStr += " and [" + utils::num2str(shape2.rows) + ", " + utils::num2str(shape2.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return NdArray>(); // get rid of compiler warning + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> dot(const NdArray>& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape1 = inArray1.shape(); + const auto shape2 = inArray2.shape(); + + if (shape1 == shape2 && (shape1.rows == 1 || shape1.cols == 1)) + { + const std::complex dotProduct = + std::inner_product(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), std::complex{ 0 }); + NdArray> returnArray = { dotProduct }; + return returnArray; + } + if (shape1.cols == shape2.rows) + { + // 2D array, use matrix multiplication + NdArray> returnArray(shape1.rows, shape2.cols); + auto array2T = inArray2.transpose(); + + for (uint32 i = 0; i < shape1.rows; ++i) + { + for (uint32 j = 0; j < shape2.cols; ++j) + { + returnArray(i, j) = std::inner_product(array2T.cbegin(j), + array2T.cend(j), + inArray1.cbegin(i), + std::complex{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape1.rows) + ", " + utils::num2str(shape1.cols) + "]"; + errStr += " and [" + utils::num2str(shape2.rows) + ", " + utils::num2str(shape2.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return NdArray>(); // get rid of compiler warning + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/dump.hpp b/runexamples/cpp/include/NumCpp/Functions/dump.hpp new file mode 100644 index 0000000..cd04612 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/dump.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Dump a binary file of the array to the specified file. + /// The array can be read back with or NC::load. + /// + /// @param inArray + /// @param inFilename + /// @return NdArray + /// + template + void dump(const NdArray& inArray, const std::string& inFilename) + { + inArray.dump(inFilename); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/empty.hpp b/runexamples/cpp/include/NumCpp/Functions/empty.hpp new file mode 100644 index 0000000..a88c7b1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/empty.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, without initializing entries. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray empty(uint32 inNumRows, uint32 inNumCols) + { + return NdArray(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, without initializing entries. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray empty(const Shape& inShape) + { + return NdArray(inShape); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/empty_like.hpp b/runexamples/cpp/include/NumCpp/Functions/empty_like.hpp new file mode 100644 index 0000000..f560a3c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/empty_like.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the same shape as a given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.empty_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray empty_like(const NdArray& inArray) + { + return NdArray(inArray.shape()); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/endianess.hpp b/runexamples/cpp/include/NumCpp/Functions/endianess.hpp new file mode 100644 index 0000000..73e9f63 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/endianess.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the endianess of the array values. + /// + /// @param inArray + /// @return Endian + /// + template + Endian endianess(const NdArray& inArray) noexcept + { + return inArray.endianess(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/equal.hpp b/runexamples/cpp/include/NumCpp/Functions/equal.hpp new file mode 100644 index 0000000..630d55b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/equal.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return (x1 == x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 == inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/exp.hpp b/runexamples/cpp/include/NumCpp/Functions/exp.hpp new file mode 100644 index 0000000..c370779 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/exp.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate the exponential of the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp.html + /// + /// @param inValue + /// @return value + /// + template + auto exp(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::exp(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the exponential of all elements in the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto exp(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return exp(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/exp2.hpp b/runexamples/cpp/include/NumCpp/Functions/exp2.hpp new file mode 100644 index 0000000..c343a16 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/exp2.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate 2**p for all p in the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp2.html + /// + /// @param inValue + /// @return value + /// + template + auto exp2(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::exp2(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate 2**p for all p in the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.exp2.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto exp2(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return exp2(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/expm1.hpp b/runexamples/cpp/include/NumCpp/Functions/expm1.hpp new file mode 100644 index 0000000..cf61a20 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/expm1.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Calculate exp(x) - 1 for the input value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.expm1.html + /// + /// @param inValue + /// @return value + /// + template + auto expm1(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::exp(inValue) - dtype{ 1 }; + } + + //============================================================================ + // Method Description: + /// Calculate exp(x) - 1 for all elements in the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.expm1.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto expm1(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return expm1(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/extract.hpp b/runexamples/cpp/include/NumCpp/Functions/extract.hpp new file mode 100644 index 0000000..66f603b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/extract.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the elements of an array that satisfy some condition. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.extract.html + /// + /// @param condition: An array whose nonzero or True entries indicate the elements of arr to extract. + /// @param arr: Input array of the same size as condition + /// @return NdArray + /// + template + NdArray extract(const NdArray& condition, const NdArray& arr) + { + if (condition.size() != arr.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input arguments 'condition' and 'arr' must have the same size."); + } + + std::vector values; + for (decltype(arr.size()) i = 0; i < arr.size(); ++i) + { + if (condition[i]) + { + values.push_back(arr[i]); + } + } + + return NdArray(values.begin(), values.end()); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/eye.hpp b/runexamples/cpp/include/NumCpp/Functions/eye.hpp new file mode 100644 index 0000000..d09d368 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/eye.hpp @@ -0,0 +1,123 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inN: number of rows (N) + /// @param inM: number of columns (M) + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(uint32 inN, uint32 inM, int32 inK = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inN, inM); + returnArray.zeros(); + + if (inK < 0) + { + uint32 col = 0; + for (uint32 row = inK; row < inN; ++row) + { + if (col >= inM) + { + break; + } + + returnArray(row, col++) = dtype{ 1 }; + } + } + else + { + uint32 row = 0; + for (uint32 col = inK; col < inM; ++col) + { + if (row >= inN) + { + break; + } + + returnArray(row++, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inN: number of rows and columns (N) + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(uint32 inN, int32 inK = 0) + { + return eye(inN, inN, inK); + } + + //============================================================================ + // Method Description: + /// Return a 2-D array with ones on the diagonal and zeros elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.eye.html + /// + /// @param inShape + /// @param inK: Index of the diagonal: 0 (the default) refers to the main diagonal, + /// a positive value refers to an upper diagonal, and a negative value to a lower diagonal. + /// + /// @return NdArray + /// + template + NdArray eye(const Shape& inShape, int32 inK = 0) + { + return eye(inShape.rows, inShape.cols, inK); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fillDiagnol.hpp b/runexamples/cpp/include/NumCpp/Functions/fillDiagnol.hpp new file mode 100644 index 0000000..b3c89c9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fillDiagnol.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Fill the main diagonal of the given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fill_diagonal.html + /// + /// @param inArray + /// @param inValue + /// + template + void fillDiagonal(NdArray& inArray, dtype inValue) noexcept + { + const auto inShape = inArray.shape(); + for (uint32 row = 0; row < inShape.rows; ++row) + { + if (row < inShape.cols) + { + inArray(row, row) = inValue; + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/find.hpp b/runexamples/cpp/include/NumCpp/Functions/find.hpp new file mode 100644 index 0000000..7ef6434 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/find.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find flat indices of nonzero elements. + /// + /// @param mask: the mask to apply to the array + /// @param n: the first n indices to return (optional, default all) + /// + /// @return NdArray + /// + inline NdArray find(const NdArray& mask, uint32 n = std::numeric_limits::max()) + { + NdArray indices = mask.flatnonzero(); + + if (indices.size() <= n) + { + return indices; + } + + return indices[Slice(0, n)]; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fix.hpp b/runexamples/cpp/include/NumCpp/Functions/fix.hpp new file mode 100644 index 0000000..fc98c9d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fix.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round to nearest integer towards zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fix.html + /// + /// @param inValue + /// @return value + /// + template + dtype fix(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue > 0 ? std::floor(inValue) : std::ceil(inValue); + } + + //============================================================================ + // Method Description: + /// Round to nearest integer towards zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fix.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray fix(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> double { return fix(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/flatnonzero.hpp b/runexamples/cpp/include/NumCpp/Functions/flatnonzero.hpp new file mode 100644 index 0000000..412020b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/flatnonzero.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return indices that are non-zero in the flattened version of a. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flatnonzero.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray flatnonzero(const NdArray& inArray) + { + return inArray.flatnonzero(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/flatten.hpp b/runexamples/cpp/include/NumCpp/Functions/flatten.hpp new file mode 100644 index 0000000..a9fe937 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/flatten.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a copy of the array collapsed into one dimension. + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray flatten(const NdArray& inArray) + { + return inArray.flatten(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/flip.hpp b/runexamples/cpp/include/NumCpp/Functions/flip.hpp new file mode 100644 index 0000000..963822b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/flip.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Reverse the order of elements in an array along the given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flip.html + /// + /// @param inArray + /// @param inAxis + /// @return NdArray + /// + template + NdArray flip(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray(inArray); + stl_algorithms::reverse(returnArray.begin(), returnArray.end()); + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inArray); + for (uint32 row = 0; row < inArray.shape().rows; ++row) + { + stl_algorithms::reverse(returnArray.begin(row), returnArray.end(row)); + } + return returnArray; + } + case Axis::ROW: + { + return flip(inArray.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fliplr.hpp b/runexamples/cpp/include/NumCpp/Functions/fliplr.hpp new file mode 100644 index 0000000..f841173 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fliplr.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flip array in the left/right direction. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fliplr.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray fliplr(const NdArray& inArray) + { + return flip(inArray, Axis::COL); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/flipud.hpp b/runexamples/cpp/include/NumCpp/Functions/flipud.hpp new file mode 100644 index 0000000..506ba5a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/flipud.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flip array in the up/down direction. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.flipud.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray flipud(const NdArray& inArray) + { + return flip(inArray, Axis::ROW); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/floor.hpp b/runexamples/cpp/include/NumCpp/Functions/floor.hpp new file mode 100644 index 0000000..54d0250 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/floor.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the floor of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor.html + /// + /// @param inValue + /// @return value + /// + template + dtype floor(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::floor(inValue); + } + + //============================================================================ + // Method Description: + /// Return the floor of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray floor(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return floor(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/floor_divide.hpp b/runexamples/cpp/include/NumCpp/Functions/floor_divide.hpp new file mode 100644 index 0000000..5da8361 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/floor_divide.hpp @@ -0,0 +1,71 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/floor.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the largest integer smaller or equal to the division of the inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor_divide.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype floor_divide(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::floor(inValue1 / inValue2); + } + + //============================================================================ + // Method Description: + /// Return the largest integer smaller or equal to the division of the inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.floor_divide.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray floor_divide(const NdArray& inArray1, const NdArray& inArray2) + { + return floor(inArray1 / inArray2); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fmax.hpp b/runexamples/cpp/include/NumCpp/Functions/fmax.hpp new file mode 100644 index 0000000..74a326c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fmax.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// maximum of inputs. + /// + /// Compare two value and returns a value containing the + /// maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype fmax(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::max(inValue1, + inValue2, + [](const dtype value1, const dtype value2) noexcept -> bool { return value1 < value2; }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmax(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return fmax(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray fmax(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return fmax(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise maxima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmax.html + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray fmax(const dtype& inScalar, const NdArray& inArray) + { + return fmax(inArray, inScalar); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fmin.hpp b/runexamples/cpp/include/NumCpp/Functions/fmin.hpp new file mode 100644 index 0000000..d167ea1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fmin.hpp @@ -0,0 +1,127 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// minimum of inputs. + /// + /// Compare two value and returns a value containing the + /// minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template + dtype fmin(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::min(inValue1, + inValue2, + [](const dtype value1, const dtype value2) noexcept -> bool { return value1 < value2; }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmin(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> dtype + { return fmin(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray fmin(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return fmin(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// Compare two arrays and returns a new array containing the + /// element - wise minima + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmin.html + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray fmin(const dtype& inScalar, const NdArray& inArray) + { + return fmin(inArray, inScalar); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fmod.hpp b/runexamples/cpp/include/NumCpp/Functions/fmod.hpp new file mode 100644 index 0000000..f1e5746 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fmod.hpp @@ -0,0 +1,90 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template, int> = 0> + dtype fmod(dtype inValue1, dtype inValue2) noexcept + { + return inValue1 % inValue2; + } + + //============================================================================ + // Method Description: + /// Return the remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @return value + /// + template, int> = 0> + dtype fmod(dtype inValue1, dtype inValue2) noexcept + { + return std::fmod(inValue1, inValue2); + } + + //============================================================================ + // Method Description: + /// Return the element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fmod.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray fmod(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 % inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/frombuffer.hpp b/runexamples/cpp/include/NumCpp/Functions/frombuffer.hpp new file mode 100644 index 0000000..371679a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/frombuffer.hpp @@ -0,0 +1,57 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Interpret a buffer as a 1-dimensional array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.frombuffer.html + /// + /// @param inBufferPtr + /// @param inNumBytes + /// @return NdArray + /// + template + NdArray frombuffer(const char* inBufferPtr, uint32 inNumBytes) + { + if (inNumBytes % sizeof(dtype) != 0) + { + THROW_INVALID_ARGUMENT_ERROR("inNumBytes % sizeof(dtype) != 0"); + } + + const auto numElements = static_cast(inNumBytes / sizeof(dtype)); + return NdArray(reinterpret_cast(inBufferPtr), numElements); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fromfile.hpp b/runexamples/cpp/include/NumCpp/Functions/fromfile.hpp new file mode 100644 index 0000000..8f81358 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fromfile.hpp @@ -0,0 +1,113 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/fromstring.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array from data in a binary file. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromfile.html + /// + /// @param inFilename + /// @return NdArray + /// + template + NdArray fromfile(const std::string& inFilename) + { + if (!std::filesystem::exists(inFilename)) + { + THROW_INVALID_ARGUMENT_ERROR("input filename does not exist.\n\t" + inFilename); + } + + // read in as binary file + std::ifstream file(inFilename.c_str(), std::ios::in | std::ios::binary); + if (!file.is_open()) + { + THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename); + } + + file.seekg(0, std::ifstream::end); + const uint32 fileSize = static_cast(file.tellg()); + file.seekg(0, std::ifstream::beg); + + std::vector fileBuffer; + fileBuffer.reserve(fileSize); + file.read(fileBuffer.data(), fileSize); + + if (file.bad() || file.fail()) + { + THROW_INVALID_ARGUMENT_ERROR("error occured while reading the file"); + } + + file.close(); + + NdArray returnArray(reinterpret_cast(fileBuffer.data()), fileSize / sizeof(dtype)); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Construct an array from data in a text file. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromfile.html + /// + /// @param inFilename + /// @param inSep: Delimiter separator between values in the file + /// @return NdArray + /// + template + NdArray fromfile(const std::string& inFilename, const char inSep) + { + std::ifstream file(inFilename.c_str()); + if (!file.is_open()) + { + THROW_INVALID_ARGUMENT_ERROR("unable to open file\n\t" + inFilename); + } + + std::stringstream buffer; + buffer << file.rdbuf(); + file.close(); + + return fromstring(buffer.str(), inSep); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fromfunction.hpp b/runexamples/cpp/include/NumCpp/Functions/fromfunction.hpp new file mode 100644 index 0000000..b5024bd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fromfunction.hpp @@ -0,0 +1,115 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array by executing a function over each coordinate. + /// The resulting array therefore has a value fn(x) at coordinate(x). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html + /// + /// @param func: callable that accepts an integer coordinate and returns type T + /// @param size: the size of the 1d array to create + /// + /// @return NdArray + /// + template + NdArray fromfunction(const std::function::size_type)> func, + typename NdArray::size_type size) + { + NdArray result(1, size); + const auto indices = [size] + { + std::vector::size_type> temp(size); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + + stl_algorithms::transform(indices.begin(), + indices.end(), + result.begin(), + [&func](const auto idx) { return func(idx); }); + + return result; + } + + //============================================================================ + // Method Description: + /// Construct an array by executing a function over each coordinate. + /// The resulting array therefore has a value fn(x, y) at coordinate(x, y). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html + /// + /// @param func: callable that accepts an integer coordinate and returns type T + /// @param shape: the shape of the array to create + /// + /// @return NdArray + /// + template + NdArray fromfunction( + const std::function::size_type, typename NdArray::size_type)> func, + Shape shape) + { + NdArray result(shape); + const auto rows = [&shape] + { + std::vector::size_type> temp(shape.rows); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + const auto cols = [&shape] + { + std::vector::size_type> temp(shape.cols); + std::iota(temp.begin(), temp.end(), 0); + return temp; + }(); + + stl_algorithms::for_each(rows.begin(), + rows.end(), + [&cols, &result, &func](const auto row) + { + stl_algorithms::transform(cols.begin(), + cols.end(), + result.begin(row), + [&func, row](const auto col) { return func(row, col); }); + }); + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fromiter.hpp b/runexamples/cpp/include/NumCpp/Functions/fromiter.hpp new file mode 100644 index 0000000..45c9acc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fromiter.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Create a new 1-dimensional array from an iterable object. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromiter.html + /// + /// @param inBegin + /// @param inEnd + /// @return NdArray + /// + template + NdArray fromiter(Iter inBegin, Iter inEnd) + { + return NdArray(inBegin, inEnd); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/fromstring.hpp b/runexamples/cpp/include/NumCpp/Functions/fromstring.hpp new file mode 100644 index 0000000..ed7e35e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/fromstring.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array from data in a string + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.fromstring.html + /// + /// @param inStr + /// @param inSep: Delimiter separator between values in the string + /// @return NdArray + /// + template + NdArray fromstring(const std::string& inStr, const char inSep = ' ') + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::istringstream inputStream(inStr); + auto values = std::vector{}; + dtype value{}; + for (std::string segment; std::getline(inputStream, segment, inSep);) + { + if (!inputStream.fail()) + { + std::istringstream segmentStream(segment); + while (segmentStream >> value) + { + if (!inputStream.fail()) + { + values.push_back(value); + } + } + } + } + + return NdArray(values); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/full.hpp b/runexamples/cpp/include/NumCpp/Functions/full.hpp new file mode 100644 index 0000000..8611526 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/full.hpp @@ -0,0 +1,88 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inSquareSize + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(uint32 inSquareSize, dtype inFillValue) + { + NdArray returnArray(inSquareSize, inSquareSize); + returnArray.fill(inFillValue); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inNumRows + /// @param inNumCols + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(uint32 inNumRows, uint32 inNumCols, dtype inFillValue) + { + NdArray returnArray(inNumRows, inNumCols); + returnArray.fill(inFillValue); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with inFillValue + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full.html + /// + /// @param inShape + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full(const Shape& inShape, dtype inFillValue) + { + return full(inShape.rows, inShape.cols, inFillValue); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/full_like.hpp b/runexamples/cpp/include/NumCpp/Functions/full_like.hpp new file mode 100644 index 0000000..503bb11 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/full_like.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a full array with the same shape and type as a given array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.full_like.html + /// + /// @param inArray + /// @param inFillValue + /// @return NdArray + /// + template + NdArray full_like(const NdArray& inArray, dtype inFillValue) + { + return full(inArray.shape(), inFillValue); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/gcd.hpp b/runexamples/cpp/include/NumCpp/Functions/gcd.hpp new file mode 100644 index 0000000..10d16d6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/gcd.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/integer/common_factor_rt.hpp" +#endif + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the greatest common divisor of |x1| and |x2|. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gcd.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return dtype + /// + template + dtype gcd(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + +#ifdef __cpp_lib_gcd_lcm + return std::gcd(inValue1, inValue2); +#else + return boost::integer::gcd(inValue1, inValue2); +#endif // #ifdef __cpp_lib_gcd_lcm + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Returns the greatest common divisor of the values in the + /// input array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gcd.html + /// + /// @param inArray + /// @return NdArray + /// + template + dtype gcd(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + return boost::integer::gcd_range(inArray.cbegin(), inArray.cend()).first; + } +#endif // #ifndef NUMCPP_NO_USE_BOOST +} // namespace nc + +#endif // defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) \ No newline at end of file diff --git a/runexamples/cpp/include/NumCpp/Functions/geomspace.hpp b/runexamples/cpp/include/NumCpp/Functions/geomspace.hpp new file mode 100644 index 0000000..57ef785 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/geomspace.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/logb.hpp" +#include "NumCpp/Functions/logspace.hpp" +#include "NumCpp/Functions/nth_root.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return numbers spaced evenly on a log scale (a geometric progression). + /// + /// This is similar to logspace, but with endpoints specified directly. + /// Each output sample is a constant multiple of the previous. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.geomspace.html + /// + /// @param start: the starting value of a sequence + /// @param stop: The final value of the sequence, unless endpoint is False. + /// In that case, num + 1 values are spaced over the interval + /// in log-space, of which all but the last (a sequence of length num) are returned. + /// @param num: Number of samples to generate. Default 50. + /// @param endPoint: If true, stop is the last sample. Otherwide,it is not included. Default is true. + /// @return NdArray + /// + template + NdArray geomspace(dtype start, dtype stop, uint32 num = 50, bool endPoint = true) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (utils::essentiallyEqual(start, dtype{ 0 })) + { + THROW_INVALID_ARGUMENT_ERROR("Geometric sequence cannot include zero"); + } + + if (num == 1) + { + return { static_cast(start) }; + } + else if (num == 2 && endPoint) + { + return { static_cast(start), static_cast(stop) }; + } + + const auto base = nth_root(stop / start, num - 1); + const auto logStart = logb(start, base); + const auto logStop = logb(stop, base); + return logspace(logStart, logStop, num, endPoint, base); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/gradient.hpp b/runexamples/cpp/include/NumCpp/Functions/gradient.hpp new file mode 100644 index 0000000..777a515 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/gradient.hpp @@ -0,0 +1,247 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the gradient of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gradient.html + /// + /// + /// @param inArray + /// @param inAxis (default ROW) + /// @return NdArray + /// + template + NdArray gradient(const NdArray& inArray, Axis inAxis = Axis::ROW) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::ROW: + { + const auto inShape = inArray.shape(); + if (inShape.rows < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 row."); + } + + // first do the first and last rows + auto returnArray = NdArray(inShape); + for (uint32 col = 0; col < inShape.cols; ++col) + { + returnArray(0, col) = static_cast(inArray(1, col)) - static_cast(inArray(0, col)); + returnArray(-1, col) = + static_cast(inArray(-1, col)) - static_cast(inArray(-2, col)); + } + + // then rip through the rest of the array + for (uint32 col = 0; col < inShape.cols; ++col) + { + for (uint32 row = 1; row < inShape.rows - 1; ++row) + { + returnArray(row, col) = + (static_cast(inArray(row + 1, col)) - static_cast(inArray(row - 1, col))) / + 2.; + } + } + + return returnArray; + } + case Axis::COL: + { + const auto inShape = inArray.shape(); + if (inShape.cols < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 columns."); + } + + // first do the first and last columns + auto returnArray = NdArray(inShape); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(row, 0) = static_cast(inArray(row, 1)) - static_cast(inArray(row, 0)); + returnArray(row, -1) = + static_cast(inArray(row, -1)) - static_cast(inArray(row, -2)); + } + + // then rip through the rest of the array + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 1; col < inShape.cols - 1; ++col) + { + returnArray(row, col) = + (static_cast(inArray(row, col + 1)) - static_cast(inArray(row, col - 1))) / + 2.; + } + } + + return returnArray; + } + default: + { + // will return the gradient of the flattened array + if (inArray.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 element."); + } + + auto returnArray = NdArray(1, inArray.size()); + returnArray[0] = static_cast(inArray[1]) - static_cast(inArray[0]); + returnArray[-1] = static_cast(inArray[-1]) - static_cast(inArray[-2]); + + stl_algorithms::transform(inArray.cbegin() + 2, + inArray.cend(), + inArray.cbegin(), + returnArray.begin() + 1, + [](dtype value1, dtype value2) -> double + { return (static_cast(value1) - static_cast(value2)) / 2.; }); + + return returnArray; + } + } + } + + //============================================================================ + // Method Description: + /// Return the gradient of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.gradient.html + /// + /// + /// @param inArray + /// @param inAxis (default ROW) + /// @return NdArray + /// + template + NdArray> gradient(const NdArray>& inArray, Axis inAxis = Axis::ROW) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::ROW: + { + const auto inShape = inArray.shape(); + if (inShape.rows < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 row."); + } + + // first do the first and last rows + auto returnArray = NdArray>(inShape); + for (uint32 col = 0; col < inShape.cols; ++col) + { + returnArray(0, col) = complex_cast(inArray(1, col)) - complex_cast(inArray(0, col)); + returnArray(-1, col) = + complex_cast(inArray(-1, col)) - complex_cast(inArray(-2, col)); + } + + // then rip through the rest of the array + for (uint32 col = 0; col < inShape.cols; ++col) + { + for (uint32 row = 1; row < inShape.rows - 1; ++row) + { + returnArray(row, col) = (complex_cast(inArray(row + 1, col)) - + complex_cast(inArray(row - 1, col))) / + 2.; + } + } + + return returnArray; + } + case Axis::COL: + { + const auto inShape = inArray.shape(); + if (inShape.cols < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 columns."); + } + + // first do the first and last columns + auto returnArray = NdArray>(inShape); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray(row, 0) = complex_cast(inArray(row, 1)) - complex_cast(inArray(row, 0)); + returnArray(row, -1) = + complex_cast(inArray(row, -1)) - complex_cast(inArray(row, -2)); + } + + // then rip through the rest of the array + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 1; col < inShape.cols - 1; ++col) + { + returnArray(row, col) = (complex_cast(inArray(row, col + 1)) - + complex_cast(inArray(row, col - 1))) / + 2.; + } + } + + return returnArray; + } + default: + { + // will return the gradient of the flattened array + if (inArray.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("input array must have more than 1 element."); + } + + auto returnArray = NdArray>(1, inArray.size()); + returnArray[0] = complex_cast(inArray[1]) - complex_cast(inArray[0]); + returnArray[-1] = complex_cast(inArray[-1]) - complex_cast(inArray[-2]); + + stl_algorithms::transform( + inArray.cbegin() + 2, + inArray.cend(), + inArray.cbegin(), + returnArray.begin() + 1, + [](const std::complex& value1, const std::complex& value2) -> std::complex + { return (complex_cast(value1) - complex_cast(value2)) / 2.; }); + + return returnArray; + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/greater.hpp b/runexamples/cpp/include/NumCpp/Functions/greater.hpp new file mode 100644 index 0000000..37b6caf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/greater.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 > x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray greater(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 > inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/greater_equal.hpp b/runexamples/cpp/include/NumCpp/Functions/greater_equal.hpp new file mode 100644 index 0000000..47fccbc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/greater_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 >= x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.greater_equal.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray greater_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 >= inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/hamming.hpp b/runexamples/cpp/include/NumCpp/Functions/hamming.hpp new file mode 100644 index 0000000..fee9d5e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hamming.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the Hamming window. + /// + /// The Hamming window is a taper formed by using a weighted cosine. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hamming.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray hamming(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto twoPiDivMMinus1 = (2. * constants::pi) / (mDouble - 1.); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = 0.54 - 0.46 * std::cos(twoPiDivMMinus1 * n); + } + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/hammingEncode.hpp b/runexamples/cpp/include/NumCpp/Functions/hammingEncode.hpp new file mode 100644 index 0000000..6272b6b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hammingEncode.hpp @@ -0,0 +1,396 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Hamming EDAC encoding https://en.wikipedia.org/wiki/Hamming_code +/// + +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include +#include +#include +#include +#include +#include + +#include "boost/dynamic_bitset.hpp" + +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::edac +{ + namespace detail + { + //============================================================================ + // Method Description: + /// @brief Tests if value is a power of two + /// + /// @param n integer value + /// @return bool true if value is a power of two, else false + /// + template, int> = 0> + constexpr bool isPowerOfTwo(IntType n) noexcept + { + // Returns true if the given non-negative integer n is a power of two. + return n != 0 && (n & (n - 1)) == 0; + } + + //============================================================================ + // Method Description: + /// Calculates the next power of two after n + /// >>> _next_power_of_two(768) + /// 1024 + /// >>> _next_power_of_two(4) + /// 8 + /// + /// @param n integer value + /// @return next power of two + /// @exception std::invalid_argument if input value is less than zero + //// + template, int> = 0> + std::size_t nextPowerOfTwo(IntType n) + { + if (n < 0) + { + throw std::invalid_argument("Input value must be greater than or equal to zero."); + } + + if (isPowerOfTwo(n)) + { + return static_cast(n) << 1; + } + + return static_cast(std::pow(2, std::ceil(std::log2(n)))); + } + + //============================================================================ + // Method Description: + /// Calculates the first n powers of two + /// + /// @param n integer value + /// @return first n powers of two + /// @exception std::bad_alloc if unable to allocate for return vector + /// + template, int> = 0> + std::vector powersOfTwo(IntType n) + { + auto i = std::size_t{ 0 }; + auto power = std::size_t{ 1 }; + auto powers = std::vector(); + powers.reserve(n); + + while (i < static_cast(n)) + { + powers.push_back(power); + power <<= 1; + ++i; + } + + return powers; + } + + //============================================================================ + // Method Description: + /// Calculates the number of needed Hamming SECDED parity bits to encode the data + /// + /// @param numDataBits the number of data bits to encode + /// @return number of Hamming SECDED parity bits + /// @exception std::invalid_argument if input value is less than zero + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + std::size_t numSecdedParityBitsNeeded(IntType numDataBits) + { + const auto n = nextPowerOfTwo(numDataBits); + const auto lowerBin = static_cast(std::floor(std::log2(n))); + const auto upperBin = lowerBin + 1; + const auto dataBitBoundary = n - lowerBin - 1; + const auto numParityBits = numDataBits <= dataBitBoundary ? lowerBin + 1 : upperBin + 1; + + if (!isPowerOfTwo(numParityBits + numDataBits)) + { + throw std::runtime_error("input number of data bits is not a valid Hamming SECDED code configuration."); + } + + return numParityBits; + } + + //============================================================================ + // Method Description: + /// Returns the indices of all data bits covered by a specified parity bit in a bitstring + /// of length numDataBits. The indices are relative to DATA BITSTRING ITSELF, NOT including + /// parity bits. + /// + /// @param numDataBits the number of data bits to encode + /// @param parityBit the parity bit number + /// @return number of Hamming SECDED parity bits + /// @exception std::invalid_argument if parityBit is not a power of two + /// @exception std::bad_alloc if unable to allocate return vector + /// + template, int> = 0, + std::enable_if_t, int> = 0> + std::vector dataBitsCovered(IntType1 numDataBits, IntType2 parityBit) + { + if (!isPowerOfTwo(parityBit)) + { + throw std::invalid_argument("All hamming parity bits are indexed by powers of two."); + } + + std::size_t dataIndex = 1; // bit we're currently at in the DATA bitstring + std::size_t totalIndex = 3; // bit we're currently at in the OVERALL bitstring + auto parityBit_ = static_cast(parityBit); + + auto indices = std::vector(); + indices.reserve(numDataBits); // worst case + + while (dataIndex <= static_cast(numDataBits)) + { + const auto currentBitIsData = !isPowerOfTwo(totalIndex); + if (currentBitIsData && (totalIndex % (parityBit_ << 1)) >= parityBit_) + { + indices.push_back(dataIndex - 1); // adjust output to be zero indexed + } + + dataIndex += currentBitIsData ? 1 : 0; + ++totalIndex; + } + + return indices; + } + + //============================================================================ + // Method Description: + /// Calculates the overall parity of the data, assumes last bit is the parity bit itself + /// + /// @param data the data word + /// @return overall parity bit value + /// + template + constexpr bool calculateParity(const std::bitset& data) noexcept + { + bool parity = false; + for (std::size_t i = 0; i < DataBits - 1; ++i) + { + parity ^= data[i]; + } + + return parity; + } + + //============================================================================ + // Method Description: + /// Calculates the overall parity of the data, assumes last bit is the parity bit itself + /// + /// @param data the data word + /// @return overall parity bit value + /// + inline bool calculateParity(const boost::dynamic_bitset<>& data) noexcept + { + bool parity = false; + for (std::size_t i = 0; i < data.size() - 1; ++i) + { + parity ^= data[i]; + } + + return parity; + } + + //============================================================================ + // Method Description: + /// Calculates the specified Hamming parity bit (1, 2, 4, 8, etc.) for the given data. + /// Assumes even parity to allow for easier computation of parity using XOR. + /// + /// @param data the data word + /// @param parityBit the parity bit number + /// @return parity bit value + /// @exception std::invalid_argument if parityBit is not a power of two + /// @exception std::bad_alloc if unable to allocate return vector + /// + template, int> = 0> + bool calculateParity(const std::bitset& data, IntType parityBit) + { + const auto bitsCovered = dataBitsCovered(DataBits, parityBit); + return std::accumulate(bitsCovered.begin(), + bitsCovered.end(), + false, + [&data](bool parity, const auto value) noexcept -> bool { return parity ^= value; }); + } + + //============================================================================ + // Method Description: + /// Checks that the number of DataBits and EncodedBits are consistent + /// + /// @return the number of parity bits + /// @exception std::runtime_error if DataBits and EncodedBits are not consistent + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + std::size_t checkBitsConsistent() + { + const auto numParityBits = detail::numSecdedParityBitsNeeded(DataBits); + if (numParityBits + DataBits != EncodedBits) + { + throw std::runtime_error("DataBits and EncodedBits are not consistent"); + } + + return numParityBits; + } + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED decoded bits from the endoded bits. Assumes that the + /// DataBits and EncodedBits have been checks for consistancy already + /// + /// @param encodedBits the Hamming SECDED encoded word + /// @return data bits from the encoded word + /// + template, int> = 0> + std::bitset extractData(const std::bitset& encodedBits) noexcept + { + auto dataBits = std::bitset(); + + std::size_t dataIndex = 0; + for (std::size_t encodedIndex = 0; encodedIndex < EncodedBits; ++encodedIndex) + { + if (!isPowerOfTwo(encodedIndex + 1)) + { + dataBits[dataIndex++] = encodedBits[encodedIndex]; + if (dataIndex == DataBits) + { + break; + } + } + } + + return dataBits; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED encoded bits for the data bits + /// + /// @param dataBits the data bits to encode + /// @return encoded data bits + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template + boost::dynamic_bitset<> encode(const std::bitset& dataBits) + { + const auto numParityBits = detail::numSecdedParityBitsNeeded(DataBits); + const auto numEncodedBits = numParityBits + DataBits; + + auto encodedBits = boost::dynamic_bitset<>(numEncodedBits); // NOLINT(google-readability-casting) + + // set the parity bits + for (const auto parityBit : + detail::powersOfTwo(numParityBits - 1)) // -1 because overall parity will be calculated seperately later + { + encodedBits[parityBit - 1] = detail::calculateParity(dataBits, parityBit); + } + + // set the data bits, switch to 1 based to make things easier for isPowerOfTwo + std::size_t dataBitIndex = 0; + for (std::size_t bitIndex = 1; bitIndex <= numEncodedBits - 1; + ++bitIndex) // -1 to account for the overall parity bit + { + if (!detail::isPowerOfTwo(bitIndex)) + { + encodedBits[bitIndex - 1] = dataBits[dataBitIndex++]; + } + } + + // compute and set overall parity for the entire encoded data (not including the overall parity bit itself) + encodedBits[numEncodedBits - 1] = detail::calculateParity(encodedBits); // overall parity at the end + + // all done! + return encodedBits; + } + + //============================================================================ + // Method Description: + /// Returns the Hamming SECDED decoded bits for the enocoded bits + /// https://en.wikipedia.org/wiki/Hamming_code + /// + /// @param encodedBits the encoded bits to decode + /// @param decodedBits the output decoded bits + /// @return int status (0=no errors, 1=1 corrected error, 2=2 errors detected) + /// @exception std::runtime_error if DataBits and EncodedBits are not consistent + /// @exception std::runtime_error if the number of data bits does not represent a valid Hamming SECDED code + /// + template, int> = 0> + int decode(std::bitset encodedBits, std::bitset& decodedBits) + { + const auto numParityBits = detail::checkBitsConsistent(); + + // the data bits, which may be corrupted + decodedBits = detail::extractData(encodedBits); + + // check the overall parity bit + const auto overallExpected = detail::calculateParity(encodedBits); + const auto overallActual = encodedBits[EncodedBits - 1]; + const auto overallCorrect = overallExpected == overallActual; + + // check individual parities - each parity bit's index (besides overall parity) is a power of two + std::size_t indexOfError = 0; + for (const auto parityBit : detail::powersOfTwo(numParityBits - 1)) + { + const auto expected = detail::calculateParity(decodedBits, parityBit); + const auto actual = encodedBits[parityBit - 1]; // -1 because parityBit is 1 based + if (expected != actual) + { + indexOfError += parityBit; + } + } + + // attempt to repair a single flipped bit or throw exception if more than one + if (overallCorrect && indexOfError != 0) + { + // two errors found + return 2; + } + else if (!overallCorrect && indexOfError != 0) + { + // one error found, flip the bit in error and we're good + encodedBits.flip(indexOfError - 1); + decodedBits = detail::extractData(encodedBits); + return 1; + } + + return 0; + } +} // namespace nc::edac +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Functions/hanning.hpp b/runexamples/cpp/include/NumCpp/Functions/hanning.hpp new file mode 100644 index 0000000..cc75868 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hanning.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the Hamming window. + /// + /// The Hanning window is a taper formed by using a weighted cosine. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hanning.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @return NdArray + /// + inline NdArray hanning(int32 m) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto twoPiDivMMinus1 = (2. * constants::pi) / (mDouble - 1.); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(0., mDouble - 1., m, true)) + { + result[i++] = 0.5 - 0.5 * std::cos(twoPiDivMMinus1 * n); + } + + return result; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/histogram.hpp b/runexamples/cpp/include/NumCpp/Functions/histogram.hpp new file mode 100644 index 0000000..6be744d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/histogram.hpp @@ -0,0 +1,142 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the histogram of a set of data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.histogram.html + /// + /// + /// @param inArray + /// @param inBinEdges: monotonically increasing array of bin edges, including the + /// rightmost edge, allowing for non-uniform bin widths. + /// + /// @return array of histogram counts + /// + template + NdArray histogram(const NdArray& inArray, const NdArray& inBinEdges) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inBinEdges.size() < 2) + { + THROW_INVALID_ARGUMENT_ERROR("number of bin edges must be >= 2."); + } + + // sort just in case the user hasn't already + const auto binEdges = sort(inBinEdges); + + NdArray histo = zeros(1, binEdges.size() - 1); + for (const auto value : inArray) + { + if (value < binEdges.front() || value > binEdges.back()) + { + continue; + } + + // binary search to find the bin idx + constexpr bool keepSearching = true; + uint32 lowIdx = 0; + uint32 highIdx = binEdges.size() - 1; + while (keepSearching) + { + const uint32 idx = (lowIdx + highIdx) / 2; // integer division + if (lowIdx == highIdx || lowIdx == highIdx - 1) + { + // we found the bin + ++histo[lowIdx]; + break; + } + + if (value > binEdges[idx]) + { + lowIdx = idx; + } + else if (value < binEdges[idx]) + { + highIdx = idx; + } + else + { + // we found the bin + ++histo[idx]; + break; + } + } + } + + return histo; + } + + //============================================================================ + // Method Description: + /// Compute the histogram of a set of data. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.histogram.html + /// + /// + /// @param inArray + /// @param inNumBins( default 10) + /// + /// @return std::pair of NdArrays; first is histogram counts, seconds is the bin edges + /// + template + std::pair, NdArray> histogram(const NdArray& inArray, uint32 inNumBins = 10) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inNumBins == 0) + { + THROW_INVALID_ARGUMENT_ERROR("number of bins must be positive."); + } + + constexpr bool useEndPoint = true; + const NdArray binEdges = linspace(static_cast(inArray.min().item()), + static_cast(inArray.max().item()), + inNumBins + 1, + useEndPoint); + + const auto histo = histogram(inArray, binEdges); + return std::make_pair(histo, binEdges); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/hsplit.hpp b/runexamples/cpp/include/NumCpp/Functions/hsplit.hpp new file mode 100644 index 0000000..347a274 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hsplit.hpp @@ -0,0 +1,107 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays horizontal (column-wise). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html + /// + /// @param inArray + /// @param indices: the indices to split + /// + /// @return NdArray + /// + template = 0> + std::vector> hsplit(const NdArray& inArray, const Indices& indices) + { + const auto numCols = static_cast(inArray.numCols()); + NdArray uniqueIndices(1, indices.size()); + stl_algorithms::transform(indices.begin(), + indices.end(), + uniqueIndices.begin(), + [numCols](auto index) noexcept -> int32 + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index = std::max(index + numCols, int32{ 0 }); + } + } + if (static_cast(index) > numCols - 1) + { + index = numCols - 1; + } + + return static_cast(index); + }); + uniqueIndices = unique(uniqueIndices); + + std::vector> splits{}; + splits.reserve(uniqueIndices.size() + 1); + + const auto rSlice = inArray.rSlice(); + int32 lowerIdx = 0; + for (const auto index : uniqueIndices) + { + if (index == 0) + + { + splits.push_back(NdArray(Shape(inArray.numRows(), 0))); + continue; + } + else + { + splits.push_back(inArray(rSlice, Slice(lowerIdx, index))); + } + + lowerIdx = index; + } + + if (lowerIdx < numCols - 1) + { + splits.push_back(inArray(rSlice, Slice(lowerIdx, numCols))); + } + else + { + splits.push_back(inArray(rSlice, -1)); + } + + return splits; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/hstack.hpp b/runexamples/cpp/include/NumCpp/Functions/hstack.hpp new file mode 100644 index 0000000..6b7bbe7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hstack.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Stack arrays in sequence horizontally (column wise). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hstack.html + /// + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray hstack(std::initializer_list> inArrayList) + { + return column_stack(inArrayList); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/hypot.hpp b/runexamples/cpp/include/NumCpp/Functions/hypot.hpp new file mode 100644 index 0000000..13279f6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/hypot.hpp @@ -0,0 +1,146 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return value + /// + template + double hypot(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::hypot(static_cast(inValue1), static_cast(inValue2)); + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2 + x3**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inValue1 + /// @param inValue2 + /// @param inValue3 + /// + /// @return value + /// + template + double hypot(dtype inValue1, dtype inValue2, dtype inValue3) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_hypot + return std::hypot(static_cast(inValue1), static_cast(inValue2), static_cast(inValue3)); +#else + return std::sqrt(utils::sqr(static_cast(inValue1)) + utils::sqr(static_cast(inValue2)) + + utils::sqr(static_cast(inValue3))); +#endif + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray hypot(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> double + { return hypot(inValue1, inValue2); }); + } + + //============================================================================ + // Method Description: + /// Given the "legs" of a right triangle, return its hypotenuse. + /// + /// Equivalent to sqrt(x1**2 + x2**2), element - wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.hypot.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// @param inArray3 + /// + /// @return NdArray + /// + template + NdArray + hypot(const NdArray& inArray1, const NdArray& inArray2, const NdArray& inArray3) + { + if (inArray1.size() != inArray2.size() || inArray1.size() != inArray3.size()) + { + THROW_INVALID_ARGUMENT_ERROR("input array sizes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + for (typename NdArray::size_type i = 0; i < inArray1.size(); ++i) + { + returnArray[i] = hypot(inArray1[i], inArray2[i], inArray3[i]); + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/identity.hpp b/runexamples/cpp/include/NumCpp/Functions/identity.hpp new file mode 100644 index 0000000..ad77c35 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/identity.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the identity array. + /// + /// The identity array is a square array with ones on the main diagonal. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.identity.html + /// + /// @param inSquareSize + /// + /// @return NdArray + /// + template + NdArray identity(uint32 inSquareSize) + { + NdArray returnArray(inSquareSize); + returnArray.zeros(); + for (uint32 i = 0; i < inSquareSize; ++i) + { + returnArray(i, i) = dtype{ 1 }; + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/imag.hpp b/runexamples/cpp/include/NumCpp/Functions/imag.hpp new file mode 100644 index 0000000..d65211d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/imag.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the imaginar part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.imag.html + /// + /// @param inValue + /// @return value + /// + template + auto imag(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::imag(inValue); + } + + //============================================================================ + // Method Description: + /// Return the imaginary part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.imag.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto imag(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::imag(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/inner.hpp b/runexamples/cpp/include/NumCpp/Functions/inner.hpp new file mode 100644 index 0000000..4f24022 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/inner.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Inner product of two 1-D arrays. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.inner.html + /// + /// @param a: array 1 + /// @param b: array 2 + /// @return NdArray + /// + template + dtype inner(const NdArray& a, const NdArray& b) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (a.size() != b.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'a' and 'b' must have the same size"); + } + + return std::inner_product(a.cbegin(), a.cend(), b.cbegin(), dtype{ 0 }); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/insert.hpp b/runexamples/cpp/include/NumCpp/Functions/insert.hpp new file mode 100644 index 0000000..3ab350a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/insert.hpp @@ -0,0 +1,551 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/ones_like.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Insert values before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the value before in the flattened + /// @param value: value to insert + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const dtype& value) + { + const NdArray values = { value }; + return insert(arr, index, values); + } + + //============================================================================ + // Method Description: + /// Insert values before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before in the flattened + /// @param values: value to insert + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const NdArray& values) + { + if (index < 0) + { + index += arr.size(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.size())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + const auto valuesSlice = Slice(index, index + values.size()); + auto result = NdArray(1, arr.size() + values.size()); + result.put(valuesSlice, values); + + NdArray mask(result.shape()); + mask.fill(true); + mask.put(valuesSlice, false); + result.putMask(mask, arr.flatten()); + + return result; + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before + /// @param value: value to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const dtype& value, Axis axis) + { + const NdArray values = { value }; + return insert(arr, index, values, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param index: index to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, int32 index, const NdArray& values, Axis axis) + { + switch (axis) + { + case Axis::NONE: + { + return insert(arr, index, values); + } + case Axis::ROW: + { + if (!(values.size() == arr.numCols() || values.isscalar() || values.numCols() == arr.numCols())) + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + if (index < 0) + { + index += arr.numRows(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.numRows())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + auto result = NdArray(); + int32 valuesSize{}; + if (values.size() == arr.numCols() || values.isscalar()) + { + result.resizeFast(arr.numRows() + 1, arr.numCols()); + valuesSize = 1; + } + else if (values.numCols() == arr.numCols()) + { + result.resizeFast(arr.numRows() + values.numRows(), arr.numCols()); + valuesSize = values.numRows(); + } + + auto mask = ones_like(result); + mask.put(Slice(index, index + valuesSize), mask.cSlice(), false); + + result.putMask(mask, arr); + result.putMask(!mask, values); + + return result; + } + case Axis::COL: + { + if (!(values.size() == arr.numRows() || values.isscalar() || values.numRows() == arr.numRows())) + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + if (index < 0) + { + index += arr.numCols(); + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + else if (index > static_cast(arr.numCols())) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + auto result = NdArray(); + int32 valuesSize{}; + if (values.size() == arr.numRows() || values.isscalar()) + { + result.resizeFast(arr.numRows(), arr.numCols() + 1); + valuesSize = 1; + } + else if (values.numRows() == arr.numRows()) + { + result.resizeFast(arr.numRows(), arr.numCols() + values.numCols()); + valuesSize = values.numCols(); + } + + auto mask = ones_like(result); + mask.put(mask.rSlice(), Slice(index, index + valuesSize), false); + + result.putMask(mask, arr); + result.putMask(!mask, values); + + return result; + } + default: + { + // get rid of compiler warning + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param indices: indices to insert the values before + /// @param value: value to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template = 0> + NdArray insert(const NdArray& arr, const Indices& indices, const dtype& value, Axis axis = Axis::NONE) + { + const NdArray values = { value }; + return insert(arr, indices, values, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param slice: slice to insert the values before + /// @param value: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, Slice slice, const dtype& value, Axis axis = Axis::NONE) + { + auto sliceIndices = slice.toIndices(arr.dimSize(axis)); + return insert(arr, NdArray(sliceIndices.data(), sliceIndices.size(), false), value, axis); + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param indices: indices to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template = 0> + NdArray + insert(const NdArray& arr, const Indices& indices, const NdArray& values, Axis axis = Axis::NONE) + { + const auto isScalarValue = values.isscalar(); + + switch (axis) + { + case Axis::NONE: + { + if (!isScalarValue && indices.size() != values.size()) + { + THROW_INVALID_ARGUMENT_ERROR("could not broadcast values into indices"); + } + + const auto arrSize = static_cast(arr.size()); + + std::vector> indexValues(indices.size()); + if (isScalarValue) + { + const auto value = values.front(); + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrSize, value](auto index) -> std::pair + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrSize; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrSize) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), value); + }); + } + else + { + stl_algorithms::transform(indices.begin(), + indices.end(), + values.begin(), + indexValues.begin(), + [arrSize](auto index, const auto& value) -> std::pair + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrSize; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrSize) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), value); + }); + } + + stl_algorithms::sort(indexValues.begin(), + indexValues.end(), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first < indexValue2.first; }); + auto indexValuesUnique = std::vector{}; + std::unique_copy(indexValues.begin(), + indexValues.end(), + std::back_inserter(indexValuesUnique), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first == indexValue2.first; }); + + auto result = NdArray(1, arr.size() + indexValuesUnique.size()); + + auto mask = ones_like(result); + int32 counter = 0; + std::for_each(indexValuesUnique.begin(), + indexValuesUnique.end(), + [&counter, &mask](auto& indexValue) noexcept -> void + { mask[indexValue.first + counter++] = false; }); + + result.putMask(mask, arr); + + auto valuesSorted = [&indexValuesUnique] + { + std::vector values_; + values_.reserve(indexValuesUnique.size()); + std::transform(indexValuesUnique.begin(), + indexValuesUnique.end(), + std::back_inserter(values_), + [](const auto& indexValue) { return indexValue.second; }); + return values_; + }(); + + result.putMask(!mask, NdArray(valuesSorted.data(), valuesSorted.size(), false)); + + return result; + } + case Axis::ROW: + { + const auto arrNumRows = static_cast(arr.numRows()); + + std::vector>> indexValues(indices.size()); + if (values.isscalar()) + { + const auto value = values.front(); + auto valueRow = NdArray(1, arr.numCols()); + valueRow.fill(value); + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &valueRow](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), valueRow); + }); + } + else if (values.size() == arr.numCols()) + { + stl_algorithms::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &values](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), values); + }); + } + else if (values.numCols() == arr.numCols() && values.numRows() == indices.size()) + { + int32 counter = 0; + std::transform(indices.begin(), + indices.end(), + indexValues.begin(), + [arrNumRows, &values, &counter](auto index) -> std::pair> + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index += arrNumRows; + } + // still + if (index < 0) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + } + if (static_cast(index) > arrNumRows) + { + THROW_INVALID_ARGUMENT_ERROR("index out of range"); + } + + return std::make_pair(static_cast(index), + values(counter++, values.cSlice())); + }); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input values shape cannot be broadcast to input array dimensions"); + } + + stl_algorithms::sort(indexValues.begin(), + indexValues.end(), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first < indexValue2.first; }); + auto indexValuesUnique = std::vector{}; + std::unique_copy(indexValues.begin(), + indexValues.end(), + std::back_inserter(indexValuesUnique), + [](const auto& indexValue1, const auto& indexValue2) noexcept -> bool + { return indexValue1.first == indexValue2.first; }); + + auto result = NdArray(arrNumRows + indexValuesUnique.size(), arr.numCols()); + + auto mask = ones_like(result); + int32 counter = 0; + std::for_each(indexValuesUnique.begin(), + indexValuesUnique.end(), + [&counter, &mask](auto& indexValue) noexcept -> void + { mask.put(indexValue.first + counter++, mask.cSlice(), false); }); + + result.putMask(mask, arr); + + counter = 0; + for (const auto& [index, values_] : indexValuesUnique) + { + result.put(index + counter++, result.cSlice(), values_); + } + + return result; + } + case Axis::COL: + { + return insert(arr.transpose(), indices, values.transpose(), Axis::ROW).transpose(); + } + default: + { + // get rid of compiler warning + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Insert values along the given axis before the given indices. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.insert.html + /// + /// @param arr: input array. + /// @param slice: slice to insert the values before + /// @param values: values to insert + /// @param axis: axis along which to insert values + /// @return index: index before which values are inserted. + /// + template + NdArray insert(const NdArray& arr, Slice slice, const NdArray& values, Axis axis = Axis::NONE) + { + auto sliceIndices = slice.toIndices(arr.dimSize(axis)); + return insert(arr, NdArray(sliceIndices.data(), sliceIndices.size(), false), values, axis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/interp.hpp b/runexamples/cpp/include/NumCpp/Functions/interp.hpp new file mode 100644 index 0000000..72afb18 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/interp.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/interp.hpp" + +namespace nc +{ + //============================================================================ + /// Returns the linear interpolation between two points + /// + /// @param inValue1 + /// @param inValue2 + /// @param inPercent + /// + /// @return linear interpolated point + /// + template + constexpr double interp(dtype inValue1, dtype inValue2, double inPercent) noexcept + { + return utils::interp(inValue1, inValue2, inPercent); + } + + //============================================================================ + // Method Description: + /// One-dimensional linear interpolation. + /// + /// Returns the one - dimensional piecewise linear interpolant + /// to a function with given values at discrete data - points. + /// If input arrays are not one dimensional they will be + /// internally flattened. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.interp.html + /// + /// @param inX: The x-coordinates at which to evaluate the interpolated values. + /// @param inXp: The x-coordinates of the data points, must be increasing. Otherwise, xp is internally sorted. + /// @param inFp: The y-coordinates of the data points, same length as inXp. + /// + /// @return NdArray + /// + template + NdArray interp(const NdArray& inX, const NdArray& inXp, const NdArray& inFp) + { + // do some error checking first + if (inXp.size() != inFp.size()) + { + THROW_INVALID_ARGUMENT_ERROR("inXp and inFp need to be the same size()."); + } + + if (inX.min().item() < inXp.min().item() || inX.max().item() > inXp.max().item()) + { + THROW_INVALID_ARGUMENT_ERROR("endpoints of inX should be contained within inXp."); + } + + // sort the input inXp and inFp data + NdArray sortedXpIdxs = argsort(inXp); + NdArray sortedXp(1, inFp.size()); + NdArray sortedFp(1, inFp.size()); + uint32 counter = 0; + for (auto sortedXpIdx : sortedXpIdxs) + { + sortedXp[counter] = inXp[sortedXpIdx]; + sortedFp[counter++] = inFp[sortedXpIdx]; + } + + // get the sorted input inX array indices + NdArray sortedXIdxs = argsort(inX); + + NdArray returnArray(1, inX.size()); + + uint32 currXpIdx = 0; + uint32 currXidx = 0; + while (currXidx < inX.size()) + { + const auto sortedXIdx = sortedXIdxs[currXidx]; + const auto x = inX[sortedXIdx]; + const auto xPLow = sortedXp[currXpIdx]; + const auto xPHigh = sortedXp[currXpIdx + 1]; + const auto fPLow = sortedFp[currXpIdx]; + const auto fPHigh = sortedFp[currXpIdx + 1]; + + if (xPLow <= x && x <= xPHigh) + { + const double percent = static_cast(x - xPLow) / static_cast(xPHigh - xPLow); + returnArray[sortedXIdx] = utils::interp(fPLow, fPHigh, percent); + ++currXidx; + } + else + { + ++currXpIdx; + } + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/intersect1d.hpp b/runexamples/cpp/include/NumCpp/Functions/intersect1d.hpp new file mode 100644 index 0000000..b1a0f36 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/intersect1d.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the intersection of two arrays. + /// + /// Return the sorted, unique values that are in both of the input arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.intersect1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray intersect1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::vector res(inArray1.size() + inArray2.size()); + const std::set in1(inArray1.cbegin(), inArray1.cend()); + const std::set in2(inArray2.cbegin(), inArray2.cend()); + + const auto iter = stl_algorithms::set_intersection(in1.begin(), in1.end(), in2.begin(), in2.end(), res.begin()); + res.resize(iter - res.begin()); + return NdArray(res); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/invert.hpp b/runexamples/cpp/include/NumCpp/Functions/invert.hpp new file mode 100644 index 0000000..c438481 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/invert.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute bit-wise inversion, or bit-wise NOT, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.invert.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray invert(const NdArray& inArray) + { + return ~inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/isclose.hpp b/runexamples/cpp/include/NumCpp/Functions/isclose.hpp new file mode 100644 index 0000000..d62f75e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/isclose.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a boolean array where two arrays are element-wise + /// equal within a tolerance. + /// + /// For finite values, isclose uses the following equation to test whether two floating point values are equivalent. + /// absolute(a - b) <= (atol + rtol * absolute(b)) + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isclose.html + /// + /// @param inArray1 + /// @param inArray2 + /// @param inRtol: relative tolerance (default 1e-5) + /// @param inAtol: absolute tolerance (default 1e-9) + /// + /// @return NdArray + /// + template + NdArray isclose(const NdArray& inArray1, + const NdArray& inArray2, + double inRtol = 1e-05, + double inAtol = 1e-08) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [inRtol, inAtol](dtype inValueA, dtype inValueB) noexcept -> bool + { return std::abs(inValueA - inValueB) <= (inAtol + inRtol * std::abs(inValueB)); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/isinf.hpp b/runexamples/cpp/include/NumCpp/Functions/isinf.hpp new file mode 100644 index 0000000..d963c96 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/isinf.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isinf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isinf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isinf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isinf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isinf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/isnan.hpp b/runexamples/cpp/include/NumCpp/Functions/isnan.hpp new file mode 100644 index 0000000..bcc6ec4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/isnan.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for NaN and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isnan.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isnan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (DtypeInfo::isInteger()) + { + return false; + } + + return std::isnan(static_cast(inValue)); // static_cast is needed for compiler error + } + + //============================================================================ + // Method Description: + /// Test element-wise for NaN and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isnan.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isnan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isnan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/isneginf.hpp b/runexamples/cpp/include/NumCpp/Functions/isneginf.hpp new file mode 100644 index 0000000..c91b28c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/isneginf.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for negative inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isneginf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isneginf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return inValue < 0 && std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for negative inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isneginf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isneginf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isneginf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/isposinf.hpp b/runexamples/cpp/include/NumCpp/Functions/isposinf.hpp new file mode 100644 index 0000000..09030cd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/isposinf.hpp @@ -0,0 +1,75 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test for positive inf and return result as a boolean. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isposinf.html + /// + /// @param inValue + /// + /// @return bool + /// + template + bool isposinf(dtype inValue) noexcept + { + STATIC_ASSERT_FLOAT(dtype); + + return inValue > 0 && std::isinf(inValue); + } + + //============================================================================ + // Method Description: + /// Test element-wise for positive inf and return result as a boolean array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.isposinf.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray isposinf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return isposinf(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/kaiser.hpp b/runexamples/cpp/include/NumCpp/Functions/kaiser.hpp new file mode 100644 index 0000000..6ceb6c5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/kaiser.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/bessel_in.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// The Kaiser window is a taper formed by using a Bessel function. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.kaiser.html + /// + /// @param m: Number of points in the output window. If zero or less, an empty array is returned. + /// @param beta: shape parameter for the window + /// @return NdArray + /// + inline NdArray kaiser(int32 m, double beta) + { + if (m < 1) + { + return {}; + } + + const auto mDouble = static_cast(m); + const auto mMinus1 = mDouble - 1.; + const auto mMinus1Over2 = mMinus1 / 2.; + const auto mMinus1Squared = utils::sqr(mMinus1); + const auto i0Beta = special::bessel_in(0, beta); + + NdArray result(1, m); + int32 i = 0; + for (auto n : linspace(-mMinus1Over2, mMinus1Over2, m, true)) + { + auto value = beta * std::sqrt(1. - (4. * utils::sqr(n)) / mMinus1Squared); + result[i++] = special::bessel_in(0, value) / i0Beta; + } + + return result; + } +} // namespace nc + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Functions/lcm.hpp b/runexamples/cpp/include/NumCpp/Functions/lcm.hpp new file mode 100644 index 0000000..aca7515 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/lcm.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/integer/common_factor_rt.hpp" +#endif + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the least common multiple of |x1| and |x2|. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.lcm.html + /// + /// @param inValue1 + /// @param inValue2 + /// @return dtype + /// + template + dtype lcm(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_INTEGER(dtype); + +#ifdef __cpp_lib_gcd_lcm + return std::lcm(inValue1, inValue2); +#else + return boost::integer::lcm(inValue1, inValue2); +#endif + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Returns the least common multiple of the values of the input array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.lcm.html + /// + /// @param inArray + /// @return NdArray + /// + template + dtype lcm(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + + return boost::integer::lcm_range(inArray.cbegin(), inArray.cend()).first; + } +#endif // #ifndef NUMCPP_NO_USE_BOOST +} // namespace nc + +#endif // #if defined(__cpp_lib_gcd_lcm) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Functions/ldexp.hpp b/runexamples/cpp/include/NumCpp/Functions/ldexp.hpp new file mode 100644 index 0000000..9d61697 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ldexp.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns x1 * 2^x2. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ldexp.html + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return value + /// + template + dtype ldexp(dtype inValue1, uint8 inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::ldexp(static_cast(inValue1), inValue2)); + } + + //============================================================================ + // Method Description: + /// Returns x1 * 2^x2, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ldexp.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray ldexp(const NdArray& inArray1, const NdArray& inArray2) + { + if (inArray1.shape() != inArray2.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform(inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [](dtype inValue1, uint8 inValue2) noexcept -> dtype + { return ldexp(inValue1, inValue2); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/left_shift.hpp b/runexamples/cpp/include/NumCpp/Functions/left_shift.hpp new file mode 100644 index 0000000..bb91fd6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/left_shift.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Shift the bits of an integer to the left. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.left_shift.html + /// + /// @param inArray + /// @param inNumBits + /// + /// @return NdArray + /// + template + NdArray left_shift(const NdArray& inArray, uint8 inNumBits) + { + return inArray << inNumBits; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/less.hpp b/runexamples/cpp/include/NumCpp/Functions/less.hpp new file mode 100644 index 0000000..38d7ea8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/less.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 < x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.less.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray less(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 < inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/less_equal.hpp b/runexamples/cpp/include/NumCpp/Functions/less_equal.hpp new file mode 100644 index 0000000..a3f1920 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/less_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truth value of (x1 <= x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.less_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray less_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 <= inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/linspace.hpp b/runexamples/cpp/include/NumCpp/Functions/linspace.hpp new file mode 100644 index 0000000..563ca5b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/linspace.hpp @@ -0,0 +1,121 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return evenly spaced numbers over a specified interval. + /// + /// Returns num evenly spaced samples, calculated over the + /// interval[start, stop]. + /// + /// The endpoint of the interval can optionally be excluded. + /// + /// Mostly only usefull if called with a floating point type + /// for the template argument. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.linspace.html + /// + /// @param inStart + /// @param inStop + /// @param inNum: number of points (default = 50) + /// @param endPoint: include endPoint (default = true) + /// + /// @return NdArray + /// + template + NdArray linspace(dtype inStart, dtype inStop, uint32 inNum = 50, bool endPoint = true) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inNum == 0) + { + return NdArray(0); + } + + if (inNum == 1) + { + NdArray returnArray = { inStart }; + return returnArray; + } + + if (inStop <= inStart) + { + THROW_INVALID_ARGUMENT_ERROR("stop value must be greater than the start value."); + } + + if (endPoint) + { + if (inNum == 2) + { + NdArray returnArray = { inStart, inStop }; + return returnArray; + } + + NdArray returnArray(1, inNum); + returnArray.front() = inStart; + returnArray.back() = inStop; + + dtype step = (inStop - inStart) / static_cast(inNum - 1); + + for (uint32 i = 1; i < inNum - 1; ++i) + { + returnArray[i] = inStart + static_cast(i) * step; + } + + return returnArray; + } + + if (inNum == 2) + { + dtype step = (inStop - inStart) / (inNum); + NdArray returnArray = { inStart, inStart + step }; + return returnArray; + } + + NdArray returnArray(1, inNum); + returnArray.front() = inStart; + + dtype step = (inStop - inStart) / static_cast(inNum); + + for (uint32 i = 1; i < inNum; ++i) + { + returnArray[i] = inStart + static_cast(i) * step; + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/load.hpp b/runexamples/cpp/include/NumCpp/Functions/load.hpp new file mode 100644 index 0000000..5703778 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/load.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/fromfile.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// loads a .bin file from the dump() method into an NdArray + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.load.html + /// + /// @param inFilename + /// + /// @return NdArray + /// + template + NdArray load(const std::string& inFilename) + { + return fromfile(inFilename); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/log.hpp b/runexamples/cpp/include/NumCpp/Functions/log.hpp new file mode 100644 index 0000000..8017158 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/log.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Natural logarithm. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(inValue); + } + + //============================================================================ + // Method Description: + /// Natural logarithm, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/log10.hpp b/runexamples/cpp/include/NumCpp/Functions/log10.hpp new file mode 100644 index 0000000..2c1afce --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/log10.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the base 10 logarithm of the input array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log10.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log10(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log10(inValue); + } + + //============================================================================ + // Method Description: + /// Return the base 10 logarithm of the input array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log10.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log10(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log10(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/log1p.hpp b/runexamples/cpp/include/NumCpp/Functions/log1p.hpp new file mode 100644 index 0000000..cf044eb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/log1p.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the natural logarithm of one plus the input array. + /// + /// Calculates log(1 + x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log1p.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log1p(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log1p(inValue); + } + + //============================================================================ + // Method Description: + /// Return the natural logarithm of one plus the input array, element-wise. + /// + /// Calculates log(1 + x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log1p.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log1p(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log1p(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/log2.hpp b/runexamples/cpp/include/NumCpp/Functions/log2.hpp new file mode 100644 index 0000000..f4aabc3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/log2.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Base-2 logarithm of x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log2.html + /// + /// @param inValue + /// + /// @return value + /// + template + auto log2(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log2(inValue); + } + + //============================================================================ + // Method Description: + /// Base-2 logarithm of x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.log2.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto log2(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return log2(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logaddexp.hpp b/runexamples/cpp/include/NumCpp/Functions/logaddexp.hpp new file mode 100644 index 0000000..f59e9b1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logaddexp.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return value + /// + template + auto logaddexp(dtype x1, dtype x2) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(std::exp(x1) + std::exp(x2)); + } + + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs, element-wise. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return NdArray + /// + template + auto logaddexp(const NdArray& x1, const NdArray& x2) + { + if (x1.size() != x2.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'x1', and 'x2' must be the same size"); + } + + NdArray returnArray(x1.shape()); + stl_algorithms::transform( + x1.cbegin(), + x1.cend(), + x2.cbegin(), + returnArray.begin(), + [](dtype inX1, dtype inX2) noexcept -> auto{ return logaddexp(inX1, inX2); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logaddexp2.hpp b/runexamples/cpp/include/NumCpp/Functions/logaddexp2.hpp new file mode 100644 index 0000000..1c5c837 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logaddexp2.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return value + /// + template + auto logaddexp2(dtype x1, dtype x2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::log2(utils::powerf(2, x1) + utils::powerf(2, x2)); + } + + //============================================================================ + // Method Description: + /// Logarithm of the sum of exponentiations of the inputs, element-wise. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html + /// + /// @param x1 + /// @param x2 + /// + /// @return NdArray + /// + template + auto logaddexp2(const NdArray& x1, const NdArray& x2) + { + if (x1.size() != x2.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Inputs 'x1', and 'x2' must be the same size"); + } + + NdArray returnArray(x1.shape()); + stl_algorithms::transform( + x1.cbegin(), + x1.cend(), + x2.cbegin(), + returnArray.begin(), + [](dtype inX1, dtype inX2) noexcept -> auto{ return logaddexp2(inX1, inX2); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logb.hpp b/runexamples/cpp/include/NumCpp/Functions/logb.hpp new file mode 100644 index 0000000..d1a2e81 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logb.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Logarithm of an arbitrary base + /// + /// @param inValue + /// @param inBase: the logorithm base + /// + /// @return value + /// + template + auto logb(dtype inValue, dtype inBase) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::log(inValue) / std::log(inBase); + } + + //============================================================================ + // Method Description: + /// Logarithm of an arbitrary base + /// + /// @param inArray + /// @param inBase: the logorithm base + /// + /// @return NdArray + /// + template + auto logb(const NdArray& inArray, dtype inBase) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inBase](dtype inValue) noexcept -> auto{ return logb(inValue, inBase); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logical_and.hpp b/runexamples/cpp/include/NumCpp/Functions/logical_and.hpp new file mode 100644 index 0000000..0d37062 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logical_and.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 AND x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_and.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_and(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 && inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logical_not.hpp b/runexamples/cpp/include/NumCpp/Functions/logical_not.hpp new file mode 100644 index 0000000..566e5f9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logical_not.hpp @@ -0,0 +1,59 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of NOT x element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_not.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray logical_not(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> bool { return utils::essentiallyEqual(inValue, dtype{ 0 }); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logical_or.hpp b/runexamples/cpp/include/NumCpp/Functions/logical_or.hpp new file mode 100644 index 0000000..e9e0fdf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logical_or.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 OR x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_or.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_or(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 || inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logical_xor.hpp b/runexamples/cpp/include/NumCpp/Functions/logical_xor.hpp new file mode 100644 index 0000000..9f44530 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logical_xor.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the truth value of x1 XOR x2 element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.logical_xor.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray logical_xor(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) -> bool { + return !utils::essentiallyEqual(inValue1, dtype{ 0 }) != + !utils::essentiallyEqual(inValue2, dtype{ 0 }); + }); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/logspace.hpp b/runexamples/cpp/include/NumCpp/Functions/logspace.hpp new file mode 100644 index 0000000..5fdcd35 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/logspace.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/linspace.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return numbers spaced evenly on a log scale. + /// + /// This is similar to logspace, but with endpoints specified directly. + /// Each output sample is a constant multiple of the previous. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.logspace.html + /// + /// @param start: the starting value of a sequence + /// @param stop: The final value of the sequence, unless endpoint is False. + /// In that case, num + 1 values are spaced over the interval + /// in log-space, of which all but the last (a sequence of length num) are returned. + /// @param num: Number of samples to generate. Default 50. + /// @param endPoint: If true, stop is the last sample. Otherwise,it is not included. Default is true. + /// @param base: The base of the log space. The step size between the elements in ln(samples) / ln(base) + /// @return NdArray + /// + template + NdArray logspace(dtype start, dtype stop, uint32 num = 50, bool endPoint = true, double base = 10.) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + auto spacedValues = linspace(static_cast(start), static_cast(stop), num, endPoint); + stl_algorithms::for_each(spacedValues.begin(), + spacedValues.end(), + [base](auto& value) -> void { value = utils::powerf(base, value); }); + + return spacedValues; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/matmul.hpp b/runexamples/cpp/include/NumCpp/Functions/matmul.hpp new file mode 100644 index 0000000..2adb4ea --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/matmul.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray matmul(const NdArray& inArray1, const NdArray& inArray2) + { + return dot(inArray1, inArray2); + } + + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray> matmul(const NdArray& inArray1, const NdArray>& inArray2) + { + return dot(inArray1, inArray2); + } + + //============================================================================ + // Method Description: + /// Matrix product of two arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.matmul.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray> matmul(const NdArray>& inArray1, const NdArray& inArray2) + { + return dot(inArray1, inArray2); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/max.hpp b/runexamples/cpp/include/NumCpp/Functions/max.hpp new file mode 100644 index 0000000..4880e08 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/max.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray max(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.max(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/maximum.hpp b/runexamples/cpp/include/NumCpp/Functions/maximum.hpp new file mode 100644 index 0000000..b6c90b7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/maximum.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray maximum(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](const dtype& lhs, const dtype& rhs) noexcept -> bool { return lhs < rhs; }; + return broadcast::broadcaster(inArray1, + inArray2, + [&comparitor](const dtype& value1, const dtype& value2) + { return std::max(value1, value2, comparitor); }); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray maximum(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return maximum(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise maximum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.maximum.html + /// + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray maximum(const dtype& inScalar, const NdArray& inArray) + { + return maximum(inArray, inScalar); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/mean.hpp b/runexamples/cpp/include/NumCpp/Functions/mean.hpp new file mode 100644 index 0000000..a2e81fd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/mean.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //=========================================================================== + // Method Description: + /// Compute the mean along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray mean(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = std::accumulate(inArray.cbegin(), inArray.cend(), 0.); + NdArray returnArray = { sum /= static_cast(inArray.size()) }; + + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + auto sum = std::accumulate(inArray.cbegin(row), inArray.cend(row), 0.); + returnArray(0, row) = sum / static_cast(inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + return mean(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; + } + } + } + + //============================================================================ + // Method Description: + /// Compute the mean along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> mean(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = std::accumulate(inArray.cbegin(), inArray.cend(), std::complex(0.)); + NdArray> returnArray = { sum /= std::complex(inArray.size()) }; + + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + auto sum = std::accumulate(inArray.cbegin(row), inArray.cend(row), std::complex(0.)); + returnArray(0, row) = sum / std::complex(inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + NdArray> transposedArray = inArray.transpose(); + NdArray> returnArray(1, transposedArray.numRows()); + for (uint32 row = 0; row < transposedArray.numRows(); ++row) + { + auto sum = std::accumulate(transposedArray.cbegin(row), + transposedArray.cend(row), + std::complex(0.)); + returnArray(0, row) = sum / std::complex(transposedArray.numCols()); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/median.hpp b/runexamples/cpp/include/NumCpp/Functions/median.hpp new file mode 100644 index 0000000..6b66f30 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/median.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the median along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.median.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray median(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.median(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/meshgrid.hpp b/runexamples/cpp/include/NumCpp/Functions/meshgrid.hpp new file mode 100644 index 0000000..8504956 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/meshgrid.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return coordinate matrices from coordinate vectors. + /// Make 2D coordinate arrays for vectorized evaluations of 2D scalar + /// vector fields over 2D grids, given one - dimensional coordinate arrays x1, x2, ..., xn. + /// If input arrays are not one dimensional they will be flattened. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.meshgrid.html + /// + /// @param inICoords + /// @param inJCoords + /// + /// @return std::pair, NdArray >, i and j matrices + /// + template + std::pair, NdArray> meshgrid(const NdArray& inICoords, const NdArray& inJCoords) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const uint32 numRows = inJCoords.size(); + const uint32 numCols = inICoords.size(); + auto returnArrayI = NdArray(numRows, numCols); + auto returnArrayJ = NdArray(numRows, numCols); + + // first the I array + for (uint32 row = 0; row < numRows; ++row) + { + for (uint32 col = 0; col < numCols; ++col) + { + returnArrayI(row, col) = inICoords[col]; + } + } + + // then the I array + for (uint32 col = 0; col < numCols; ++col) + { + for (uint32 row = 0; row < numRows; ++row) + { + returnArrayJ(row, col) = inJCoords[row]; + } + } + + return std::make_pair(returnArrayI, returnArrayJ); + } + + //============================================================================ + // Method Description: + /// Return coordinate matrices from coordinate vectors. + /// Make 2D coordinate arrays for vectorized evaluations of 2D scalar + /// vector fields over 2D grids, given one - dimensional coordinate arrays x1, x2, ..., xn. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.meshgrid.html + /// + /// @param inSlice1 + /// @param inSlice2 + /// + /// @return std::pair, NdArray >, i and j matrices + /// + template + std::pair, NdArray> meshgrid(const Slice& inSlice1, const Slice& inSlice2) + { + return meshgrid(arange(inSlice1), arange(inSlice2)); + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/min.hpp b/runexamples/cpp/include/NumCpp/Functions/min.hpp new file mode 100644 index 0000000..6e8f500 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/min.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or minimum along an axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray min(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.min(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/minimum.hpp b/runexamples/cpp/include/NumCpp/Functions/minimum.hpp new file mode 100644 index 0000000..7a8fedd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/minimum.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray minimum(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](const dtype& lhs, const dtype& rhs) noexcept -> bool { return lhs < rhs; }; + return broadcast::broadcaster(inArray1, + inArray2, + [&comparitor](const dtype& value1, const dtype& value2) + { return std::min(value1, value2, comparitor); }); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inArray + /// @param inScalar + /// + /// @return NdArray + /// + template + NdArray minimum(const NdArray& inArray, const dtype& inScalar) + { + const NdArray inArray2 = { inScalar }; + return minimum(inArray, inArray2); + } + + //============================================================================ + // Method Description: + /// Element-wise minimum of array elements. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html + /// + /// + /// @param inScalar + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray minimum(const dtype& inScalar, const NdArray& inArray) + { + return minimum(inArray, inScalar); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/mod.hpp b/runexamples/cpp/include/NumCpp/Functions/mod.hpp new file mode 100644 index 0000000..ae3d466 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/mod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.mod.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray mod(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 % inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/multiply.hpp b/runexamples/cpp/include/NumCpp/Functions/multiply.hpp new file mode 100644 index 0000000..129f22d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/multiply.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray multiply(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray multiply(const NdArray& inArray, dtype value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray multiply(dtype value, const NdArray& inArray) + { + return value * inArray; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> multiply(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> multiply(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 * inArray2; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> multiply(const NdArray& inArray, const std::complex& value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> multiply(const std::complex& value, const NdArray& inArray) + { + return value * inArray; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> multiply(const NdArray>& inArray, dtype value) + { + return inArray * value; + } + + //============================================================================ + // Method Description: + /// multiply arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.multiply.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> multiply(dtype value, const NdArray>& inArray) + { + return value * inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nan_to_num.hpp b/runexamples/cpp/include/NumCpp/Functions/nan_to_num.hpp new file mode 100644 index 0000000..218d309 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nan_to_num.hpp @@ -0,0 +1,85 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/isinf.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Replace NaN with zero and infinity with large finite numbers (default behaviour) + /// or with the numbers defined by the user using the nan, posinf and/or neginf keywords. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.nan_to_num.html + /// + /// @param inArray + /// @param nan: value to be used to fill NaN values, default 0 + /// @param posInf: value to be used to fill positive infinity values, default a very large number + /// @param negInf: value to be used to fill negative infinity values, default a very large negative number + /// @return NdArray + /// + template + NdArray nan_to_num(NdArray inArray, + dtype nan = static_cast(0.), + dtype posInf = DtypeInfo::max(), + dtype negInf = DtypeInfo::min()) + { + STATIC_ASSERT_FLOAT(dtype); + + stl_algorithms::for_each(inArray.begin(), + inArray.end(), + [nan, posInf, negInf](dtype& value) + { + if (isnan(value)) + { + value = nan; + } + else if (isinf(value)) + { + if (value > static_cast(0.)) + { + value = posInf; + } + else + { + value = negInf; + } + } + }); + + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanargmax.hpp b/runexamples/cpp/include/NumCpp/Functions/nanargmax.hpp new file mode 100644 index 0000000..a6a9c41 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanargmax.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the maximum values along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanargmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nanargmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::min(); + }; + }); + + return argmax(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanargmin.hpp b/runexamples/cpp/include/NumCpp/Functions/nanargmin.hpp new file mode 100644 index 0000000..038807f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanargmin.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the indices of the minimum values along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanargmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nanargmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::max(); + }; + }); + + return argmin(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nancumprod.hpp b/runexamples/cpp/include/NumCpp/Functions/nancumprod.hpp new file mode 100644 index 0000000..64222da --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nancumprod.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/cumprod.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative product of elements along a given axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nancumprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nancumprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = dtype{ 1 }; + }; + }); + + return cumprod(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nancumsum.hpp b/runexamples/cpp/include/NumCpp/Functions/nancumsum.hpp new file mode 100644 index 0000000..40b7b8b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nancumsum.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/cumsum.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along a given axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nancumsum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray nancumsum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = dtype{ 0 }; + }; + }); + + return cumsum(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanmax.hpp b/runexamples/cpp/include/NumCpp/Functions/nanmax.hpp new file mode 100644 index 0000000..ee8aece --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanmax.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the maximum of an array or maximum along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmax.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::min(); + }; + }); + + return max(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanmean.hpp b/runexamples/cpp/include/NumCpp/Functions/nanmean.hpp new file mode 100644 index 0000000..3beb22a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanmean.hpp @@ -0,0 +1,118 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the mean along the specified axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmean.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmean(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto sum = static_cast(std::accumulate(inArray.cbegin(), + inArray.cend(), + 0., + [](dtype inValue1, dtype inValue2) -> dtype { + return std::isnan(inValue2) ? inValue1 + : inValue1 + inValue2; + })); + + const auto numberNonNan = + static_cast(std::accumulate(inArray.cbegin(), + inArray.cend(), + 0., + [](dtype inValue1, dtype inValue2) -> dtype + { return std::isnan(inValue2) ? inValue1 : inValue1 + 1; })); + + NdArray returnArray = { sum /= numberNonNan }; + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + auto sum = static_cast( + std::accumulate(inArray.cbegin(row), + inArray.cend(row), + 0., + [](dtype inValue1, dtype inValue2) -> dtype + { return std::isnan(inValue2) ? inValue1 : inValue1 + inValue2; })); + + auto numberNonNan = + static_cast(std::accumulate(inArray.cbegin(row), + inArray.cend(row), + 0., + [](dtype inValue1, dtype inValue2) -> dtype { + return std::isnan(inValue2) ? inValue1 : inValue1 + 1; + })); + + returnArray(0, row) = sum / numberNonNan; + } + + return returnArray; + } + case Axis::ROW: + { + return nanmean(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanmedian.hpp b/runexamples/cpp/include/NumCpp/Functions/nanmedian.hpp new file mode 100644 index 0000000..b028eb5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanmedian.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/max.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the median along the specified axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmedian.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmedian(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector values; + for (auto value : inArray) + { + if (!std::isnan(value)) + { + values.push_back(value); + } + } + + const uint32 middle = static_cast(values.size()) / 2; + stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end()); + NdArray returnArray = { values[middle] }; + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + std::vector values; + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (!std::isnan(inArray(row, col))) + { + values.push_back(inArray(row, col)); + } + } + + const uint32 middle = static_cast(values.size()) / 2; + stl_algorithms::nth_element(values.begin(), values.begin() + middle, values.end()); + returnArray(0, row) = values[middle]; + } + + return returnArray; + } + case Axis::ROW: + { + return nanmedian(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanmin.hpp b/runexamples/cpp/include/NumCpp/Functions/nanmin.hpp new file mode 100644 index 0000000..78328b3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanmin.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/min.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the minimum of an array or maximum along an axis ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanmin.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanmin(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = DtypeInfo::max(); + }; + }); + + return min(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanpercentile.hpp b/runexamples/cpp/include/NumCpp/Functions/nanpercentile.hpp new file mode 100644 index 0000000..65ac757 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanpercentile.hpp @@ -0,0 +1,133 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/isnan.hpp" +#include "NumCpp/Functions/percentile.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the qth percentile of the data along the specified axis, while ignoring nan values. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanpercentile.html + /// + /// @param inArray + /// @param inPercentile + /// @param inAxis (Optional, default NONE) + /// @param inInterpMethod (default linear) choices = ['linear','lower','higher','nearest','midpoint'] + /// @return NdArray + /// + template + NdArray nanpercentile(const NdArray& inArray, + double inPercentile, + Axis inAxis = Axis::NONE, + const std::string& inInterpMethod = "linear") + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector arrayCopy; + arrayCopy.reserve(inArray.size()); + for (auto value : inArray) + { + if (!isnan(value)) + { + arrayCopy.push_back(static_cast(value)); + } + } + + if (arrayCopy.empty()) + { + NdArray returnArray = { constants::nan }; + return returnArray; + } + + return percentile(NdArray(arrayCopy.data(), + static_cast::size_type>(arrayCopy.size()), + false), + inPercentile, + Axis::NONE, + inInterpMethod); + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + NdArray outValue = nanpercentile(NdArray(&inArray.front(row), inShape.cols), + inPercentile, + Axis::NONE, + inInterpMethod); + + if (outValue.isscalar()) + { + returnArray[row] = outValue.item(); + } + else + { + returnArray[row] = constants::nan; + } + } + + return returnArray; + } + case Axis::ROW: + { + return nanpercentile(inArray.transpose(), inPercentile, Axis::COL, inInterpMethod); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanprod.hpp b/runexamples/cpp/include/NumCpp/Functions/nanprod.hpp new file mode 100644 index 0000000..b69170e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanprod.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/prod.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the product of array elements over a given axis treating Not a Numbers (NaNs) as ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanprod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanprod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = static_cast(1); + }; + }); + + return prod(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nans.hpp b/runexamples/cpp/include/NumCpp/Functions/nans.hpp new file mode 100644 index 0000000..30272e5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nans.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inSquareSize + /// @return NdArray + /// + inline NdArray nans(uint32 inSquareSize) + { + return full(inSquareSize, constants::nan); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + inline NdArray nans(uint32 inNumRows, uint32 inNumCols) + { + return full(inNumRows, inNumCols, constants::nan); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// Only really works for dtype = float/double + /// + /// @param inShape + /// @return NdArray + /// + inline NdArray nans(const Shape& inShape) + { + return full(inShape, constants::nan); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nans_like.hpp b/runexamples/cpp/include/NumCpp/Functions/nans_like.hpp new file mode 100644 index 0000000..8a21936 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nans_like.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with nans. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray nans_like(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + returnArray.nans(); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanstdev.hpp b/runexamples/cpp/include/NumCpp/Functions/nanstdev.hpp new file mode 100644 index 0000000..83c38a9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanstdev.hpp @@ -0,0 +1,114 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/nanmean.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis, while ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanstd.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanstdev(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + double meanValue = nanmean(inArray, inAxis).item(); + double sum = 0; + double counter = 0; + for (auto value : inArray) + { + if (std::isnan(value)) + { + continue; + } + + sum += utils::sqr(static_cast(value) - meanValue); + ++counter; + } + NdArray returnArray = { std::sqrt(sum / counter) }; + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + NdArray meanValue = nanmean(inArray, inAxis); + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + double sum = 0; + double counter = 0; + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (std::isnan(inArray(row, col))) + { + continue; + } + + sum += utils::sqr(static_cast(inArray(row, col)) - meanValue[row]); + ++counter; + } + returnArray(0, row) = std::sqrt(sum / counter); + } + + return returnArray; + } + case Axis::ROW: + { + return nanstdev(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nansum.hpp b/runexamples/cpp/include/NumCpp/Functions/nansum.hpp new file mode 100644 index 0000000..b8e7a5a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nansum.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/sum.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nansum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nansum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray arrayCopy(inArray); + stl_algorithms::for_each(arrayCopy.begin(), + arrayCopy.end(), + [](dtype& value) noexcept -> void + { + if (std::isnan(value)) + { + value = static_cast(0); + }; + }); + + return sum(arrayCopy, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nanvar.hpp b/runexamples/cpp/include/NumCpp/Functions/nanvar.hpp new file mode 100644 index 0000000..e3977a0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nanvar.hpp @@ -0,0 +1,56 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/nanstdev.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis, while ignoring NaNs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nanvar.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray nanvar(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_FLOAT(dtype); + + return square(nanstdev(inArray, inAxis)); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nbytes.hpp b/runexamples/cpp/include/NumCpp/Functions/nbytes.hpp new file mode 100644 index 0000000..e04e741 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nbytes.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the number of bytes held by the array + /// + /// @param inArray + /// @return number of bytes + /// + template + uint64 nbytes(const NdArray& inArray) noexcept + { + return inArray.nbytes(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/negative.hpp b/runexamples/cpp/include/NumCpp/Functions/negative.hpp new file mode 100644 index 0000000..ac6c506 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/negative.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Numerical negative, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.negative.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray negative(const NdArray& inArray) + { + return -inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/newbyteorder.hpp b/runexamples/cpp/include/NumCpp/Functions/newbyteorder.hpp new file mode 100644 index 0000000..ba6e2d8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/newbyteorder.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types, + /// floating point types will not compile and you will + /// be confused as to why... + /// + /// + /// @param inValue + /// @param inEndianess + /// + /// @return inValue + /// + template + dtype newbyteorder(dtype inValue, Endian inEndianess) + { + NdArray valueArray = { inValue }; + return valueArray.newbyteorder(inEndianess).item(); + } + + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types, + /// floating point types will not compile and you will + /// be confused as to why... + /// + /// + /// @param inArray + /// @param inEndianess + /// + /// @return NdArray + /// + template + NdArray newbyteorder(const NdArray& inArray, Endian inEndianess) + { + return inArray.newbyteorder(inEndianess); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/none.hpp b/runexamples/cpp/include/NumCpp/Functions/none.hpp new file mode 100644 index 0000000..5a3835e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/none.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Test whether no array elements along a given axis evaluate to True. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.all.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + template + NdArray none(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.none(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nonzero.hpp b/runexamples/cpp/include/NumCpp/Functions/nonzero.hpp new file mode 100644 index 0000000..27cbaff --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nonzero.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the indices of the flattened array of the + /// elements that are non-zero. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.nonzero.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + std::pair, NdArray> nonzero(const NdArray& inArray) + { + return inArray.nonzero(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/norm.hpp b/runexamples/cpp/include/NumCpp/Functions/norm.hpp new file mode 100644 index 0000000..451f369 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/norm.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray norm(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double sumOfSquares = 0.; + const auto function = [&sumOfSquares](dtype value) -> void + { sumOfSquares += utils::sqr(static_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray returnArray = { std::sqrt(sumOfSquares) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + sumOfSquares = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(sumOfSquares); + } + + return returnArray; + } + case Axis::ROW: + { + return norm(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Matrix or vector norm. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> norm(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex sumOfSquares(0., 0.); + const auto function = [&sumOfSquares](const std::complex& value) -> void + { sumOfSquares += utils::sqr(complex_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray> returnArray = { std::sqrt(sumOfSquares) }; + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + sumOfSquares = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(sumOfSquares); + } + + return returnArray; + } + case Axis::ROW: + { + NdArray> transposedArray = inArray.transpose(); + NdArray> returnArray(1, transposedArray.numRows()); + for (uint32 row = 0; row < transposedArray.numRows(); ++row) + { + sumOfSquares = std::complex(0., 0.); + std::for_each(transposedArray.cbegin(row), transposedArray.cend(row), function); + returnArray(0, row) = std::sqrt(sumOfSquares); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/not_equal.hpp b/runexamples/cpp/include/NumCpp/Functions/not_equal.hpp new file mode 100644 index 0000000..cfa71de --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/not_equal.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return (x1 != x2) element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.not_equal.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray not_equal(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 != inArray2; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/nth_root.hpp b/runexamples/cpp/include/NumCpp/Functions/nth_root.hpp new file mode 100644 index 0000000..aec5504 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/nth_root.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the nth-root of an value. + /// + /// @param inValue + /// @param inRoot + /// @return value + /// + template + double nth_root(dtype1 inValue, dtype2 inRoot) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return utils::powerf(static_cast(inValue), 1. / static_cast(inRoot)); + } + + //============================================================================ + // Method Description: + /// Return the nth-root of an array. + /// + /// @param inArray + /// @param inRoot + /// @return NdArray + /// + template + NdArray nth_root(const NdArray& inArray, dtype2 inRoot) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inRoot](dtype1 inValue) noexcept -> double { return nth_root(inValue, inRoot); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/ones.hpp b/runexamples/cpp/include/NumCpp/Functions/ones.hpp new file mode 100644 index 0000000..2632438 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ones.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inSquareSize + /// @return NdArray + /// + template + NdArray ones(uint32 inSquareSize) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inSquareSize, inSquareSize, dtype{ 1 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray ones(uint32 inNumRows, uint32 inNumCols) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inNumRows, inNumCols, dtype{ 1 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray ones(const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inShape, dtype{ 1 }); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/ones_like.hpp b/runexamples/cpp/include/NumCpp/Functions/ones_like.hpp new file mode 100644 index 0000000..2733699 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ones_like.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with ones. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ones_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray ones_like(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + returnArray.ones(); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/packbits.hpp b/runexamples/cpp/include/NumCpp/Functions/packbits.hpp new file mode 100644 index 0000000..d9cf92f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/packbits.hpp @@ -0,0 +1,193 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Packs the elements of a binary-valued array into bits in a uint8 array. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.packbits.html + /// + /// @param a: An array of integers or booleans whose elements should be packed to bits. + /// @param axis: The dimension over which bit-packing is done. None implies packing the flattened array. + /// @return NdArray + /// + template || std::is_same_v, int> = 0> + NdArray packbitsLittleEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + const auto numFullValues = a.size() / 8; + const auto leftOvers = a.size() % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(1, resultSize); + result.fill(0); + + for (typename NdArray::size_type i = 0; i < numFullValues; ++i) + { + const auto startIdx = i * 8; + for (auto bit = 0; bit < 8; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result[i] |= (value << bit); + } + } + + if (leftOvers != 0) + { + const auto startIdx = numFullValues * 8; + for (std::remove_const_t bit = 0; bit < leftOvers; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result.back() |= (value << bit); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + const auto numFullValues = aShape.cols / 8; + const auto leftOvers = aShape.cols % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(aShape.rows, resultSize); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (typename NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, packbitsLittleEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return packbitsLittleEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Packs the elements of a binary-valued array into bits in a uint8 array. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.packbits.html + /// + /// @param a: An array of integers or booleans whose elements should be packed to bits. + /// @param axis: The dimension over which bit-packing is done. None implies packing the flattened array. + /// @return NdArray + /// + template || std::is_same_v, int> = 0> + NdArray packbitsBigEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + const auto numFullValues = a.size() / 8; + const auto leftOvers = a.size() % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(1, resultSize); + result.fill(0); + + for (typename NdArray::size_type i = 0; i < numFullValues; ++i) + { + const auto startIdx = i * 8; + for (auto bit = 0; bit < 8; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result[i] |= (value << (7 - bit)); + } + } + + if (leftOvers != 0) + { + const auto startIdx = numFullValues * 8; + for (std::remove_const_t bit = 0; bit < leftOvers; ++bit) + { + auto value = static_cast(a[startIdx + bit]); + value = value == 0 ? 0 : 1; + result.back() |= (value << (7 - bit)); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + const auto numFullValues = aShape.cols / 8; + const auto leftOvers = aShape.cols % 8; + const auto resultSize = leftOvers == 0 ? numFullValues : numFullValues + 1; + + NdArray result(aShape.rows, resultSize); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (typename NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, packbitsBigEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return packbitsBigEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/pad.hpp b/runexamples/cpp/include/NumCpp/Functions/pad.hpp new file mode 100644 index 0000000..e509009 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/pad.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Pads an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.pad.html + /// + /// @param inArray + /// @param inPadWidth + /// @param inPadValue + /// @return NdArray + /// + template + NdArray pad(const NdArray& inArray, uint16 inPadWidth, dtype inPadValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + Shape outShape(inShape); + outShape.rows += 2 * inPadWidth; + outShape.cols += 2 * inPadWidth; + + NdArray returnArray(outShape); + returnArray.fill(inPadValue); + returnArray.put(Slice(inPadWidth, inPadWidth + inShape.rows), + Slice(inPadWidth, inPadWidth + inShape.cols), + inArray); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/partition.hpp b/runexamples/cpp/include/NumCpp/Functions/partition.hpp new file mode 100644 index 0000000..4b5bd07 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/partition.hpp @@ -0,0 +1,58 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Rearranges the elements in the array in such a way that + /// value of the element in kth position is in the position it + /// would be in a sorted array. All elements smaller than the kth + /// element are moved before this element and all equal or greater + /// are moved behind it. The ordering of the elements in the two + /// partitions is undefined. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.partition.html + /// + /// @param inArray + /// @param inKth: kth element + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray partition(const NdArray& inArray, uint32 inKth, Axis inAxis = Axis::NONE) + { + NdArray returnArray(inArray); + returnArray.partition(inKth, inAxis); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/percentile.hpp b/runexamples/cpp/include/NumCpp/Functions/percentile.hpp new file mode 100644 index 0000000..3600f40 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/percentile.hpp @@ -0,0 +1,203 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmin.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the qth percentile of the data along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.percentile.html + /// + /// @param inArray + /// @param inPercentile: percentile must be in the range [0, 100] + /// @param inAxis (Optional, default NONE) + /// @param inInterpMethod (Optional) interpolation method + /// linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j. + /// lower : i. + /// higher : j. + /// nearest : i or j, whichever is nearest. + /// midpoint : (i + j) / 2. + /// @return NdArray + /// + template + NdArray percentile(const NdArray& inArray, + double inPercentile, + Axis inAxis = Axis::NONE, + const std::string& inInterpMethod = "linear") + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inPercentile < 0. || inPercentile > 100.) + { + THROW_INVALID_ARGUMENT_ERROR("input percentile value must be of the range [0, 100]."); + } + + if (inArray.isempty()) + { + return {}; + } + else if (inArray.isscalar()) + { + NdArray returnArray = { static_cast(inArray.front()) }; + return returnArray; + } + + if (inInterpMethod != "linear" && inInterpMethod != "lower" && inInterpMethod != "higher" && + inInterpMethod != "nearest" && inInterpMethod != "midpoint") + { + std::string errStr = "input interpolation method is not a vaid option.\n"; + errStr += "\tValid options are 'linear', 'lower', 'higher', 'nearest', 'midpoint'."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + switch (inAxis) + { + case Axis::NONE: + { + NdArray arrayCopy = inArray.template astype(); + stl_algorithms::sort(arrayCopy.begin(), arrayCopy.end()); + + if (utils::essentiallyEqual(inPercentile, 0.)) + { + NdArray returnArray = { arrayCopy.front() }; + return returnArray; + } + if (utils::essentiallyEqual(inPercentile, 100.)) + { + NdArray returnArray = { arrayCopy.back() }; + return returnArray; + } + + const auto i = + static_cast(std::floor(static_cast(inArray.size() - 1) * inPercentile / 100.)); + const auto indexLower = clip(i, 0, inArray.size() - 2); + + if (inInterpMethod == "linear") + { + const double percentI = static_cast(indexLower) / static_cast(inArray.size() - 1); + const double fraction = + (inPercentile / 100. - percentI) / + (static_cast(indexLower + 1) / static_cast(inArray.size() - 1) - percentI); + + NdArray returnArray = { arrayCopy[indexLower] + + (arrayCopy[indexLower + 1] - arrayCopy[indexLower]) * fraction }; + return returnArray; + } + + if (inInterpMethod == "lower") + { + NdArray returnArray = { arrayCopy[indexLower] }; + return returnArray; + } + + if (inInterpMethod == "higher") + { + NdArray returnArray = { arrayCopy[indexLower + 1] }; + return returnArray; + } + + if (inInterpMethod == "nearest") + { + const double percent = inPercentile / 100.; + const double percent1 = static_cast(indexLower) / static_cast(inArray.size() - 1); + const double percent2 = + static_cast(indexLower + 1) / static_cast(inArray.size() - 1); + const double diff1 = percent - percent1; + const double diff2 = percent2 - percent; + + switch (argmin({ diff1, diff2 }).item()) + { + case 0: + { + NdArray returnArray = { arrayCopy[indexLower] }; + return returnArray; + } + case 1: + { + NdArray returnArray = { arrayCopy[indexLower + 1] }; + return returnArray; + } + } + } + + if (inInterpMethod == "midpoint") + { + NdArray returnArray = { (arrayCopy[indexLower] + arrayCopy[indexLower + 1]) / 2. }; + return returnArray; + } + + THROW_INVALID_ARGUMENT_ERROR("interpolation method has not been implemented: " + inInterpMethod); + break; // get rid of compiler warning... + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + NdArray returnArray(1, inShape.rows); + for (uint32 row = 0; row < inShape.rows; ++row) + { + returnArray[row] = percentile(NdArray(&inArray.front(row), inShape.cols), + inPercentile, + Axis::NONE, + inInterpMethod) + .item(); + } + + return returnArray; + } + case Axis::ROW: + { + return percentile(inArray.transpose(), inPercentile, Axis::COL, inInterpMethod); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/place.hpp b/runexamples/cpp/include/NumCpp/Functions/place.hpp new file mode 100644 index 0000000..7c00a80 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/place.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change elements of an array based on conditional and input values. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.place.html + /// + /// @param arr: Array to put data into. + /// @param mask: Boolean mask array. Must have the same size as arr + /// @param vals: Values to put into a. Only the first N elements are used, where N is the + /// number of True values in mask. If vals is smaller than N, it will be repeated. + /// @return NdArray + /// + template + void place(NdArray& arr, const NdArray& mask, const NdArray& vals) + { + if (mask.size() != arr.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input arguments 'arr' and 'mask' must have the same size."); + } + + if (vals.isempty()) + { + return; + } + + auto valIdx = 0; + for (decltype(arr.size()) i = 0; i < arr.size(); ++i) + { + if (mask[i]) + { + arr[i] = vals[valIdx++ % vals.size()]; + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/polar.hpp b/runexamples/cpp/include/NumCpp/Functions/polar.hpp new file mode 100644 index 0000000..fcc8d14 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/polar.hpp @@ -0,0 +1,82 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns a complex number with magnitude r and phase angle theta. + /// + /// @param magnitude + /// @param phaseAngle + /// + /// @return std::complex + /// + template + auto polar(dtype magnitude, dtype phaseAngle) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::polar(magnitude, phaseAngle); + } + + //============================================================================ + // Method Description: + /// Returns a complex number with magnitude r and phase angle theta. + /// + /// @param magnitude + /// @param phaseAngle + /// @return NdArray + /// + template + auto polar(const NdArray& magnitude, const NdArray& phaseAngle) + { + if (magnitude.shape() != phaseAngle.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("Input magnitude and phaseAngle arrays must be the same shape"); + } + + NdArray returnArray(magnitude.shape()); + stl_algorithms::transform( + magnitude.cbegin(), + magnitude.cend(), + phaseAngle.begin(), + returnArray.begin(), + [](dtype mag, dtype angle) -> auto{ return nc::polar(mag, angle); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/power.hpp b/runexamples/cpp/include/NumCpp/Functions/power.hpp new file mode 100644 index 0000000..5612fdb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/power.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inValue + /// @param inExponent + /// @return value raised to the power + /// + template + constexpr dtype power(dtype inValue, uint8 inExponent) noexcept + { + return utils::power(inValue, inExponent); + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponent + /// @return NdArray + /// + template + NdArray power(const NdArray& inArray, uint8 inExponent) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inExponent](dtype inValue) noexcept -> dtype + { return nc::power(inValue, inExponent); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input integer powers + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponents + /// @return NdArray + /// + template + NdArray power(const NdArray& inArray, const NdArray& inExponents) + { + if (inArray.shape() != inExponents.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + inExponents.cbegin(), + returnArray.begin(), + [](dtype inValue, uint8 inExponent) -> dtype + { return nc::power(inValue, inExponent); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/powerf.hpp b/runexamples/cpp/include/NumCpp/Functions/powerf.hpp new file mode 100644 index 0000000..b8c60f3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/powerf.hpp @@ -0,0 +1,108 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inValue + /// @param inExponent + /// @return value raised to the power + /// + template + auto powerf(dtype1 inValue, dtype2 inExponent) noexcept + { + return utils::powerf(inValue, inExponent); + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point power + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponent + /// @return NdArray + /// + template + auto powerf(const NdArray& inArray, dtype2 inExponent) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inExponent](dtype1 inValue) noexcept -> auto{ return nc::powerf(inValue, inExponent); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Raises the elements of the array to the input floating point powers + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.power.html + /// + /// @param inArray + /// @param inExponents + /// @return NdArray + /// + template + auto powerf(const NdArray& inArray, const NdArray& inExponents) + { + if (inArray.shape() != inExponents.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant."); + } + + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + inExponents.cbegin(), + returnArray.begin(), + [](dtype1 inValue, dtype2 inExponent) noexcept -> auto{ return nc::powerf(inValue, inExponent); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/print.hpp b/runexamples/cpp/include/NumCpp/Functions/print.hpp new file mode 100644 index 0000000..b533c76 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/print.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Prints the array to the console. + /// + /// @param inArray + /// @return None + /// + template + void print(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::cout << inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/prod.hpp b/runexamples/cpp/include/NumCpp/Functions/prod.hpp new file mode 100644 index 0000000..b34e3dd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/prod.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the product of array elements over a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.prod.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray prod(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.prod(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/proj.hpp b/runexamples/cpp/include/NumCpp/Functions/proj.hpp new file mode 100644 index 0000000..43a7646 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/proj.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns the projection of the complex number z onto the Riemann sphere. + /// + /// @param inValue + /// @return value + /// + template + auto proj(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::proj(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the projection of the complex number z onto the Riemann sphere. + /// + /// @param inArray + /// @return NdArray + /// + template + auto proj(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::proj(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/ptp.hpp b/runexamples/cpp/include/NumCpp/Functions/ptp.hpp new file mode 100644 index 0000000..bbb6d31 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ptp.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Range of values (maximum - minimum) along an axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ptp.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray ptp(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.ptp(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/put.hpp b/runexamples/cpp/include/NumCpp/Functions/put.hpp new file mode 100644 index 0000000..9b4bcba --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/put.hpp @@ -0,0 +1,472 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// set the flat index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndex + /// @param inValue + /// + template + NdArray& put(NdArray& inArray, int32 inIndex, const dtype& inValue) + { + inArray.put(inIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// set the 2D row/col index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRow + /// @param inCol + /// @param inValue + /// + template + NdArray& put(NdArray& inArray, int32 inRow, int32 inCol, const dtype& inValue) + { + inArray.put(inRow, inCol, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inIndices, const dtype& inValue) + { + inArray.put(inIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values[n] for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inIndices, const NdArray& inValues) + { + inArray.put(inIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inSlice, const dtype& inValue) + { + inArray.put(inSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inSlice, const NdArray& inValues) + { + inArray.put(inSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const ColIndices& inColIndices, + const dtype& inValue) + { + inArray.put(inRowIndices, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const RowIndices& inRowIndices, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowIndices, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, const ColIndices& inColIndices, const dtype& inValue) + { + inArray.put(inRowSlice, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inRowSlice, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowSlice, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, const Indices& inRowIndices, int32 inColIndex, const dtype& inValue) + { + inArray.put(inRowIndices, inColIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, const Slice& inRowSlice, int32 inColIndex, const dtype& inValue) + { + inArray.put(inRowSlice, inColIndex, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, int32 inRowIndex, const Indices& inColIndices, const dtype& inValue) + { + inArray.put(inRowIndex, inColIndices, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template + NdArray& put(NdArray& inArray, int32 inRowIndex, const Slice& inColSlice, const dtype& inValue) + { + inArray.put(inRowIndex, inColSlice, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const ColIndices& inColIndices, + const NdArray& inValues) + { + inArray.put(inRowIndices, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, + const RowIndices& inRowIndices, + const Slice& inColSlice, + const NdArray& inValues) + { + inArray.put(inRowIndices, inColSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& put(NdArray& inArray, + const Slice& inRowSlice, + const ColIndices& inColIndices, + const NdArray& inValues) + { + inArray.put(inRowSlice, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, const Slice& inColSlice, const NdArray& inValues) + { + inArray.put(inRowSlice, inColSlice, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndices + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, const Indices& inRowIndices, int32 inColIndex, const NdArray& inValues) + { + inArray.put(inRowIndices, inColIndex, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowSlice + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, const Slice& inRowSlice, int32 inColIndex, const NdArray& inValues) + { + inArray.put(inRowSlice, inColIndex, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + NdArray& + put(NdArray& inArray, int32 inRowIndex, const Indices& inColIndices, const NdArray& inValues) + { + inArray.put(inRowIndex, inColIndices, inValues); + return inArray; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inArray + /// @param inRowIndex + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template + NdArray& + put(NdArray& inArray, int32 inRowIndex, const Slice& inColSlice, const NdArray& inValues) + { + inArray.put(inRowIndex, inColSlice, inValues); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/putmask.hpp b/runexamples/cpp/include/NumCpp/Functions/putmask.hpp new file mode 100644 index 0000000..9a757c8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/putmask.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Changes elements of an array based on conditional and input values. + /// + /// Sets a.flat[n] = values[n] for each n where mask.flat[n] == True. + /// + /// If values is not the same size as a and mask then it will repeat. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.putmask.html + /// + /// @param inArray + /// @param inMask + /// @param inValue + /// @return NdArray + /// + template + NdArray& putmask(NdArray& inArray, const NdArray& inMask, dtype inValue) + { + inArray.putMask(inMask, inValue); + return inArray; + } + + //============================================================================ + // Method Description: + /// Changes elements of an array based on conditional and input values. + /// + /// Sets a.flat[n] = values[n] for each n where mask.flat[n] == True. + /// + /// If values is not the same size as a and mask then it will repeat. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.putmask.html + /// + /// @param inArray + /// @param inMask + /// @param inValues + /// @return NdArray + /// + template + NdArray& putmask(NdArray& inArray, const NdArray& inMask, const NdArray& inValues) + { + inArray.putMask(inMask, inValues); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/rad2deg.hpp b/runexamples/cpp/include/NumCpp/Functions/rad2deg.hpp new file mode 100644 index 0000000..edff3bf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/rad2deg.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from radians to degrees. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rad2deg.html + /// + /// @param inValue + /// + /// @return value + /// + template + constexpr auto rad2deg(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue * 180. / constants::pi; + } + + //============================================================================ + // Method Description: + /// Convert angles from radians to degrees. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rad2deg.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + auto rad2deg(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return rad2deg(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/radians.hpp b/runexamples/cpp/include/NumCpp/Functions/radians.hpp new file mode 100644 index 0000000..e0e15db --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/radians.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Functions/deg2rad.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.radians.html + /// + /// @param inValue + /// @return value + /// + template + constexpr auto radians(dtype inValue) noexcept + { + return deg2rad(inValue); + } + + //============================================================================ + // Method Description: + /// Convert angles from degrees to radians. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.radians.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto radians(const NdArray& inArray) + { + return deg2rad(inArray); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/ravel.hpp b/runexamples/cpp/include/NumCpp/Functions/ravel.hpp new file mode 100644 index 0000000..b363abf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/ravel.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Flattens the array but does not make a copy. + /// + /// Numpy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray& ravel(NdArray& inArray) noexcept + { + inArray.ravel(); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/real.hpp b/runexamples/cpp/include/NumCpp/Functions/real.hpp new file mode 100644 index 0000000..15822a1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/real.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the real part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.real.html + /// + /// @param inValue + /// @return value + /// + template + auto real(const std::complex& inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::real(inValue); + } + + //============================================================================ + // Method Description: + /// Return the real part of the complex argument. + /// + /// NumPy Reference: https://numpy.org/devdocs/reference/generated/numpy.real.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto real(const NdArray>& inArray) + { + NdArray{ 0 }))> returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](auto& inValue) -> auto{ return nc::real(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/reciprocal.hpp b/runexamples/cpp/include/NumCpp/Functions/reciprocal.hpp new file mode 100644 index 0000000..ccb85c8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/reciprocal.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the reciprocal of the argument, element-wise. + /// + /// Calculates 1 / x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.reciprocal.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray reciprocal(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray.shape()); + + uint32 counter = 0; + std::for_each(inArray.cbegin(), + inArray.cend(), + [&returnArray, &counter](dtype value) noexcept -> void + { returnArray[counter++] = 1. / static_cast(value); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Return the reciprocal of the argument, element-wise. + /// + /// Calculates 1 / x. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.reciprocal.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray> reciprocal(const NdArray>& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray> returnArray(inArray.shape()); + + uint32 counter = 0; + std::for_each(inArray.cbegin(), + inArray.cend(), + [&returnArray, &counter](std::complex value) -> void + { returnArray[counter++] = std::complex(1.) / complex_cast(value); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/remainder.hpp b/runexamples/cpp/include/NumCpp/Functions/remainder.hpp new file mode 100644 index 0000000..6ece5f4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/remainder.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.remainder.html + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return NdArray + /// + template + double remainder(dtype inValue1, dtype inValue2) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::remainder(inValue1, inValue2)); + } + + //============================================================================ + // Method Description: + /// Return element-wise remainder of division. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.remainder.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray remainder(const NdArray& inArray1, const NdArray& inArray2) + { + return broadcast::broadcaster(inArray1, + inArray2, + [](dtype inValue1, dtype inValue2) noexcept -> double + { return remainder(inValue1, inValue2); }); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/repeat.hpp b/runexamples/cpp/include/NumCpp/Functions/repeat.hpp new file mode 100644 index 0000000..5126095 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/repeat.hpp @@ -0,0 +1,70 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.repeat.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray repeat(const NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + return inArray.repeat(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.repeat.html + /// + /// @param inArray + /// @param inRepeatShape + /// + /// @return NdArray + /// + template + NdArray repeat(const NdArray& inArray, const Shape& inRepeatShape) + { + return inArray.repeat(inRepeatShape); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/replace.hpp b/runexamples/cpp/include/NumCpp/Functions/replace.hpp new file mode 100644 index 0000000..4714302 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/replace.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Replaces the matching elements of an array with the new value + /// + /// @param inArray + /// @param oldValue: the value to replace + /// @param newValue: the value to replace with + /// + /// @return NdArray + /// + template + NdArray replace(const NdArray& inArray, dtype oldValue, dtype newValue) + { + auto returnArray = inArray.copy(); + returnArray.replace(oldValue, newValue); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/reshape.hpp b/runexamples/cpp/include/NumCpp/Functions/reshape.hpp new file mode 100644 index 0000000..6e0d97e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/reshape.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inSize + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, uint32 inSize) + { + inArray.reshape(inSize); + return inArray; + } + + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, int32 inNumRows, int32 inNumCols) + { + inArray.reshape(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Gives a new shape to an array without changing its data. + /// + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& reshape(NdArray& inArray, const Shape& inNewShape) + { + inArray.reshape(inNewShape); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/resizeFast.hpp b/runexamples/cpp/include/NumCpp/Functions/resizeFast.hpp new file mode 100644 index 0000000..62ca62b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/resizeFast.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& resizeFast(NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + inArray.resizeFast(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& resizeFast(NdArray& inArray, const Shape& inNewShape) + { + inArray.resizeFast(inNewShape); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/resizeSlow.hpp b/runexamples/cpp/include/NumCpp/Functions/resizeSlow.hpp new file mode 100644 index 0000000..75404f6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/resizeSlow.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// + /// @return NdArray + /// + template + NdArray& resizeSlow(NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + inArray.resizeSlow(inNumRows, inNumCols); + return inArray; + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.resize.html + /// + /// @param inArray + /// @param inNewShape + /// + /// @return NdArray + /// + template + NdArray& resizeSlow(NdArray& inArray, const Shape& inNewShape) + { + inArray.resizeSlow(inNewShape); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/right_shift.hpp b/runexamples/cpp/include/NumCpp/Functions/right_shift.hpp new file mode 100644 index 0000000..7c785c5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/right_shift.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Shift the bits of an integer to the right. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.right_shift.html + /// + /// @param inArray + /// @param inNumBits + /// + /// @return NdArray + /// + template + NdArray right_shift(const NdArray& inArray, uint8 inNumBits) + { + return inArray >> inNumBits; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/rint.hpp b/runexamples/cpp/include/NumCpp/Functions/rint.hpp new file mode 100644 index 0000000..65300a2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/rint.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round value to the nearest integer. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rint.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype rint(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::rint(inValue); + } + + //============================================================================ + // Method Description: + /// Round elements of the array to the nearest integer. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rint.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray rint(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return rint(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/rms.hpp b/runexamples/cpp/include/NumCpp/Functions/rms.hpp new file mode 100644 index 0000000..c36aa97 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/rms.hpp @@ -0,0 +1,141 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the root mean square (RMS) along the specified axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray rms(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double squareSum = 0.; + const auto function = [&squareSum](dtype value) -> void + { squareSum += utils::sqr(static_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + NdArray returnArray = { std::sqrt(squareSum / static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + squareSum = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(squareSum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + return rms(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Compute the root mean square (RMS) along the specified axis. + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> rms(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex squareSum = 0.; + const auto function = [&squareSum](std::complex value) -> void + { squareSum += utils::sqr(complex_cast(value)); }; + + switch (inAxis) + { + case Axis::NONE: + { + std::for_each(inArray.cbegin(), inArray.cend(), function); + NdArray> returnArray = { std::sqrt(squareSum / + static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + squareSum = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + returnArray(0, row) = std::sqrt(squareSum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + return rms(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/roll.hpp b/runexamples/cpp/include/NumCpp/Functions/roll.hpp new file mode 100644 index 0000000..90c0e0e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/roll.hpp @@ -0,0 +1,100 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Roll array elements along a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.roll.html + /// + /// @param inArray + /// @param inShift: (elements to shift, positive means forward, negative means backwards) + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray roll(const NdArray& inArray, int32 inShift, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + uint32 shift = std::abs(inShift) % inArray.size(); + if (inShift > 0) + { + shift = inArray.size() - shift; + } + + NdArray returnArray(inArray); + stl_algorithms::rotate(returnArray.begin(), returnArray.begin() + shift, returnArray.end()); + + return returnArray; + } + case Axis::COL: + { + const Shape inShape = inArray.shape(); + + uint32 shift = std::abs(inShift) % inShape.cols; + if (inShift > 0) + { + shift = inShape.cols - shift; + } + + NdArray returnArray(inArray); + for (uint32 row = 0; row < inShape.rows; ++row) + { + stl_algorithms::rotate(returnArray.begin(row), + returnArray.begin(row) + shift, + returnArray.end(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return roll(inArray.transpose(), inShift, Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/rot90.hpp b/runexamples/cpp/include/NumCpp/Functions/rot90.hpp new file mode 100644 index 0000000..f51eba5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/rot90.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/flip.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/Functions/flipud.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Rotate an array by 90 degrees counter clockwise in the plane. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.rot90.html + /// + /// @param inArray + /// @param inK: the number of times to rotate 90 degrees + /// + /// @return NdArray + /// + template + NdArray rot90(const NdArray& inArray, uint8 inK = 1) + { + inK %= 4; + switch (inK) + { + case 0: + { + return inArray; + } + case 1: + { + return flipud(inArray.transpose()); + } + case 2: + { + return flip(inArray, Axis::NONE); + } + case 3: + { + return fliplr(inArray.transpose()); + } + default: + { + // this isn't actually possible, just putting this here to get rid + // of the compiler warning. + return {}; + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/round.hpp b/runexamples/cpp/include/NumCpp/Functions/round.hpp new file mode 100644 index 0000000..1a9b6ec --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/round.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Round value to the given number of decimals. + /// + /// @param inValue + /// @param inDecimals + /// + /// @return value + /// + template + dtype round(dtype inValue, uint8 inDecimals = 0) + { + NdArray input = { inValue }; + return input.round(inDecimals).item(); + } + + //============================================================================ + // Method Description: + /// Round an array to the given number of decimals. + /// + /// @param inArray + /// @param inDecimals + /// + /// @return NdArray + /// + template + NdArray round(const NdArray& inArray, uint8 inDecimals = 0) + { + return inArray.round(inDecimals); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/row_stack.hpp b/runexamples/cpp/include/NumCpp/Functions/row_stack.hpp new file mode 100644 index 0000000..902b09d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/row_stack.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Stack arrays in sequence vertically (row wise). + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray row_stack(const std::initializer_list>& inArrayList) + { + // first loop through to calculate the final size of the array + Shape finalShape; + for (auto& ndarray : inArrayList) + { + if (finalShape.isnull()) + { + finalShape = ndarray.shape(); + } + else if (ndarray.shape().cols != finalShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input arrays must have the same number of columns."); + } + else + { + finalShape.rows += ndarray.shape().rows; + } + } + + // now that we know the final size, contruct the output array + NdArray returnArray(finalShape); + uint32 rowStart = 0; + for (auto& ndarray : inArrayList) + { + const Shape theShape = ndarray.shape(); + for (uint32 row = 0; row < theShape.rows; ++row) + { + for (uint32 col = 0; col < theShape.cols; ++col) + { + returnArray(rowStart + row, col) = ndarray(row, col); + } + } + rowStart += theShape.rows; + } + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/select.hpp b/runexamples/cpp/include/NumCpp/Functions/select.hpp new file mode 100644 index 0000000..eb34aed --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/select.hpp @@ -0,0 +1,158 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return an array drawn from elements in choiceVec, depending on conditions. + /// + /// NumPy Reference: + /// https://numpy.org/doc/stable/reference/generated/numpy.select.html?highlight=select#numpy.select + /// + /// @param condVec The vector of conditions which determine from which array in choiceVec + /// the output elements are taken. When multiple conditions are satisfied, + /// the first one encountered in choiceVec is used. + /// @param choiceVec The vector of array pointers from which the output elements are taken. + /// It has to be of the same length as condVec. + /// @param defaultValue The element inserted in output when all conditions evaluate to False + /// @return NdArray + /// + template + NdArray select(const std::vector*>& condVec, + const std::vector*>& choiceVec, + dtype defaultValue = dtype{ 0 }) + { + if (choiceVec.size() != condVec.size()) + { + THROW_INVALID_ARGUMENT_ERROR("condVec and choiceVec need to be the same size"); + } + + if (choiceVec.size() == 0) + { + THROW_INVALID_ARGUMENT_ERROR("choiceVec is size 0"); + } + + auto theShape = condVec.front()->shape(); + for (const auto cond : condVec) + { + const auto& theCond = *cond; + if (theCond.shape() != theShape) + { + THROW_INVALID_ARGUMENT_ERROR("all NdArrays of the condVec must be the same shape"); + } + } + + for (const auto choice : choiceVec) + { + const auto& theChoice = *choice; + if (theChoice.shape() != theShape) + { + THROW_INVALID_ARGUMENT_ERROR( + "all NdArrays of the choiceVec must be the same shape, and the same as condVec"); + } + } + + using size_type = typename NdArray::size_type; + constexpr auto nullChoice = std::numeric_limits::max(); + + NdArray choiceIndices(theShape); + choiceIndices.fill(nullChoice); + for (size_type condIdx = 0; condIdx < condVec.size(); ++condIdx) + { + const auto& theCond = *condVec[condIdx]; + for (size_type i = 0; i < theCond.size(); ++i) + { + if (theCond[i] && choiceIndices[i] == nullChoice) + { + choiceIndices[i] = condIdx; + } + } + } + + NdArray result(theShape); + result.fill(defaultValue); + for (size_type i = 0; i < choiceIndices.size(); ++i) + { + const auto choiceIndex = choiceIndices[i]; + if (choiceIndex != nullChoice) + { + const auto& theChoice = *choiceVec[choiceIndex]; + result[i] = theChoice[i]; + } + } + + return result; + } + + //============================================================================ + // Method Description: + /// Return an array drawn from elements in choiceList, depending on conditions. + /// + /// NumPy Reference: + /// https://numpy.org/doc/stable/reference/generated/numpy.select.html?highlight=select#numpy.select + /// + /// @param condList The list of conditions which determine from which array in choiceList + /// the output elements are taken. When multiple conditions are satisfied, + /// the first one encountered in choiceList is used. + /// @param choiceList The list of array pointers from which the output elements are taken. + /// It has to be of the same length as condVec. + /// @param defaultValue The element inserted in output when all conditions evaluate to False + /// @return NdArray + /// + template + NdArray select(const std::vector>& condList, + const std::vector>& choiceList, + dtype defaultValue = dtype{ 0 }) + { + std::vector*> condVec(condList.size()); + stl_algorithms::transform(condList.begin(), + condList.end(), + condVec.begin(), + [](auto& cond) noexcept -> const NdArray* { return &cond; }); + + std::vector*> choiceVec(choiceList.size()); + stl_algorithms::transform(choiceList.begin(), + choiceList.end(), + choiceVec.begin(), + [](auto& choice) noexcept -> const NdArray* { return &choice; }); + + return select(condVec, choiceVec, defaultValue); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/setdiff1d.hpp b/runexamples/cpp/include/NumCpp/Functions/setdiff1d.hpp new file mode 100644 index 0000000..8220ed7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/setdiff1d.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/unique.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the set difference of two arrays. + /// + /// Return the sorted, unique values in ar1 that are not in ar2. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.setdiff1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray setdiff1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool { return lhs < rhs; }; + + const auto set1 = unique(inArray1); + const auto set2 = unique(inArray2); + + std::vector res(set1.size()); + const auto last = + stl_algorithms::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/shape.hpp b/runexamples/cpp/include/NumCpp/Functions/shape.hpp new file mode 100644 index 0000000..d3ddad5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/shape.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the shape of the array + /// + /// @param inArray + /// @return Shape + /// + template + Shape shape(const NdArray& inArray) noexcept + { + return inArray.shape(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sign.hpp b/runexamples/cpp/include/NumCpp/Functions/sign.hpp new file mode 100644 index 0000000..672f289 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sign.hpp @@ -0,0 +1,92 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns an element-wise indication of the sign of a number. + /// + /// The sign function returns - 1 if x < 0, 0 if x == 0, 1 if x > 0. + /// nan is returned for nan inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sign.html + /// + /// @param inValue + /// @return NdArray + /// + template + int8 sign(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inValue < dtype{ 0 }) + { + return -1; + } + + if (inValue > dtype{ 0 }) + { + return 1; + } + + return 0; + } + + //============================================================================ + // Method Description: + /// Returns an element-wise indication of the sign of a number. + /// + /// The sign function returns - 1 if x < 0, 0 if x == 0, 1 if x > 0. + /// nan is returned for nan inputs. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sign.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray sign(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> int8 { return sign(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/signbit.hpp b/runexamples/cpp/include/NumCpp/Functions/signbit.hpp new file mode 100644 index 0000000..7a1f30f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/signbit.hpp @@ -0,0 +1,73 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Returns element-wise True where signbit is set (less than zero). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.signbit.html + /// + /// @param inValue + /// @return NdArray + /// + template + bool signbit(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inValue < dtype{ 0 } ? true : false; + } + + //============================================================================ + // Method Description: + /// Returns element-wise True where signbit is set (less than zero). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.signbit.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray signbit(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> bool { return signbit(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sin.hpp b/runexamples/cpp/include/NumCpp/Functions/sin.hpp new file mode 100644 index 0000000..de1b5c9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sin.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trigonometric sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sin.html + /// + /// @param inValue + /// @return value + /// + template + auto sin(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sin(inValue); + } + + //============================================================================ + // Method Description: + /// Trigonometric sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sin.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sin(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sin(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sinc.hpp b/runexamples/cpp/include/NumCpp/Functions/sinc.hpp new file mode 100644 index 0000000..44bf816 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sinc.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sinc function. + /// + /// The sinc function is sin(pi*x) / (pi*x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinc.html + /// + /// @param inValue + /// @return value + /// + template + auto sinc(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sin(constants::pi * inValue) / (constants::pi * inValue); + } + + //============================================================================ + // Method Description: + /// Return the sinc function. + /// + /// The sinc function is sin(pi*x) / (pi*x). + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinc.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sinc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sinc(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sinh.hpp b/runexamples/cpp/include/NumCpp/Functions/sinh.hpp new file mode 100644 index 0000000..03927dd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sinh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Hyperbolic sine. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinh.html + /// + /// @param inValue + /// @return value + /// + template + auto sinh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sinh(inValue); + } + + //============================================================================ + // Method Description: + /// Hyperbolic sine, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sinh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sinh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sinh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/size.hpp b/runexamples/cpp/include/NumCpp/Functions/size.hpp new file mode 100644 index 0000000..3dca948 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/size.hpp @@ -0,0 +1,47 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the number of elements. + /// + /// @param inArray + /// @return uint32 size + /// + template + uint32 size(const NdArray& inArray) noexcept + { + return inArray.size(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sort.hpp b/runexamples/cpp/include/NumCpp/Functions/sort.hpp new file mode 100644 index 0000000..7fce03c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sort.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a sorted copy of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sort.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray sort(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + NdArray returnArray(inArray); + returnArray.sort(inAxis); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/split.hpp b/runexamples/cpp/include/NumCpp/Functions/split.hpp new file mode 100644 index 0000000..21a0a4a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/split.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Functions/hsplit.hpp" +#include "NumCpp/Functions/vsplit.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays as views into array. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.split.html + /// + /// @param inArray + /// @param indices: the indices to split + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template = 0> + std::vector> split(const NdArray& inArray, const Indices& indices, Axis inAxis = Axis::ROW) + { + switch (inAxis) + { + case Axis::ROW: + { + return vsplit(inArray, indices); + } + case Axis::COL: + { + return hsplit(inArray, indices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input inAxis must be either Axis::ROW or Axis::COL"); + } + } + + return {}; // get rid of compiler warning + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sqrt.hpp b/runexamples/cpp/include/NumCpp/Functions/sqrt.hpp new file mode 100644 index 0000000..cddaef1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sqrt.hpp @@ -0,0 +1,76 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the positive square-root of a value. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sqrt.html + /// + /// @param inValue + /// @return value + /// + template + auto sqrt(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::sqrt(inValue); + } + + //============================================================================ + // Method Description: + /// Return the positive square-root of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sqrt.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto sqrt(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return sqrt(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/square.hpp b/runexamples/cpp/include/NumCpp/Functions/square.hpp new file mode 100644 index 0000000..567d3cb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/square.hpp @@ -0,0 +1,74 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the square of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.square.html + /// + /// @param inValue + /// @return value + /// + template + constexpr dtype square(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return utils::sqr(inValue); + } + + //============================================================================ + // Method Description: + /// Return the square of an array, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.square.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray square(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return square(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/stack.hpp b/runexamples/cpp/include/NumCpp/Functions/stack.hpp new file mode 100644 index 0000000..69ac4ad --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/stack.hpp @@ -0,0 +1,71 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/column_stack.hpp" +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.stack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// @param inAxis: axis to stack the input NdArrays + /// @return NdArray + /// + template + NdArray stack(std::initializer_list> inArrayList, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::ROW: + { + return row_stack(inArrayList); + } + case Axis::COL: + { + return column_stack(inArrayList); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("inAxis must be either ROW or COL."); + return {}; // getting rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/stdev.hpp b/runexamples/cpp/include/NumCpp/Functions/stdev.hpp new file mode 100644 index 0000000..fc205e6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/stdev.hpp @@ -0,0 +1,168 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/mean.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.std.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray stdev(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + double meanValue = 0.; + double sum = 0.; + + const auto function = [&sum, &meanValue](dtype value) -> void + { sum += utils::sqr(static_cast(value) - meanValue); }; + + switch (inAxis) + { + case Axis::NONE: + { + meanValue = mean(inArray, inAxis).item(); + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray returnArray = { std::sqrt(sum / inArray.size()) }; + return returnArray; + } + case Axis::COL: + { + NdArray meanValueArray = mean(inArray, inAxis); + NdArray returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = 0.; + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / inArray.numCols()); + } + + return returnArray; + } + case Axis::ROW: + { + return stdev(inArray.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Compute the standard deviation along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.std.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray> stdev(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::complex meanValue(0., 0.); + std::complex sum(0., 0.); + + const auto function = [&sum, &meanValue](std::complex value) -> void + { sum += utils::sqr(complex_cast(value) - meanValue); }; + + switch (inAxis) + { + case Axis::NONE: + { + meanValue = mean(inArray, inAxis).item(); + std::for_each(inArray.cbegin(), inArray.cend(), function); + + NdArray> returnArray = { std::sqrt(sum / static_cast(inArray.size())) }; + return returnArray; + } + case Axis::COL: + { + NdArray> meanValueArray = mean(inArray, inAxis); + NdArray> returnArray(1, inArray.numRows()); + for (uint32 row = 0; row < inArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = std::complex(0., 0.); + std::for_each(inArray.cbegin(row), inArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / static_cast(inArray.numCols())); + } + + return returnArray; + } + case Axis::ROW: + { + NdArray> meanValueArray = mean(inArray, inAxis); + NdArray> transposedArray = inArray.transpose(); + NdArray> returnArray(1, transposedArray.numRows()); + for (uint32 row = 0; row < transposedArray.numRows(); ++row) + { + meanValue = meanValueArray[row]; + sum = std::complex(0., 0.); + std::for_each(transposedArray.cbegin(row), transposedArray.cend(row), function); + + returnArray(0, row) = std::sqrt(sum / static_cast(transposedArray.numCols())); + } + + return returnArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/subtract.hpp b/runexamples/cpp/include/NumCpp/Functions/subtract.hpp new file mode 100644 index 0000000..abc2f37 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/subtract.hpp @@ -0,0 +1,179 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray subtract(const NdArray& inArray1, const NdArray& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray subtract(const NdArray& inArray, dtype value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray subtract(dtype value, const NdArray& inArray) + { + return value - inArray; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> subtract(const NdArray& inArray1, const NdArray>& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray1 + /// @param inArray2 + /// @return NdArray + /// + template + NdArray> subtract(const NdArray>& inArray1, const NdArray& inArray2) + { + return inArray1 - inArray2; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> subtract(const NdArray& inArray, const std::complex& value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> subtract(const std::complex& value, const NdArray& inArray) + { + return value - inArray; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param inArray + /// @param value + /// @return NdArray + /// + template + NdArray> subtract(const NdArray>& inArray, dtype value) + { + return inArray - value; + } + + //============================================================================ + // Method Description: + /// subtract arguments element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.subtract.html + /// + /// @param value + /// @param inArray + /// @return NdArray + /// + template + NdArray> subtract(dtype value, const NdArray>& inArray) + { + return value - inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/sum.hpp b/runexamples/cpp/include/NumCpp/Functions/sum.hpp new file mode 100644 index 0000000..b6cdc1a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/sum.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Sum of array elements over a given axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.sum.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray sum(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + return inArray.sum(inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/swap.hpp b/runexamples/cpp/include/NumCpp/Functions/swap.hpp new file mode 100644 index 0000000..52e4110 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/swap.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps the contents of two arrays + /// + /// @param inArray1 + /// @param inArray2 + /// + template + void swap(NdArray& inArray1, NdArray& inArray2) noexcept + { + NdArray tmp(std::move(inArray1)); + inArray1 = std::move(inArray2); + inArray2 = std::move(tmp); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/swapCols.hpp b/runexamples/cpp/include/NumCpp/Functions/swapCols.hpp new file mode 100644 index 0000000..842f8a2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/swapCols.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps cols of the array + /// + /// @param inArray + /// @param colIdx1 + /// @param colIdx2 + /// + template + NdArray& swapCols(NdArray& inArray, int32 colIdx1, int32 colIdx2) noexcept + { + inArray.swapCols(colIdx1, colIdx2); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/swapRows.hpp b/runexamples/cpp/include/NumCpp/Functions/swapRows.hpp new file mode 100644 index 0000000..a8329ac --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/swapRows.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param inArray + /// @param rowIdx1 + /// @param rowIdx2 + /// + template + NdArray& swapRows(NdArray& inArray, int32 rowIdx1, int32 rowIdx2) noexcept + { + inArray.swapRows(rowIdx1, rowIdx2); + return inArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/swapaxes.hpp b/runexamples/cpp/include/NumCpp/Functions/swapaxes.hpp new file mode 100644 index 0000000..12fe639 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/swapaxes.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Interchange two axes of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.swapaxes.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray swapaxes(const NdArray& inArray) + { + return inArray.swapaxes(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/take.hpp b/runexamples/cpp/include/NumCpp/Functions/take.hpp new file mode 100644 index 0000000..939af1a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/take.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Evenly round to the given number of decimals. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.take.html + /// + /// @param inArray + /// @param inIndices + /// @param inAxis + /// @return NdArray + /// + template = 0> + NdArray take(const NdArray& inArray, const Indices& inIndices, Axis inAxis = Axis::NONE) + { + switch (inAxis) + { + case Axis::NONE: + { + return inArray[inIndices]; + } + case Axis::ROW: + { + return inArray(inIndices, inArray.cSlice()); + } + case Axis::COL: + { + return inArray(inArray.rSlice(), inIndices); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/tan.hpp b/runexamples/cpp/include/NumCpp/Functions/tan.hpp new file mode 100644 index 0000000..fc76229 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/tan.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tan.html + /// + /// @param inValue + /// @return value + /// + template + auto tan(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::tan(inValue); + } + + //============================================================================ + // Method Description: + /// Compute tangent element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tan.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto tan(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return tan(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/tanh.hpp b/runexamples/cpp/include/NumCpp/Functions/tanh.hpp new file mode 100644 index 0000000..1d156c0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/tanh.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute hyperbolic tangent. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tanh.html + /// + /// @param inValue + /// @return value + /// + template + auto tanh(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return std::tanh(inValue); + } + + //============================================================================ + // Method Description: + /// Compute hyperbolic tangent element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tanh.html + /// + /// @param inArray + /// @return NdArray + /// + template + auto tanh(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> auto{ return tanh(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/tile.hpp b/runexamples/cpp/include/NumCpp/Functions/tile.hpp new file mode 100644 index 0000000..d999bd2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/tile.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Construct an array by repeating A the number of times given by reps. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tile.html + /// + /// @param inArray + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray tile(const NdArray& inArray, uint32 inNumRows, uint32 inNumCols) + { + return inArray.repeat(inNumRows, inNumCols); + } + + //============================================================================ + // Method Description: + /// Construct an array by repeating A the number of times given by reps. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tile.html + /// + /// @param inArray + /// @param inReps + /// @return NdArray + /// + template + NdArray tile(const NdArray& inArray, const Shape& inReps) + { + return inArray.repeat(inReps); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/toStlVector.hpp b/runexamples/cpp/include/NumCpp/Functions/toStlVector.hpp new file mode 100644 index 0000000..d55c6bf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/toStlVector.hpp @@ -0,0 +1,46 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Write flattened array to an STL vector + /// + /// @param inArray + /// @return std::vector + /// + template + std::vector toStlVector(const NdArray& inArray) + { + return inArray.toStlVector(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/tofile.hpp b/runexamples/cpp/include/NumCpp/Functions/tofile.hpp new file mode 100644 index 0000000..940a38e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/tofile.hpp @@ -0,0 +1,68 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Write array to a file as binary. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// @param inArray + /// @param inFilename + /// @return None + /// + template + void tofile(const NdArray& inArray, const std::string& inFilename) + { + return inArray.tofile(inFilename); + } + + //============================================================================ + // Method Description: + /// Write array to a file as text. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// @param inArray + /// @param inFilename + /// @param inSep: Separator between array items for text output. + /// @return None + /// + template + void tofile(const NdArray& inArray, const std::string& inFilename, const char inSep) + { + return inArray.tofile(inFilename, inSep); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/trace.hpp b/runexamples/cpp/include/NumCpp/Functions/trace.hpp new file mode 100644 index 0000000..9c03e6d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/trace.hpp @@ -0,0 +1,51 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the sum along diagonals of the array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trace.html + /// + /// @param inArray + /// @param inOffset: (Offset from main diaganol, default = 0, negative=above, positve=below) + /// @param inAxis (Optional, default ROW) + /// @return NdArray + /// + template + dtype trace(const NdArray& inArray, int16 inOffset = 0, Axis inAxis = Axis::ROW) noexcept + { + return inArray.trace(inOffset, inAxis); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/transpose.hpp b/runexamples/cpp/include/NumCpp/Functions/transpose.hpp new file mode 100644 index 0000000..d6853df --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/transpose.hpp @@ -0,0 +1,49 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Permute the dimensions of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.transpose.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray transpose(const NdArray& inArray) + { + return inArray.transpose(); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/trapz.hpp b/runexamples/cpp/include/NumCpp/Functions/trapz.hpp new file mode 100644 index 0000000..21e29f6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/trapz.hpp @@ -0,0 +1,167 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Integrate along the given axis using the composite trapezoidal rule. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html + /// + /// @param inArray + /// @param dx: (Optional defaults to 1.) + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray trapz(const NdArray& inArray, double dx = 1., Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + switch (inAxis) + { + case Axis::NONE: + { + double sum = 0.; + for (uint32 i = 0; i < inArray.size() - 1; ++i) + { + sum += static_cast(inArray[i + 1] - inArray[i]) / 2. + static_cast(inArray[i]); + } + + NdArray returnArray = { sum * dx }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inShape.rows, 1); + for (uint32 row = 0; row < inShape.rows; ++row) + { + double sum = 0; + for (uint32 col = 0; col < inShape.cols - 1; ++col) + { + sum += static_cast(inArray(row, col + 1) - inArray(row, col)) / 2. + + static_cast(inArray(row, col)); + } + + returnArray[row] = sum * dx; + } + + return returnArray; + } + case Axis::ROW: + { + return trapz(inArray.transpose(), dx, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Integrate along the given axis using the composite trapezoidal rule. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trapz.html + /// + /// @param inArrayY + /// @param inArrayX + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray trapz(const NdArray& inArrayY, const NdArray& inArrayX, Axis inAxis = Axis::NONE) + { + const Shape inShapeY = inArrayY.shape(); + const Shape inShapeX = inArrayX.shape(); + + if (inShapeY != inShapeX) + { + THROW_INVALID_ARGUMENT_ERROR("input x and y arrays should be the same shape."); + } + + switch (inAxis) + { + case Axis::NONE: + { + double sum = 0.; + for (uint32 i = 0; i < inArrayY.size() - 1; ++i) + { + const auto dx = static_cast(inArrayX[i + 1] - inArrayX[i]); + sum += dx * + (static_cast(inArrayY[i + 1] - inArrayY[i]) / 2. + static_cast(inArrayY[i])); + } + + NdArray returnArray = { sum }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(inShapeY.rows, 1); + for (uint32 row = 0; row < inShapeY.rows; ++row) + { + double sum = 0; + for (uint32 col = 0; col < inShapeY.cols - 1; ++col) + { + const auto dx = static_cast(inArrayX(row, col + 1) - inArrayX(row, col)); + sum += dx * (static_cast(inArrayY(row, col + 1) - inArrayY(row, col)) / 2. + + static_cast(inArrayY(row, col))); + } + + returnArray[row] = sum; + } + + return returnArray; + } + case Axis::ROW: + { + return trapz(inArrayY.transpose(), inArrayX.transpose(), Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/tri.hpp b/runexamples/cpp/include/NumCpp/Functions/tri.hpp new file mode 100644 index 0000000..fdc3b11 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/tri.hpp @@ -0,0 +1,257 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// An array with ones at and below the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(uint32 inN, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN); + returnArray.zeros(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inN) + { + break; + } + + returnArray(row, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and below the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows + /// @param inM: number of columns + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(uint32 inN, uint32 inM, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else if (inOffset < 0) + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN, inM); + returnArray.zeros(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inM) + { + break; + } + + returnArray(row, col) = dtype{ 1 }; + } + } + + return returnArray; + } + + // forward declare + template + NdArray triu(uint32 inN, uint32 inM, int32 inOffset = 0); + + //============================================================================ + // Method Description: + /// Lower triangle of an array. + /// + /// Return a copy of an array with elements above the k - th diagonal zeroed. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.tril.html + /// + /// @param inArray: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray tril(const NdArray& inArray, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + auto outArray = inArray.copy(); + outArray.putMask(triu(inShape.rows, inShape.cols, inOffset + 1), 0); + return outArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and above the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows + /// @param inM: number of columns + /// @param inOffset: (the sub-diagonal at and above which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(uint32 inN, uint32 inM, int32 inOffset) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + // because i'm stealing the lines of code from tril and reversing it, this is necessary + inOffset -= 1; + + uint32 rowStart = 0; + uint32 colStart = 0; + if (inOffset > 0) + { + colStart = inOffset; + } + else if (inOffset < 0) + { + rowStart = inOffset * -1; + } + + NdArray returnArray(inN, inM); + returnArray.ones(); + for (uint32 row = rowStart; row < inN; ++row) + { + for (uint32 col = 0; col < row + colStart + 1 - rowStart; ++col) + { + if (col == inM) + { + break; + } + + returnArray(row, col) = dtype{ 0 }; + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// An array with ones at and above the given diagonal and zeros elsewhere. + /// + /// @param inN: number of rows and cols + /// @param inOffset: (the sub-diagonal at and above which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(uint32 inN, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return tril(inN, -inOffset).transpose(); + } + + //============================================================================ + // Method Description: + /// Upper triangle of an array. + /// + /// Return a copy of an array with elements below the k - th diagonal zeroed. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.triu.html + /// + /// @param inArray: number of rows and cols + /// @param inOffset: (the sub-diagonal at and below which the array is filled. + /// k = 0 is the main diagonal, while k < 0 is below it, + /// and k > 0 is above. The default is 0.) + /// + /// + /// @return NdArray + /// + template + NdArray triu(const NdArray& inArray, int32 inOffset = 0) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + auto outArray = inArray.copy(); + outArray.putMask(tril(inShape.rows, inShape.cols, inOffset - 1), 0); + return outArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/trim_zeros.hpp b/runexamples/cpp/include/NumCpp/Functions/trim_zeros.hpp new file mode 100644 index 0000000..bcd0208 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/trim_zeros.hpp @@ -0,0 +1,147 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Trim the leading and/or trailing zeros from a 1-D array or sequence. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trim_zeros.html + /// + /// @param inArray + /// @param inTrim: ("f" = front, "b" = back, "fb" = front and back) + /// + /// @return NdArray + /// + template + NdArray trim_zeros(const NdArray& inArray, const std::string& inTrim = "fb") + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inTrim == "f") + { + uint32 place = 0; + for (auto value : inArray) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + break; + } + + ++place; + } + + if (place == inArray.size()) + { + return NdArray(0); + } + + NdArray returnArray(1, inArray.size() - place); + stl_algorithms::copy(inArray.cbegin() + place, inArray.cend(), returnArray.begin()); + + return returnArray; + } + + if (inTrim == "b") + { + uint32 place = inArray.size(); + for (uint32 i = inArray.size() - 1; i > 0; --i) + { + if (!utils::essentiallyEqual(inArray[i], dtype{ 0 })) + { + break; + } + + --place; + } + + if (place == 0 || (place == 1 && utils::essentiallyEqual(inArray[0], dtype{ 0 }))) + { + return NdArray(0); + } + + NdArray returnArray(1, place); + stl_algorithms::copy(inArray.cbegin(), inArray.cbegin() + place, returnArray.begin()); + + return returnArray; + } + + if (inTrim == "fb") + { + uint32 placeBegin = 0; + for (auto value : inArray) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + break; + } + + ++placeBegin; + } + + if (placeBegin == inArray.size()) + { + return NdArray(0); + } + + uint32 placeEnd = inArray.size(); + for (uint32 i = inArray.size() - 1; i > 0; --i) + { + if (!utils::essentiallyEqual(inArray[i], dtype{ 0 })) + { + break; + } + + --placeEnd; + } + + if (placeEnd == 0 || (placeEnd == 1 && utils::essentiallyEqual(inArray[0], dtype{ 0 }))) + { + return NdArray(0); + } + + NdArray returnArray(1, placeEnd - placeBegin); + stl_algorithms::copy(inArray.cbegin() + placeBegin, inArray.cbegin() + placeEnd, returnArray.begin()); + + return returnArray; + } + + THROW_INVALID_ARGUMENT_ERROR("trim options are 'f' = front, 'b' = back, 'fb' = front and back."); + return {}; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/trunc.hpp b/runexamples/cpp/include/NumCpp/Functions/trunc.hpp new file mode 100644 index 0000000..b15acf2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/trunc.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return the truncated value of the input. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trunc.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype trunc(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::trunc(inValue); + } + + //============================================================================ + // Method Description: + /// Return the truncated value of the input, element-wise. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.trunc.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray trunc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return trunc(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/union1d.hpp b/runexamples/cpp/include/NumCpp/Functions/union1d.hpp new file mode 100644 index 0000000..9817d62 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/union1d.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the union of two arrays. + /// + /// Return the unique, sorted array of values that are in + /// either of the two input arrays. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.union1d.html + /// + /// @param inArray1 + /// @param inArray2 + /// + /// @return NdArray + /// + template + NdArray union1d(const NdArray& inArray1, const NdArray& inArray2) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool { return lhs < rhs; }; + + const auto set1 = unique(inArray1); + const auto set2 = unique(inArray2); + + std::vector res(set1.size() + set2.size()); + const auto last = + stl_algorithms::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/unique.hpp b/runexamples/cpp/include/NumCpp/Functions/unique.hpp new file mode 100644 index 0000000..0d6e05a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/unique.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Functions/sort.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Find the unique elements of an array. + /// + /// Returns the sorted unique elements of an array. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unique.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray unique(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comp = [](const dtype lhs, const dtype rhs) noexcept -> bool + { return utils::essentiallyEqual(lhs, rhs); }; + + const auto sorted = sort(inArray); + + std::vector res(sorted.size()); + const auto last = stl_algorithms::unique_copy(sorted.begin(), sorted.end(), res.begin(), comp); + + return NdArray(res.begin(), last); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/unpackbits.hpp b/runexamples/cpp/include/NumCpp/Functions/unpackbits.hpp new file mode 100644 index 0000000..570b765 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/unpackbits.hpp @@ -0,0 +1,161 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Unpacks elements of a uint8 array into a binary-valued output array. + /// + /// Each element of a represents a bit - field that should be unpacked into a binary - + /// valued output array.The shape of the output array is either 1 - D(if axis is None) or + /// the same shape as the input array with unpacking done along the axis specified. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html + /// + /// @param a: An array of uint8 whose elements should be unpacked to bits. + /// @param axis: The dimension over which bit-unpacking is done. None implies unpacking the flattened array. + /// @return NdArray + /// + inline NdArray unpackbitsLittleEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + NdArray result(1, a.size() * 8); + + for (NdArray::size_type byte = 0; byte < a.size(); ++byte) + { + const auto startIdx = byte * 8; + const auto byteValue = a[byte]; + + for (uint8 bit = 0; bit < 8; ++bit) + { + result[startIdx + bit] = static_cast((byteValue & (uint8{ 1 } << bit)) >> bit); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + NdArray result(aShape.rows, aShape.cols * 8); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, unpackbitsLittleEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return unpackbitsLittleEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Unpacks elements of a uint8 array into a binary-valued output array. + /// + /// Each element of a represents a bit - field that should be unpacked into a binary - + /// valued output array.The shape of the output array is either 1 - D(if axis is None) or + /// the same shape as the input array with unpacking done along the axis specified. + /// + /// Numpy Reference: https://numpy.org/doc/stable/reference/generated/numpy.unpackbits.html + /// + /// @param a: An array of uint8 whose elements should be unpacked to bits. + /// @param axis: The dimension over which bit-unpacking is done. None implies unpacking the flattened array. + /// @return NdArray + /// + inline NdArray unpackbitsBigEndian(const NdArray& a, Axis axis = Axis::NONE) + { + switch (axis) + { + case Axis::NONE: + { + NdArray result(1, a.size() * 8); + + for (NdArray::size_type byte = 0; byte < a.size(); ++byte) + { + const auto startIdx = byte * 8; + const auto byteValue = a[byte]; + + for (uint8 bit = 0; bit < 8; ++bit) + { + const auto bitToMask = static_cast(7 - bit); + result[startIdx + bit] = + static_cast((byteValue & (uint8{ 1 } << bitToMask)) >> bitToMask); + } + } + + return result; + } + case Axis::COL: + { + const auto aShape = a.shape(); + NdArray result(aShape.rows, aShape.cols * 8); + const auto resultCSlice = result.cSlice(); + const auto aCSlice = a.cSlice(); + + for (NdArray::size_type row = 0; row < aShape.rows; ++row) + { + result.put(row, resultCSlice, unpackbitsBigEndian(a(row, aCSlice))); + } + + return result; + } + case Axis::ROW: + { + return unpackbitsBigEndian(a.transpose(), Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/unwrap.hpp b/runexamples/cpp/include/NumCpp/Functions/unwrap.hpp new file mode 100644 index 0000000..2e9299a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/unwrap.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Unwrap by changing deltas between values to 2*pi complement. + /// Unwraps to [-pi, pi]. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unwrap.html + /// + /// @param inValue + /// + /// @return value + /// + template + dtype unwrap(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return static_cast(std::atan2(std::sin(inValue), std::cos(inValue))); + } + + //============================================================================ + // Method Description: + /// Unwrap by changing deltas between values to 2*pi complement. + /// Unwraps to [-pi, pi]. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.unwrap.html + /// + /// @param inArray + /// + /// @return NdArray + /// + template + NdArray unwrap(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) noexcept -> dtype { return unwrap(inValue); }); + + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/vander.hpp b/runexamples/cpp/include/NumCpp/Functions/vander.hpp new file mode 100644 index 0000000..72edd36 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/vander.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Functions/fliplr.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/powerf.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Generate a Vandermonde matrix. + /// The columns of the output matrix are powers of the input vector. The order of the powers is determined by the + /// increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector + /// raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named + /// for Alexandre- Theophile Vandermonde. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vander.html + /// + /// @param x: 1-D input array, otherwise the array will be flattened + /// @param n: Number of columns in the output. If N is not specified, a square array is returned (N = len(x)). + /// @param increasing: Order of the powers of the columns. If True, the powers increase from left to right, if False + /// (the default) they are reversed. + /// + /// @return NdArray + /// + template + auto vander(const NdArray& x, uint32 n, bool increasing = true) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray(), uint32{ 0 }))> result(x.size(), n); + for (uint32 row = 0; row < x.size(); ++row) + { + for (uint32 col = 0; col < n; ++col) + { + result(row, col) = std::pow(x[row], col); + } + } + + if (!increasing) + { + return fliplr(result); + } + + return result; + } + + //============================================================================ + // Method Description: + /// Generate a Vandermonde matrix. + /// The columns of the output matrix are powers of the input vector. The order of the powers is determined by the + /// increasing boolean argument. Specifically, when increasing is False, the i-th output column is the input vector + /// raised element-wise to the power of N - i - 1. Such a matrix with a geometric progression in each row is named + /// for Alexandre- Theophile Vandermonde. + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vander.html + /// + /// @param x: 1-D input array, otherwise the array will be flattened + /// @param increasing: Order of the powers of the columns. If True, the powers increase from left to right, if False + /// (the default) they are reversed. + /// + /// @return NdArray + /// + template + auto vander(const NdArray& x, bool increasing = true) + { + return vander(x, x.size(), increasing); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/var.hpp b/runexamples/cpp/include/NumCpp/Functions/var.hpp new file mode 100644 index 0000000..76f70ec --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/var.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/stdev.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.var.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray var(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray stdValues = stdev(inArray, inAxis); + const auto function = [](double& value) -> void { value *= value; }; + + stl_algorithms::for_each(stdValues.begin(), stdValues.end(), function); + return stdValues; + } + + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.var.html + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// + /// @return NdArray + /// + template + NdArray> var(const NdArray>& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray> stdValues = stdev(inArray, inAxis); + const auto function = [](std::complex& value) -> void { value *= value; }; + + stl_algorithms::for_each(stdValues.begin(), stdValues.end(), function); + return stdValues; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/vsplit.hpp b/runexamples/cpp/include/NumCpp/Functions/vsplit.hpp new file mode 100644 index 0000000..0077c5e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/vsplit.hpp @@ -0,0 +1,105 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/split.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Split an array into multiple sub-arrays vertically (row-wise). + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.vsplit.html + /// + /// @param inArray + /// @param indices: the indices to split + /// + /// @return NdArray + /// + template = 0> + std::vector> vsplit(const NdArray& inArray, const Indices& indices) + { + const auto numRows = static_cast(inArray.numRows()); + NdArray uniqueIndices(1, indices.size()); + stl_algorithms::transform(indices.begin(), + indices.end(), + uniqueIndices.begin(), + [numRows](auto index) noexcept -> int32 + { + if constexpr (type_traits::is_ndarray_signed_int_v) + { + if (index < 0) + { + index = std::max(index + numRows, int32{ 0 }); + } + } + if (index > numRows - 1) + { + index = numRows - 1; + } + + return static_cast(index); + }); + uniqueIndices = unique(uniqueIndices); + + std::vector> splits{}; + splits.reserve(uniqueIndices.size() + 1); + + const auto cSlice = inArray.cSlice(); + int32 lowerIdx = 0; + for (const auto index : uniqueIndices) + { + if (index == 0) + { + splits.push_back(NdArray(Shape(0, inArray.numCols()))); + continue; + } + else + { + splits.push_back(inArray(Slice(lowerIdx, index), cSlice)); + } + + lowerIdx = index; + } + + if (lowerIdx < numRows - 1) + { + splits.push_back(inArray(Slice(lowerIdx, numRows), cSlice)); + } + else + { + splits.push_back(inArray(-1, cSlice)); + } + + return splits; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/vstack.hpp b/runexamples/cpp/include/NumCpp/Functions/vstack.hpp new file mode 100644 index 0000000..3756b13 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/vstack.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Functions/row_stack.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Compute the variance along the specified axis. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.vstack.html + /// + /// @param inArrayList: {list} of arrays to stack + /// + /// @return NdArray + /// + template + NdArray vstack(std::initializer_list> inArrayList) + { + return row_stack(inArrayList); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/where.hpp b/runexamples/cpp/include/NumCpp/Functions/where.hpp new file mode 100644 index 0000000..c8e0e54 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/where.hpp @@ -0,0 +1,203 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, const NdArray& inA, const NdArray& inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeA = inA.shape(); + if (shapeA != inB.shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input inA and inB must be the same shapes."); + } + + if (shapeMask != shapeA) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA[idx]; + } + else + { + outArray[idx] = inB[idx]; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, const NdArray& inA, dtype inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeA = inA.shape(); + if (shapeMask != shapeA) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA[idx]; + } + else + { + outArray[idx] = inB; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, dtype inA, const NdArray& inB) + { + const auto shapeMask = inMask.shape(); + const auto shapeB = inB.shape(); + if (shapeMask != shapeB) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the input arrays."); + } + + auto outArray = NdArray(shapeMask); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA; + } + else + { + outArray[idx] = inB[idx]; + } + ++idx; + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// Return elements, either from x or y, depending on the input mask. + /// The output array contains elements of x where mask is True, and + /// elements from y elsewhere. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.where.html + /// + /// @param inMask + /// @param inA + /// @param inB + /// @return NdArray + /// + template + NdArray where(const NdArray& inMask, dtype inA, dtype inB) + { + auto outArray = NdArray(inMask.shape()); + + uint32 idx = 0; + for (auto maskValue : inMask) + { + if (maskValue) + { + outArray[idx] = inA; + } + else + { + outArray[idx] = inB; + } + ++idx; + } + + return outArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/zeros.hpp b/runexamples/cpp/include/NumCpp/Functions/zeros.hpp new file mode 100644 index 0000000..fbc9fbf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/zeros.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/full.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inSquareSize + /// @return NdArray + /// + template + NdArray zeros(uint32 inSquareSize) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inSquareSize, dtype{ 0 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + template + NdArray zeros(uint32 inNumRows, uint32 inNumCols) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inNumRows, inNumCols, dtype{ 0 }); + } + + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros.html + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray zeros(const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return full(inShape, dtype{ 0 }); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Functions/zeros_like.hpp b/runexamples/cpp/include/NumCpp/Functions/zeros_like.hpp new file mode 100644 index 0000000..3a77129 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Functions/zeros_like.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Functions for working with NdArrays +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Return a new array of given shape and type, filled with zeros. + /// + /// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.zeros_like.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray zeros_like(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + returnArray.zeros(); + return returnArray; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing.hpp new file mode 100644 index 0000000..b341424 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing.hpp @@ -0,0 +1,39 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for basic image processing +/// +#pragma once + +#include "NumCpp/ImageProcessing/Centroid.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/ImageProcessing/ClusterMaker.hpp" +#include "NumCpp/ImageProcessing/Pixel.hpp" +#include "NumCpp/ImageProcessing/applyThreshold.hpp" +#include "NumCpp/ImageProcessing/centroidClusters.hpp" +#include "NumCpp/ImageProcessing/clusterPixels.hpp" +#include "NumCpp/ImageProcessing/generateCentroids.hpp" +#include "NumCpp/ImageProcessing/generateThreshold.hpp" +#include "NumCpp/ImageProcessing/windowExceedances.hpp" diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/Centroid.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/Centroid.hpp new file mode 100644 index 0000000..3e0e327 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/Centroid.hpp @@ -0,0 +1,340 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// holds the information for a centroid +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/centerOfMass.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// holds the information for a centroid + template + class Centroid + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + using accumulator_t = typename std::conditional::value, int64, double>::type; + + //============================================================================= + // Description: + /// defualt constructor needed by containers + /// + Centroid() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inCluster + /// + explicit Centroid(const Cluster& inCluster) : + intensity_(inCluster.intensity()), + eod_(inCluster.eod()) + { + centerOfMass(inCluster); + setEllipseProperties(inCluster); + } + + //============================================================================= + // Description: + /// gets the centroid row + /// + /// @return centroid row + /// + [[nodiscard]] double row() const noexcept + { + return row_; + } + + //============================================================================= + // Description: + /// gets the centroid col + /// + /// @return centroid col + /// + [[nodiscard]] double col() const noexcept + { + return col_; + } + + //============================================================================= + // Description: + /// gets the centroid intensity + /// + /// @return centroid intensity + /// + [[nodiscard]] accumulator_t intensity() const noexcept + { + return intensity_; + } + + //============================================================================= + // Description: + /// returns the estimated eod of the centroid + /// + /// @return star id + /// + [[nodiscard]] double eod() const noexcept + { + return eod_; + } + + //============================================================================= + // Description: + /// returns the ellipse semi-major axis a + /// + /// @return a + /// + [[nodiscard]] double a() const noexcept + { + return a_; + } + + //============================================================================= + + // Description: + /// returns the ellipse semi-minor axis b + /// + /// @return b + /// + [[nodiscard]] double b() const noexcept + { + return b_; + } + + //============================================================================= + // Description: + /// returns the ellipse eccentricity + /// + /// @return eccentricity + /// + [[nodiscard]] double eccentricity() const noexcept + { + return eccentricity_; + } + + //============================================================================= + + // Description: + /// returns the ellipse semi-minor axis orientation + /// + /// @return orientation + /// + [[nodiscard]] double orientation() const noexcept + { + return orientation_; + } + + //============================================================================= + // Description: + /// returns the centroid as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "row = " + utils::num2str(row_) + " col = " + utils::num2str(col_) + + " intensity = " + utils::num2str(intensity_) + " eod = " + utils::num2str(eod_) + + " a = " + utils::num2str(a_) + " b = " + utils::num2str(b_) + + " eccentricity = " + utils::num2str(eccentricity_) + + " orientation = " + utils::num2str(orientation_) + '\n'; + + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Centroid object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator==(const Centroid& rhs) const noexcept + { + return (utils::essentiallyEqual(row_, rhs.row_) && utils::essentiallyEqual(col_, rhs.col_) && + utils::essentiallyEqual(intensity_, rhs.intensity_) && utils::essentiallyEqual(eod_, rhs.eod_) && + utils::essentiallyEqual(a_, rhs.a_) && utils::essentiallyEqual(b_, rhs.b_) && + utils::essentiallyEqual(eccentricity_, rhs.eccentricity_) && + utils::essentiallyEqual(orientation_, rhs.orientation_)); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator!=(const Centroid& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// less than operator for std::sort algorithm; + /// NOTE: std::sort sorts in ascending order. Since I want to sort + /// the centroids in descensing order, I am purposefully defining + /// this operator backwards! + /// + /// @param rhs + /// + /// @return bool + /// + bool operator<(const Centroid& rhs) const noexcept + { + return intensity_ < rhs.intensity_ ? false : true; + } + + //============================================================================= + // Description: + /// ostream operator + /// + /// @param inStream + /// @param inCentriod + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Centroid& inCentriod) + { + inStream << inCentriod.str(); + return inStream; + } + + private: + //==================================Attributes================================/// + double row_{ 0. }; + double col_{ 0. }; + accumulator_t intensity_{ 0 }; + double eod_{ 0. }; + /// The ellipse semi-major axis a + double a_{}; + /// The ellipse semi-minor axis b + double b_{}; + /// The centriod eccentricity + double eccentricity_{}; + /// The centriod ellipse orientation in radians. Measured counter-clockwise from +x axis + double orientation_{}; + + //============================================================================= + // Description: + /// center of mass algorithm; + /// WARNING: if both positive and negative values are present in the cluster, + /// it can lead to an undefined COM. + /// + /// @param inCluster + /// + void centerOfMass(const Cluster& inCluster) + { + const Shape clusterShape(inCluster.height(), inCluster.width()); + NdArray clusterArray(clusterShape); + clusterArray.zeros(); + + const uint32 rowMin = inCluster.rowMin(); + const uint32 colMin = inCluster.colMin(); + + for (auto& pixel : inCluster) + { + clusterArray(pixel.row - rowMin, pixel.col - colMin) = pixel.intensity; + } + + const auto rowCol = nc::centerOfMass(clusterArray); + row_ = rowCol.front() + rowMin; + col_ = rowCol.back() + colMin; + } + + //============================================================================= + // Description: + /// Sets the cluster ellipse properties + /// + /// @param inCluster + /// + void setEllipseProperties(const Cluster& inCluster) noexcept + { + constexpr auto two = static_cast(2.); + + auto m20 = static_cast(0.); + auto m02 = static_cast(0.); + auto m11 = static_cast(0.); + + for (typename Cluster::const_iterator iter = inCluster.begin(); iter != inCluster.end(); ++iter) + { + const auto& pixel = *iter; + const double deltaX = pixel.col - col_; + const double deltaY = pixel.row - row_; + + m11 += deltaX * deltaY; + m20 += utils::sqr(deltaX); + m02 += utils::sqr(deltaY); + } + + const auto numPixels = static_cast(inCluster.size()); + m11 /= numPixels; + m20 /= numPixels; + m02 /= numPixels; + + double piece1 = m20 + m02; + piece1 /= two; + + double piece2 = std::sqrt(static_cast(4.) * utils::sqr(m11) + utils::sqr(m20 - m02)); + piece2 /= two; + + const double lambda1 = piece1 - piece2; + const double lambda2 = piece1 + piece2; + + eccentricity_ = std::sqrt(static_cast(1.) - lambda1 / lambda2); + orientation_ = static_cast(-0.5) * std::atan2(two * m11, m20 - m02); + a_ = two * std::sqrt(lambda2); + b_ = two * std::sqrt(lambda1); + } + }; +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/Cluster.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/Cluster.hpp new file mode 100644 index 0000000..8c2eeba --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/Cluster.hpp @@ -0,0 +1,371 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds the information for a cluster of pixels +/// + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Pixel.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// Holds the information for a cluster of pixels + template + class Cluster + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //================================Typedefs=============================== + using const_iterator = typename std::vector>::const_iterator; + using accumulator_t = typename std::conditional::value, int64, double>::type; + + //============================================================================= + // Description: + /// default constructor needed by containers + /// + Cluster() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inClusterId + /// + explicit Cluster(uint32 inClusterId) noexcept : + clusterId_(inClusterId) + { + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator==(const Cluster& rhs) const noexcept + { + if (pixels_.size() != rhs.pixels_.size()) + { + return false; + } + + return stl_algorithms::equal(begin(), end(), rhs.begin()); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + bool operator!=(const Cluster& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// access operator, no bounds checking + /// + /// @param inIndex + /// + /// @return Pixel + /// + const Pixel& operator[](uint32 inIndex) const noexcept + { + return pixels_[inIndex]; + } + + //============================================================================= + // Description: + /// access method with bounds checking + /// + /// @param inIndex + /// + /// @return Pixel + /// + [[nodiscard]] const Pixel& at(uint32 inIndex) const + { + if (inIndex >= pixels_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("index exceeds cluster size."); + } + return pixels_[inIndex]; + } + + //============================================================================= + // Description: + /// returns in iterator to the beginning pixel of the cluster + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return pixels_.cbegin(); + } + + //============================================================================= + // Description: + /// returns in iterator to the 1 past the end pixel of the cluster + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return pixels_.cend(); + } + + //============================================================================= + // Description: + /// returns the number of pixels in the cluster + /// + /// @return number of pixels in the cluster + /// + [[nodiscard]] uint32 size() const noexcept + { + return static_cast(pixels_.size()); + } + + //============================================================================= + // Description: + /// returns the minimum row number of the cluster + /// + /// @return minimum row number of the cluster + /// + [[nodiscard]] uint32 clusterId() const noexcept + { + return clusterId_; + } + + //============================================================================= + // Description: + /// returns the minimum row number of the cluster + /// + /// @return minimum row number of the cluster + /// + [[nodiscard]] uint32 rowMin() const noexcept + { + return rowMin_; + } + + //============================================================================= + // Description: + /// returns the maximum row number of the cluster + /// + /// @return maximum row number of the cluster + /// + [[nodiscard]] uint32 rowMax() const noexcept + { + return rowMax_; + } + + //============================================================================= + // Description: + /// returns the minimum column number of the cluster + /// + /// @return minimum column number of the cluster + /// + [[nodiscard]] uint32 colMin() const noexcept + { + return colMin_; + } + + //============================================================================= + // Description: + /// returns the maximum column number of the cluster + /// + /// @return maximum column number of the cluster + /// + [[nodiscard]] uint32 colMax() const noexcept + { + return colMax_; + } + + //============================================================================= + // Description: + /// returns the number of rows the cluster spans + /// + /// @return number of rows + /// + [[nodiscard]] uint32 height() const noexcept + { + return rowMax_ - rowMin_ + 1; + } + + //============================================================================= + // Description: + /// returns the number of columns the cluster spans + /// + /// @return number of columns + /// + [[nodiscard]] uint32 width() const noexcept + { + return colMax_ - colMin_ + 1; + } + + //============================================================================= + // Description: + /// returns the summed intensity of the cluster + /// + /// @return summed cluster intensity + /// + [[nodiscard]] accumulator_t intensity() const noexcept + { + return intensity_; + } + + //============================================================================= + // Description: + /// returns the intensity of the peak pixel in the cluster + /// + /// @return peak pixel intensity + /// + [[nodiscard]] dtype peakPixelIntensity() const noexcept + { + return peakPixelIntensity_; + } + + //============================================================================= + // Description: + /// returns the cluster estimated energy on detector (EOD) + /// + /// @return eod + /// + [[nodiscard]] double eod() const noexcept + { + return eod_; + } + + //============================================================================= + // Description: + /// adds a pixel to the cluster + /// + /// @param inPixel + /// + void addPixel(const Pixel& inPixel) + { + pixels_.push_back(inPixel); + intensity_ += static_cast(inPixel.intensity); + + // adjust the cluster bounds + rowMin_ = std::min(rowMin_, inPixel.row); + rowMax_ = std::max(rowMax_, inPixel.row); + colMin_ = std::min(colMin_, inPixel.col); + colMax_ = std::max(colMax_, inPixel.col); + peakPixelIntensity_ = std::max(peakPixelIntensity_, inPixel.intensity); + + // calculate the energy on detector estimate + eod_ = static_cast(peakPixelIntensity_) / static_cast(intensity_); + } + + //============================================================================= + // Description: + /// returns a string representation of the cluster + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + std::string out; + uint32 counter = 0; + std::for_each(begin(), + end(), + [&](const Pixel& pixel) + { out += "Pixel " + utils::num2str(counter++) + ":" + pixel.str(); }); + + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Cluster object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// osstream operator + /// + /// @param inStream + /// @param inCluster + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Cluster& inCluster) + { + inStream << inCluster.str(); + return inStream; + } + + private: + //================================Attributes=============================== + /// The cluster id + int32 clusterId_{ -1 }; + /// The pixels that make up the cluster + std::vector> pixels_{}; + /// The bounding box minimum row of the cluster. + uint32 rowMin_{ std::numeric_limits::max() }; // largest possible number + /// The bounding box maximum row of the cluster. + uint32 rowMax_{ 0 }; + /// The bounding box minimum col of the cluster. + uint32 colMin_{ std::numeric_limits::max() }; // largest possible number + /// The bounding box maximum row of the cluster. + uint32 colMax_{ 0 }; + /// The total summed intensity of the pixels in the cluster. + accumulator_t intensity_{ 0 }; + /// The peak pixel intensity of the cluster + dtype peakPixelIntensity_{ 0 }; + /// The minimum pixel count value of the cluster + dtype minPixel{}; + /// The maximum pixel count value of the cluster + dtype maxPixel{}; + /// The cluster energy on detector + double eod_{ 1. }; + }; +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp new file mode 100644 index 0000000..7e9af0b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/ClusterMaker.hpp @@ -0,0 +1,365 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Clusters exceedance data into contiguous groups +/// + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================= + // Class Description: + /// Clusters exceedance data into contiguous groups + template + class ClusterMaker + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //================================Typedefs===================================== + using const_iterator = typename std::vector>::const_iterator; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inXcdArrayPtr: pointer to exceedance array + /// @param inIntensityArrayPtr: pointer to intensity array + /// @param inBorderWidth: border to apply around exceedance pixels post clustering (default 0) + /// + /// @return None + /// + ClusterMaker(const NdArray* const inXcdArrayPtr, + const NdArray* const inIntensityArrayPtr, + uint8 inBorderWidth = 0) : + xcds_(inXcdArrayPtr), + intensities_(inIntensityArrayPtr) + { + if (xcds_->shape() != intensities_->shape()) + { + THROW_INVALID_ARGUMENT_ERROR("input xcd and intensity arrays must be the same shape."); + } + + shape_ = xcds_->shape(); + + // convert the NdArray of booleans to a vector of exceedances + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + if (xcds_->operator()(row, col)) + { + const Pixel thePixel(row, col, intensities_->operator()(row, col)); + xcdsVec_.push_back(thePixel); + } + } + } + + runClusterMaker(); + + for (uint8 i = 0; i < inBorderWidth; ++i) + { + expandClusters(); + } + } + + //============================================================================= + // Description: + /// returns the number of clusters in the frame + /// + /// @return number of clusters + /// + uint32 size() noexcept + { + return static_cast(clusters_.size()); + } + + //============================================================================= + // Description: + /// access operator, no bounds checking + /// + /// @param inIndex + /// + /// @return Cluster + /// + const Cluster& operator[](uint32 inIndex) const noexcept + { + return clusters_[inIndex]; + } + + //============================================================================= + // Description: + /// access method with bounds checking + /// + /// @param inIndex + /// + /// @return Cluster + /// + [[nodiscard]] const Cluster& at(uint32 inIndex) const + { + if (inIndex >= clusters_.size()) + { + THROW_INVALID_ARGUMENT_ERROR("index exceeds cluster size."); + } + return clusters_[inIndex]; + } + + //============================================================================= + // Description: + /// returns in iterator to the beginning cluster of the container + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return clusters_.cbegin(); + } + + //============================================================================= + // Description: + /// returns in iterator to the 1 past the end cluster of the container + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return clusters_.cend(); + } + + private: + //==================================Attributes================================= + const NdArray* const xcds_{}; + const NdArray* const intensities_{}; + std::vector> xcdsVec_{}; + + Shape shape_{}; + + std::vector> clusters_{}; + + //============================================================================= + // Description: + /// checks that the input row and column have not fallen off of the edge + /// + /// @param inRow + /// @param inCol + /// + /// @return returns a pixel object clipped to the image boundaries + /// + Pixel makePixel(int32 inRow, int32 inCol) noexcept + { + // Make sure that on the edges after i've added or subtracted 1 from the row and col that + // i haven't gone over the edge + const uint32 row = std::min(static_cast(std::max(inRow, 0)), shape_.rows - 1); + const uint32 col = std::min(static_cast(std::max(inCol, 0)), shape_.cols - 1); + const dtype intensity = intensities_->operator()(row, col); + + return Pixel(row, col, intensity); + } + + //============================================================================= + // Description: + /// finds all of the neighboring pixels to the input pixel + /// + /// @param inPixel + /// @param outNeighbors + /// @return None + /// + void findNeighbors(const Pixel& inPixel, std::set>& outNeighbors) + { + // using a set will auto take care of adding duplicate pixels on the edges + + // the 8 surrounding neighbors + const auto row = static_cast(inPixel.row); + const auto col = static_cast(inPixel.col); + + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col)); + outNeighbors.insert(outNeighbors.end(), makePixel(row - 1, col + 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row, col + 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col - 1)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col)); + outNeighbors.insert(outNeighbors.end(), makePixel(row + 1, col + 1)); + } + + //============================================================================= + // Description: + /// finds all of the neighboring pixels to the input pixel that are NOT exceedances + /// + /// @param inPixel + /// @param outNeighbors + /// + /// @return vector of non exceedance neighboring pixels + /// + void findNeighborNotXcds(const Pixel& inPixel, std::vector>& outNeighbors) + { + std::set> neighbors; + findNeighbors(inPixel, neighbors); + + // check if the neighboring pixels are exceedances and insert into the xcd vector + for (auto& pixel : neighbors) + { + if (!xcds_->operator()(pixel.row, pixel.col)) + { + outNeighbors.push_back(pixel); + } + } + } + + //============================================================================= + // Description: + /// finds the pixel index of neighboring pixels + /// + /// @param inPixel + /// @param outNeighbors + /// + /// @return vector of neighboring pixel indices + /// + void findNeighborXcds(const Pixel& inPixel, std::vector& outNeighbors) + { + std::set> neighbors; + findNeighbors(inPixel, neighbors); + std::vector> neighborXcds; + + // check if the neighboring pixels are exceedances and insert into the xcd vector + for (auto& pixel : neighbors) + { + if (xcds_->operator()(pixel.row, pixel.col)) + { + neighborXcds.push_back(pixel); + } + } + + // loop through the neighbors and find the cooresponding index into exceedances_ + for (auto& pixel : neighborXcds) + { + auto theExceedanceIter = std::find(xcdsVec_.begin(), xcdsVec_.end(), pixel); + outNeighbors.push_back(static_cast(theExceedanceIter - xcdsVec_.begin())); + } + } + + //============================================================================= + // Description: + /// workhorse method that performs the clustering algorithm + /// + void runClusterMaker() + { + uint32 clusterId = 0; + + for (auto& currentPixel : xcdsVec_) + { + // not already visited + if (currentPixel.clusterId == -1) + { + Cluster newCluster(clusterId); // a new cluster + currentPixel.clusterId = clusterId; + newCluster.addPixel(currentPixel); // assign pixel to cluster + + // get the neighbors + std::vector neighborIds; + findNeighborXcds(currentPixel, neighborIds); + if (neighborIds.empty()) + { + clusters_.push_back(newCluster); + ++clusterId; + continue; + } + + // loop through the neighbors + for (uint32 neighborsIdx = 0; neighborsIdx < neighborIds.size(); ++neighborsIdx) + { + Pixel& currentNeighborPixel = xcdsVec_[neighborIds[neighborsIdx]]; + + // go to neighbors + std::vector newNeighborIds; + findNeighborXcds(currentNeighborPixel, newNeighborIds); + + // loop through the new neighbors and add them to neighbors + for (auto newNeighborId : newNeighborIds) + { + // not already in neighbors + if (std::find(neighborIds.begin(), neighborIds.end(), newNeighborId) == neighborIds.end()) + { + neighborIds.push_back(newNeighborId); + } + } + + // not already assigned to a cluster + if (currentNeighborPixel.clusterId == -1) + { + currentNeighborPixel.clusterId = clusterId; + newCluster.addPixel(currentNeighborPixel); + } + } + + clusters_.push_back(std::move(newCluster)); + ++clusterId; + } + } + } + + //============================================================================= + // Description: + /// 3x3 dialates the clusters + /// + void expandClusters() + { + // loop through the clusters + for (auto& theCluster : clusters_) + { + // loop through the pixels of the cluster + for (auto& thePixel : theCluster) + { + std::vector> neighborsNotXcds; + findNeighborNotXcds(thePixel, neighborsNotXcds); + + // loop through the neighbors and if they haven't already been added to the cluster, add them + for (auto& newPixel : neighborsNotXcds) + { + if (std::find(theCluster.begin(), theCluster.end(), newPixel) == theCluster.end()) + { + theCluster.addPixel(newPixel); + } + } + } + } + } + }; +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/Pixel.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/Pixel.hpp new file mode 100644 index 0000000..a326e35 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/Pixel.hpp @@ -0,0 +1,166 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds the information for a single pixel +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc::imageProcessing +{ + //================================================================================ + // Class Description: + /// Holds the information for a single pixel + template + class Pixel + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //==================================Attributes================================ + mutable int32 clusterId{ -1 }; + uint32 row{ 0 }; + uint32 col{ 0 }; + dtype intensity{ 0 }; + + //============================================================================= + // Description: + /// defualt constructor needed by containers + /// + constexpr Pixel() = default; + + //============================================================================= + // Description: + /// constructor + /// + /// @param inRow: pixel row + /// @param inCol: pixel column + /// @param inIntensity: pixel intensity + /// + constexpr Pixel(uint32 inRow, uint32 inCol, dtype inIntensity) noexcept : + row(inRow), + col(inCol), + intensity(inIntensity) + { + } + + //============================================================================= + // Description: + /// equality operator + /// + /// @param rhs + /// + /// @return bool + /// + constexpr bool operator==(const Pixel& rhs) const noexcept + { + return utils::essentiallyEqual(row, rhs.row) && utils::essentiallyEqual(col, rhs.col) && + utils::essentiallyEqual(intensity, rhs.intensity); + } + + //============================================================================= + // Description: + /// not equality operator + /// + /// @param rhs + /// + /// @return bool + /// + constexpr bool operator!=(const Pixel& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================= + // Description: + /// less than operator for std::sort algorithm and std::set<>; + /// NOTE: std::sort sorts in ascending order. Since I want to sort + /// the centroids in descensing order, I am purposefully defining + /// this operator backwards! + /// + /// @param rhs + /// + /// @return bool + /// + bool operator<(const Pixel& rhs) const noexcept + { + if (row < rhs.row) + { + return true; + } + if (row == rhs.row) + { + return static_cast(col < rhs.col); + } + + return false; + } + + //============================================================================= + // Description: + /// returns the pixel information as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string out = "row = " + utils::num2str(row) + " col = " + utils::num2str(col); + out += " intensity = " + utils::num2str(intensity) + '\n'; + return out; + } + + //============================================================================ + /// Method Description: + /// prints the Pixel object to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================= + // Description: + /// osstream operator + /// + /// @param inStream + /// @param inPixel + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inStream, const Pixel& inPixel) + { + inStream << inPixel.str(); + return inStream; + } + }; +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp new file mode 100644 index 0000000..769cbaf --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/applyThreshold.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Applies a threshold to an image +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Applies a threshold to an image + /// + /// @param inImageArray + /// @param inThreshold + /// @return NdArray of booleans of pixels that exceeded the threshold + /// + template + NdArray applyThreshold(const NdArray& inImageArray, dtype inThreshold) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return inImageArray > inThreshold; + } +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp new file mode 100644 index 0000000..82960ff --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/centroidClusters.hpp @@ -0,0 +1,60 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Center of Mass centroids clusters +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/ImageProcessing/Centroid.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Center of Mass centroids clusters + /// + /// @param inClusters + /// @return std::vector + /// + template + std::vector> centroidClusters(const std::vector>& inClusters) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::vector> centroids(inClusters.size()); + stl_algorithms::transform(inClusters.begin(), + inClusters.end(), + centroids.begin(), + [](const auto& cluster) -> Centroid { return Centroid(cluster); }); + return centroids; + } +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp new file mode 100644 index 0000000..99c2399 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/clusterPixels.hpp @@ -0,0 +1,59 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Clusters exceedance pixels from an image +/// + +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/Cluster.hpp" +#include "NumCpp/ImageProcessing/ClusterMaker.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Clusters exceedance pixels from an image + /// + /// @param inImageArray + /// @param inExceedances + /// @param inBorderWidth: border to apply around exceedance pixels post clustering (default 0) + /// @return std::vector + /// + template + std::vector> + clusterPixels(const NdArray& inImageArray, const NdArray& inExceedances, uint8 inBorderWidth = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + ClusterMaker clusterMaker(&inExceedances, &inImageArray, inBorderWidth); + return std::vector>(clusterMaker.begin(), clusterMaker.end()); + } +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp new file mode 100644 index 0000000..ec5157e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/generateCentroids.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Generates a list of centroids givin an input exceedance rate +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/ImageProcessing/applyThreshold.hpp" +#include "NumCpp/ImageProcessing/centroidClusters.hpp" +#include "NumCpp/ImageProcessing/clusterPixels.hpp" +#include "NumCpp/ImageProcessing/generateThreshold.hpp" +#include "NumCpp/ImageProcessing/windowExceedances.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Generates a list of centroids givin an input exceedance + /// rate + /// + /// @param inImageArray + /// @param inRate: exceedance rate + /// @param inWindowType: (string "pre", or "post" for where to apply the exceedance windowing) + /// @param inBorderWidth: border to apply (default 0) + /// @return std::vector + /// + template + std::vector> generateCentroids(const NdArray& inImageArray, + double inRate, + const std::string& inWindowType, + uint8 inBorderWidth = 0) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + uint8 borderWidthPre = 0; + uint8 borderWidthPost = 0; + if (inWindowType == "pre") + { + borderWidthPre = inBorderWidth; + } + else if (inWindowType == "post") + { + borderWidthPost = inBorderWidth; + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input window type options are ['pre', 'post']"); + } + + // generate the threshold + dtype threshold = generateThreshold(inImageArray, inRate); + + // apply the threshold to get xcds + NdArray xcds = applyThreshold(inImageArray, threshold); + + // window around the xcds + if (borderWidthPre > 0) + { + xcds = windowExceedances(xcds, borderWidthPre); + } + + // cluster the exceedances + std::vector> clusters = clusterPixels(inImageArray, xcds, borderWidthPost); + + // centroid the clusters + return centroidClusters(clusters); + } +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp new file mode 100644 index 0000000..1113b95 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/generateThreshold.hpp @@ -0,0 +1,142 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Generates a threshold +/// + +#pragma once + +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Calculates a threshold such that the input rate of pixels + /// exceeds the threshold. Really should only be used for integer + /// input array values. If using floating point data, user beware... + /// + /// @param inImageArray + /// @param inRate + /// @return dtype + /// + template + dtype generateThreshold(const NdArray& inImageArray, double inRate) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inRate < 0. || inRate > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input rate must be of the range [0, 1]"); + } + + // first build a histogram + auto minValue = static_cast(std::floor(inImageArray.min().item())); + auto maxValue = static_cast(std::floor(inImageArray.max().item())); + + if (utils::essentiallyEqual(inRate, 0.)) + { + return static_cast(maxValue); + } + + if (utils::essentiallyEqual(inRate, 1.)) + { + if (DtypeInfo::isSigned()) + { + return static_cast(minValue - 1); + } + + return dtype{ 0 }; + } + + const auto histSize = static_cast(maxValue - minValue + 1); + + NdArray histogram(1, histSize); + histogram.zeros(); + for (auto intensity : inImageArray) + { + const auto bin = static_cast(static_cast(std::floor(intensity)) - minValue); + ++histogram[bin]; + } + + // integrate the normalized histogram from right to left to make a survival function (1 - CDF) + const auto dNumPixels = static_cast(inImageArray.size()); + NdArray survivalFunction(1, histSize + 1); + survivalFunction[-1] = 0.; + for (int32 i = histSize - 1; i > -1; --i) + { + double histValue = histogram[i] / dNumPixels; + survivalFunction[i] = survivalFunction[i + 1] + histValue; + } + + // binary search through the survival function to find the rate + uint32 indexLow = 0; + uint32 indexHigh = histSize - 1; + uint32 index = indexHigh / 2; // integer division + + constexpr bool keepGoing = true; + while (keepGoing) + { + const double value = survivalFunction[index]; + if (value < inRate) + { + indexHigh = index; + } + else if (value > inRate) + { + indexLow = index; + } + else + { + const int32 thresh = static_cast(index) + minValue - 1; + if (DtypeInfo::isSigned()) + { + return static_cast(thresh); + } + + return thresh < 0 ? 0 : static_cast(thresh); + } + + if (indexHigh - indexLow < 2) + { + return static_cast(static_cast(indexHigh) + minValue - 1); + } + + index = indexLow + (indexHigh - indexLow) / 2; + } + + // shouldn't ever get here but stop the compiler from throwing a warning + return static_cast(histSize - 1); + } + +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp b/runexamples/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp new file mode 100644 index 0000000..2ce9f50 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/ImageProcessing/windowExceedances.hpp @@ -0,0 +1,78 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Window expand around exceedance pixels +/// + +#pragma once + +#include + +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::imageProcessing +{ + //============================================================================ + // Method Description: + /// Window expand around exceedance pixels + /// + /// @param inExceedances + /// @param inBorderWidth + /// @return NdArray + /// + inline NdArray windowExceedances(const NdArray& inExceedances, uint8 inBorderWidth) noexcept + { + // not the most efficient way to do things, but the easist... + NdArray xcds(inExceedances); + const Shape inShape = xcds.shape(); + for (uint8 border = 0; border < inBorderWidth; ++border) + { + for (int32 row = 0; row < static_cast(inShape.rows); ++row) + { + for (int32 col = 0; col < static_cast(inShape.cols); ++col) + { + if (inExceedances(row, col)) + { + xcds(std::max(row - 1, 0), std::max(col - 1, 0)) = true; + xcds(std::max(row - 1, 0), col) = true; + xcds(std::max(row - 1, 0), std::min(col + 1, inShape.cols - 1)) = true; + + xcds(row, std::max(col - 1, 0)) = true; + xcds(row, std::min(col + 1, inShape.cols - 1)) = true; + + xcds(std::min(row + 1, inShape.rows - 1), std::max(col - 1, 0)) = true; + xcds(std::min(row + 1, inShape.rows - 1), col) = true; + xcds(std::min(row + 1, inShape.rows - 1), std::min(col + 1, inShape.cols - 1)) = + true; + } + } + } + } + + return xcds; + } +} // namespace nc::imageProcessing diff --git a/runexamples/cpp/include/NumCpp/Integrate.hpp b/runexamples/cpp/include/NumCpp/Integrate.hpp new file mode 100644 index 0000000..6c4730b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Integrate.hpp @@ -0,0 +1,33 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration routines +/// +#pragma once + +#include "NumCpp/Integrate/gauss_legendre.hpp" +#include "NumCpp/Integrate/romberg.hpp" +#include "NumCpp/Integrate/simpson.hpp" +#include "NumCpp/Integrate/trapazoidal.hpp" diff --git a/runexamples/cpp/include/NumCpp/Integrate/gauss_legendre.hpp b/runexamples/cpp/include/NumCpp/Integrate/gauss_legendre.hpp new file mode 100644 index 0000000..dc5b5f1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Integrate/gauss_legendre.hpp @@ -0,0 +1,201 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/25/numerical-methods-in-c-part-2-gauss-legendre-integration/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Class Description: + /// Legendre Polynomial class + /// + class LegendrePolynomial + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param numIterations: the number of iterations to perform + /// + explicit LegendrePolynomial(const uint32 numIterations) noexcept : + numIterations_(numIterations), + weight_(numIterations + 1), + root_(numIterations + 1) + { + calculateWeightAndRoot(); + } + + //============================================================================ + // Method Description: + /// Returns the weights vector + /// + /// @return weights vector + /// + [[nodiscard]] const std::vector& getWeight() const noexcept + { + return weight_; + } + + //============================================================================ + // Method Description: + /// Returns the roots vector + /// + /// @return roots vector + /// + [[nodiscard]] const std::vector& getRoot() const noexcept + { + return root_; + } + + private: + //============================================================================ + // Class Description: + /// Simple class to hold the results + /// + struct Result + { + double value{ 0. }; + double derivative{ 0. }; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param val: the value + /// @param deriv: the derivative + /// + Result(const double val, const double deriv) noexcept : + value(val), + derivative(deriv) + { + } + }; + + //============================================================================ + // Method Description: + /// Calculates the weights and roots vectors + /// + void calculateWeightAndRoot() noexcept + { + const auto numIterationsDouble = static_cast(numIterations_); + for (uint32 step = 0; step <= numIterations_; ++step) + { + double root = + std::cos(constants::pi * (static_cast(step) - 0.25) / (numIterationsDouble + 0.5)); + Result result = calculatePolynomialValueAndDerivative(root); + + double newtonRaphsonRatio; + do + { + newtonRaphsonRatio = result.value / result.derivative; + root -= newtonRaphsonRatio; + result = calculatePolynomialValueAndDerivative(root); + } while (std::fabs(newtonRaphsonRatio) > EPSILON); + + root_[step] = root; + weight_[step] = 2. / ((1. - utils::sqr(root)) * result.derivative * result.derivative); + } + } + + //============================================================================ + // Method Description: + /// Calculates the weights and roots vectors + /// + /// @param x + /// @return Result + /// + Result calculatePolynomialValueAndDerivative(const double x) noexcept + { + Result result(x, 0.); + + double value_minus_1 = 1.; + const double f = 1. / (utils::sqr(x) - 1.); + for (uint32 step = 2; step <= numIterations_; ++step) + { + const auto stepDouble = static_cast(step); + const double value = + ((2. * stepDouble - 1.) * x * result.value - (stepDouble - 1.) * value_minus_1) / stepDouble; + result.derivative = stepDouble * f * (x * value - result.value); + + value_minus_1 = result.value; + result.value = value; + } + + return result; + } + + //===================================Attributes============================== + const double EPSILON{ 1e-15 }; + + const uint32 numIterations_{}; + std::vector weight_{}; + std::vector root_{}; + }; + + //============================================================================ + // Method Description: + /// Performs Gauss-Legendre integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of iterations to perform + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double + gauss_legendre(const double low, const double high, const uint32 n, const std::function& f) + { + const LegendrePolynomial legendrePolynomial(n); + const std::vector& weight = legendrePolynomial.getWeight(); + const std::vector& root = legendrePolynomial.getRoot(); + + const double width = 0.5 * (high - low); + const double mean = 0.5 * (low + high); + + double gaussLegendre = 0.; + for (uint32 step = 1; step <= n; ++step) + { + gaussLegendre += weight[step] * f(width * root[step] + mean); + } + + return gaussLegendre * width; + } +} // namespace nc::integrate diff --git a/runexamples/cpp/include/NumCpp/Integrate/romberg.hpp b/runexamples/cpp/include/NumCpp/Integrate/romberg.hpp new file mode 100644 index 0000000..26a0ca6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Integrate/romberg.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Integrate/trapazoidal.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes Romberg integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of iterations + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double romberg(const double low, const double high, const uint8 n, const std::function& f) + { + NdArray rombergIntegral(n); + + // R(0,0) Start with trapezoidal integration with N = 1 + rombergIntegral(0, 0) = trapazoidal(low, high, 1, f); + + double h = high - low; + for (uint8 step = 1; step < n; step++) + { + h *= 0.5; + + // R(step, 0) Improve trapezoidal integration with decreasing h + double trapezoidal_integration = 0.; + const uint32 stepEnd = utils::power(2, step - 1); + for (uint32 tzStep = 1; tzStep <= stepEnd; ++tzStep) + { + const double deltaX = (2. * static_cast(tzStep - 1)) * h; + trapezoidal_integration += f(low + deltaX); + } + + rombergIntegral(step, 0) = 0.5 * rombergIntegral(step - 1, 0); + rombergIntegral(step, 0) += trapezoidal_integration * h; + + // R(m,n) Romberg integration with R(m,1) -> Simpson rule, R(m,2) -> Boole's rule + for (uint8 rbStep = 1; rbStep <= step; ++rbStep) + { + const double k = utils::power(4, rbStep); + rombergIntegral(step, rbStep) = k * rombergIntegral(step, rbStep - 1); + rombergIntegral(step, rbStep) -= rombergIntegral(step - 1, rbStep - 1); + rombergIntegral(step, rbStep) /= (k - 1.); + } + } + + return rombergIntegral.back(); + } +} // namespace nc::integrate diff --git a/runexamples/cpp/include/NumCpp/Integrate/simpson.hpp b/runexamples/cpp/include/NumCpp/Integrate/simpson.hpp new file mode 100644 index 0000000..ab65506 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Integrate/simpson.hpp @@ -0,0 +1,67 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes Simpson integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of subdivisions + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double + simpson(const double low, const double high, const uint32 n, const std::function& f) noexcept + { + const double width = (high - low) / static_cast(n); + + double simpson_integral = 0.; + for (uint32 step = 0; step < n; ++step) + { + const double x1 = low + static_cast(step) * width; + const double x2 = low + static_cast(step + 1) * width; + + simpson_integral += (x2 - x1) / 6. * (f(x1) + 4. * f(0.5 * (x1 + x2)) + f(x2)); + } + + return simpson_integral; + } +} // namespace nc::integrate diff --git a/runexamples/cpp/include/NumCpp/Integrate/trapazoidal.hpp b/runexamples/cpp/include/NumCpp/Integrate/trapazoidal.hpp new file mode 100644 index 0000000..6cd98d3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Integrate/trapazoidal.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Numerical Integration +/// +/// Code modified under MIT license from https://github.com/Ben1980/numericalIntegration +/// as posted in https://thoughts-on-coding.com/2019/04/17/numerical-methods-in-c-part-1-newton-cotes-integration/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Types.hpp" + +namespace nc::integrate +{ + //============================================================================ + // Method Description: + /// Performs Newton-Cotes trapazoidal integration of the input function + /// + /// @param low: the lower bound of the integration + /// @param high: the upper bound of the integration + /// @param n: the number of subdivisions + /// @param f: the function to integrate over + /// + /// @return double + /// + inline double trapazoidal(const double low, + const double high, + const uint32 n, + const std::function& f) noexcept + { + const double width = (high - low) / static_cast(n); + + double trapezoidal_integral = 0.; + for (uint32 step = 0; step < n; ++step) + { + const double x1 = low + static_cast(step) * width; + const double x2 = low + static_cast(step + 1) * width; + + trapezoidal_integral += 0.5 * (x2 - x1) * (f(x1) + f(x2)); + } + + return trapezoidal_integral; + } +} // namespace nc::integrate diff --git a/runexamples/cpp/include/NumCpp/Linalg.hpp b/runexamples/cpp/include/NumCpp/Linalg.hpp new file mode 100644 index 0000000..dc3342b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg.hpp @@ -0,0 +1,42 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Module for doing linear algebra operations +/// +#pragma once + +#include "NumCpp/Linalg/cholesky.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/Linalg/gaussNewtonNlls.hpp" +#include "NumCpp/Linalg/hat.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/Linalg/lstsq.hpp" +#include "NumCpp/Linalg/lu_decomposition.hpp" +#include "NumCpp/Linalg/matrix_power.hpp" +#include "NumCpp/Linalg/multi_dot.hpp" +#include "NumCpp/Linalg/pinv.hpp" +#include "NumCpp/Linalg/pivotLU_decomposition.hpp" +#include "NumCpp/Linalg/solve.hpp" +#include "NumCpp/Linalg/svd.hpp" diff --git a/runexamples/cpp/include/NumCpp/Linalg/cholesky.hpp b/runexamples/cpp/include/NumCpp/Linalg/cholesky.hpp new file mode 100644 index 0000000..92d7192 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/cholesky.hpp @@ -0,0 +1,100 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix cholesky decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix cholesky decomposition A = L * L.transpose() + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.cholesky.html#numpy.linalg.cholesky + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return NdArray of the decomposed L matrix + /// + template + NdArray cholesky(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + auto lMatrix = inMatrix.template astype(); + + for (uint32 row = 0; row < shape.rows; ++row) + { + for (uint32 col = row + 1; col < shape.cols; ++col) + { + lMatrix(row, col) = 0.; + } + } + + for (uint32 k = 0; k < shape.cols; ++k) + { + const double& a_kk = lMatrix(k, k); + + if (a_kk > 0.) + { + lMatrix(k, k) = std::sqrt(a_kk); + + for (uint32 i = k + 1; i < shape.rows; ++i) + { + lMatrix(i, k) /= lMatrix(k, k); + + for (uint32 j = k + 1; j <= i; ++j) + { + lMatrix(i, j) -= lMatrix(i, k) * lMatrix(j, k); + } + } + } + else + { + THROW_RUNTIME_ERROR("Matrix is not positive definite."); + } + } + + return lMatrix; + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/det.hpp b/runexamples/cpp/include/NumCpp/Linalg/det.hpp new file mode 100644 index 0000000..5fe0458 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/det.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix determinant. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + namespace detail + { + //============================================================================ + // Method Description: + /// matrix determinant. + /// + /// @param inArray + /// @param order + /// @return matrix determinant + /// + template + auto det(const NdArray& inArray, uint32 order) + -> std::conditional_t, int64, double> + { + STATIC_ASSERT_ARITHMETIC(dtype); + + using ReturnType = std::conditional_t, int64, double>; + + if (order == 1) + { + return static_cast(inArray.front()); + } + + if (order == 2) + { + return static_cast(inArray(0, 0)) * static_cast(inArray(1, 1)) - + static_cast(inArray(0, 1)) * static_cast(inArray(1, 0)); + } + + if (order == 3) + { + const auto aei = static_cast(inArray(0, 0)) * static_cast(inArray(1, 1)) * + static_cast(inArray(2, 2)); + const auto bfg = static_cast(inArray(0, 1)) * static_cast(inArray(1, 2)) * + static_cast(inArray(2, 0)); + const auto cdh = static_cast(inArray(0, 2)) * static_cast(inArray(1, 0)) * + static_cast(inArray(2, 1)); + const auto ceg = static_cast(inArray(0, 2)) * static_cast(inArray(1, 1)) * + static_cast(inArray(2, 0)); + const auto bdi = static_cast(inArray(0, 1)) * static_cast(inArray(1, 0)) * + static_cast(inArray(2, 2)); + const auto afh = static_cast(inArray(0, 0)) * static_cast(inArray(1, 2)) * + static_cast(inArray(2, 1)); + + return aei + bfg + cdh - ceg - bdi - afh; + } + + ReturnType determinant = 0; + ReturnType sign = 1; + NdArray submat(order - 1); + + for (uint32 c = 0; c < order; ++c) + { + uint32 subi = 0; + for (uint32 i = 1; i < order; ++i) + { + uint32 subj = 0; + for (uint32 j = 0; j < order; ++j) + { + if (j == c) + { + continue; + } + + submat(subi, subj++) = inArray(i, j); + } + ++subi; + } + + determinant += (sign * static_cast(inArray(0, c)) * det(submat, order - 1)); + sign *= -1; + } + + return determinant; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// matrix determinant. + /// NOTE: can get verrrrry slow for large matrices (order > 10) + /// + /// SciPy Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.det.html#scipy.linalg.det + /// + /// @param inArray + /// @return matrix determinant + /// + template + auto det(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const Shape inShape = inArray.shape(); + if (!inShape.issquare()) + { + THROW_INVALID_ARGUMENT_ERROR("input array must be square."); + } + + return detail::det(inArray, inShape.rows); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp b/runexamples/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp new file mode 100644 index 0000000..07901b5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/gaussNewtonNlls.hpp @@ -0,0 +1,134 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// The Gauss�Newton algorithm is used to solve non-linear least squares problems. +/// It is a modification of Newton's method for finding a minimum of a function. +/// +/// https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/rms.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// The Gauss�Newton algorithm is used to solve non-linear least squares problems. + /// It is a modification of Newton's method for finding a minimum of a function. + /// https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm + /// + /// @param numIterations: the number of iterations to perform + /// @param coordinates: the coordinate values. The shape needs to be [n x d], where d is + /// the number of diminsions of the fit function (f(x) is one dimensional, + /// f(x, y) is two dimensions, etc), and n is the number of observations + /// that are being fit to. + /// @param measurements: the measured values that are being fit + /// @param function: a std::function of the function that is being fit. The function takes as + /// inputs an NdArray of a single set of the coordinate values, and an NdArray + /// of the current values of the fit parameters + /// @param derivatives: array of std::functions to calculate the function + /// derivatives. The function that is being fit. The function takes as + /// inputs an NdArray of a single set of the coordinate values, and an NdArray + /// of the current values of the fit parameters + /// @param initialGuess: the initial guess of the parameters to be solved for + /// + /// @return std::pair of NdArray of solved parameter values, and rms of the residuals value + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + std::pair, double> + gaussNewtonNlls(const uint32 numIterations, + const NdArray& coordinates, + const NdArray& measurements, + const std::function&, const NdArray&)>& function, + const std::array&, const NdArray&)>, + sizeof...(Params)>& derivatives, + Params... initialGuess) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto coordinatesShape = coordinates.shape(); + + if (coordinatesShape.rows != measurements.size()) + { + THROW_INVALID_ARGUMENT_ERROR("coordinates number of rows, and measurements size must be the same."); + } + + NdArray beta = NdArray({ initialGuess... }).template astype().transpose(); + NdArray residuals(coordinatesShape.rows, 1); + NdArray jacobian(coordinatesShape.rows, sizeof...(Params)); + + const auto colSlice = coordinates.cSlice(); + for (uint32 iteration = 1; iteration <= numIterations; ++iteration) + { + for (uint32 measIdx = 0; measIdx < coordinatesShape.rows; ++measIdx) + { + const auto coordinate = coordinates(measIdx, colSlice); + + residuals[measIdx] = + static_cast(measurements[measIdx]) - static_cast(function(coordinate, beta)); + + for (uint32 paramIdx = 0; paramIdx < sizeof...(Params); ++paramIdx) + { + const auto& derivative = derivatives[paramIdx]; + jacobian(measIdx, paramIdx) = static_cast(derivative(coordinate, beta)); + } + } + + // perform the gauss-newton linear algebra + const auto jacobianT = jacobian.transpose(); + const auto jacobianPsuedoInverse = linalg::inv(jacobianT.dot(jacobian)); + const auto intermediate = jacobianPsuedoInverse.dot(jacobianT); + const auto deltaBeta = intermediate.dot(residuals); + beta += deltaBeta; + } + + // calculate the final rms of the residuals + for (uint32 measIdx = 0; measIdx < coordinatesShape.rows; ++measIdx) + { + const auto coordinate = coordinates(measIdx, colSlice); + + residuals[measIdx] = + static_cast(measurements[measIdx]) - static_cast(function(coordinate, beta)); + } + + return std::make_pair(beta.flatten(), rms(residuals).item()); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/hat.hpp b/runexamples/cpp/include/NumCpp/Linalg/hat.hpp new file mode 100644 index 0000000..f68f3f6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/hat.hpp @@ -0,0 +1,98 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// vector hat operator +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inX + /// @param inY + /// @param inZ + /// @return 3x3 NdArray + /// + template + NdArray hat(dtype inX, dtype inY, dtype inZ) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(3); + returnArray(0, 0) = 0.; + returnArray(0, 1) = -inZ; + returnArray(0, 2) = inY; + returnArray(1, 0) = inZ; + returnArray(1, 1) = 0.; + returnArray(1, 2) = -inX; + returnArray(2, 0) = -inY; + returnArray(2, 1) = inX; + returnArray(2, 2) = 0.; + + return returnArray; + } + + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inVec (3x1, or 1x3 cartesian vector) + /// @return 3x3 NdArray + /// + template + NdArray hat(const NdArray& inVec) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inVec.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be a length 3 cartesian vector."); + } + + return hat(inVec[0], inVec[1], inVec[2]); + } + + //============================================================================ + // Method Description: + /// vector hat operator + /// + /// @param inVec + /// @return 3x3 NdArray + /// + inline NdArray hat(const Vec3& inVec) + { + return hat(inVec.x, inVec.y, inVec.z); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/inv.hpp b/runexamples/cpp/include/NumCpp/Linalg/inv.hpp new file mode 100644 index 0000000..8063563 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/inv.hpp @@ -0,0 +1,132 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix inverse +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix inverse + /// + /// SciPy Reference: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.inv.html#scipy.linalg.inv + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray inv(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + if (inShape.rows != inShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input array must be square."); + } + + NdArray inArrayDouble = inArray.template astype(); + NdArray incidence = nc::zeros(inShape); + + for (uint32 k = 0; k < inShape.rows - 1; ++k) + { + if (utils::essentiallyEqual(inArrayDouble(k, k), 0.)) + { + uint32 l = k; + while (l < inShape.cols && utils::essentiallyEqual(inArrayDouble(k, l), 0.)) + { + ++l; + } + + inArrayDouble.swapRows(k, l); + incidence(k, k) = 1; + incidence(k, l) = 1; + } + } + + NdArray result(inShape); + + for (uint32 k = 0; k < inShape.rows; ++k) + { + result(k, k) = -1. / inArrayDouble(k, k); + for (uint32 i = 0; i < inShape.rows; ++i) + { + for (uint32 j = 0; j < inShape.cols; ++j) + { + if ((i - k) && (j - k)) + { + result(i, j) = inArrayDouble(i, j) + inArrayDouble(k, j) * inArrayDouble(i, k) * result(k, k); + } + else if ((i - k) && !(j - k)) + { + result(i, k) = inArrayDouble(i, k) * result(k, k); + } + else if (!(i - k) && (j - k)) + { + result(k, j) = inArrayDouble(k, j) * result(k, k); + } + } + } + + inArrayDouble = result; + } + + result *= -1.; + + for (int i = static_cast(inShape.rows) - 1; i >= 0; --i) + { + if (incidence(i, i) != 1) + { + continue; + } + + int k = 0; + for (; k < static_cast(inShape.cols); ++k) + { + if ((k - i) && incidence(i, k) != 0) + { + result.swapCols(i, k); + break; + } + } + } + + return result; + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/lstsq.hpp b/runexamples/cpp/include/NumCpp/Linalg/lstsq.hpp new file mode 100644 index 0000000..2bf7956 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/lstsq.hpp @@ -0,0 +1,66 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// linear least squares +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Linalg/svd/SVDClass.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Solves the equation a x = b by computing a vector x + /// that minimizes the Euclidean 2-norm || b - a x ||^2. + /// The equation may be under-, well-, or over- determined + /// (i.e., the number of linearly independent rows of a can + /// be less than, equal to, or greater than its number of + /// linearly independent columns). If a is square and of + /// full rank, then x (but for round-off error) is the + /// "exact" solution of the equation. + /// + /// SciPy Reference: + /// https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html#scipy.linalg.lstsq + /// + /// @param inA: coefficient matrix + /// @param inB: Ordinate or "dependent variable" values + /// @param inTolerance (default 1e-12) + /// + /// @return NdArray + /// + template + NdArray lstsq(const NdArray& inA, const NdArray& inB, double inTolerance = 1e-12) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + SVD svdSolver(inA.template astype()); + const double threshold = inTolerance * svdSolver.s().front(); + + return svdSolver.solve(inB.template astype(), threshold); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/lu_decomposition.hpp b/runexamples/cpp/include/NumCpp/Linalg/lu_decomposition.hpp new file mode 100644 index 0000000..e8542b9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/lu_decomposition.hpp @@ -0,0 +1,92 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix pivot LU decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros_like.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix LU decomposition A = LU + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return std::pair of the decomposed L and U matrices + /// + template + std::pair, NdArray> lu_decomposition(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + NdArray lMatrix = zeros_like(inMatrix); + NdArray uMatrix = inMatrix.template astype(); + + for (uint32 col = 0; col < shape.cols; ++col) + { + lMatrix(col, col) = 1; + + for (uint32 row = col + 1; row < shape.rows; ++row) + { + const double& divisor = uMatrix(col, col); + if (utils::essentiallyEqual(divisor, double{ 0. })) + { + THROW_RUNTIME_ERROR("Division by 0."); + } + + lMatrix(row, col) = uMatrix(row, col) / divisor; + + for (uint32 col2 = col; col2 < shape.cols; ++col2) + { + uMatrix(row, col2) -= lMatrix(row, col) * uMatrix(col, col2); + } + } + } + + return std::make_pair(lMatrix, uMatrix); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/matrix_power.hpp b/runexamples/cpp/include/NumCpp/Linalg/matrix_power.hpp new file mode 100644 index 0000000..511a859 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/matrix_power.hpp @@ -0,0 +1,105 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raise a square matrix to the (integer) power n. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/identity.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Raise a square matrix to the (integer) power n. + /// + /// For positive integers n, the power is computed by repeated + /// matrix squarings and matrix multiplications. If n == 0, + /// the identity matrix of the same shape as M is returned. + /// If n < 0, the inverse is computed and then raised to the abs(n). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.matrix_power.html#numpy.linalg.matrix_power + /// + /// @param inArray + /// @param inPower + /// + /// @return NdArray + /// + template + NdArray matrix_power(const NdArray& inArray, int16 inPower) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const Shape inShape = inArray.shape(); + if (inShape.rows != inShape.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input matrix must be square."); + } + + if (inPower == 0) + { + return identity(inShape.rows); + } + + if (inPower == 1) + { + return inArray.template astype(); + } + + if (inPower == -1) + { + return inv(inArray); + } + + if (inPower > 1) + { + NdArray inArrayDouble = inArray.template astype(); + NdArray returnArray = dot(inArrayDouble, inArrayDouble); + for (int16 i = 2; i < inPower; ++i) + { + returnArray = dot(returnArray, inArrayDouble); + } + return returnArray; + } + + NdArray inverse = inv(inArray); + NdArray returnArray = dot(inverse, inverse); + inPower *= -1; + for (int16 i = 2; i < inPower; ++i) + { + returnArray = dot(returnArray, inverse); + } + return returnArray; + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/multi_dot.hpp b/runexamples/cpp/include/NumCpp/Linalg/multi_dot.hpp new file mode 100644 index 0000000..68167d0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/multi_dot.hpp @@ -0,0 +1,77 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Compute the dot product of two or more arrays in a single function call. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Compute the dot product of two or more arrays in a single + /// function call. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.multi_dot.html#numpy.linalg.multi_dot + /// + /// @param inList: list of arrays + /// + /// @return NdArray + /// + template + NdArray multi_dot(const std::initializer_list>& inList) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + typename std::initializer_list>::iterator iter = inList.begin(); + + if (inList.size() == 0) + { + THROW_INVALID_ARGUMENT_ERROR("input empty list of arrays."); + } + else if (inList.size() == 1) + { + return iter->copy(); + } + + NdArray returnArray = dot(*iter, *(iter + 1)); + iter += 2; + for (; iter < inList.end(); ++iter) + { + returnArray = dot(returnArray, *iter); + } + + return returnArray; + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/pinv.hpp b/runexamples/cpp/include/NumCpp/Linalg/pinv.hpp new file mode 100644 index 0000000..d583069 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/pinv.hpp @@ -0,0 +1,69 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix psuedo-inverse +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/svd.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix psuedo-inverse + /// + /// NumPy Reference: https://numpy.org/doc/stable/reference/generated/numpy.linalg.pinv.html + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray pinv(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray u; + NdArray d; + NdArray v; + svd(inArray, u, d, v); + + const auto inShape = inArray.shape(); + auto dPlus = nc::zeros(inShape.cols, inShape.rows); // transpose + + for (uint32 i = 0; i < d.shape().rows; ++i) + { + dPlus(i, i) = 1. / d(i, i); + } + + return v.transpose().dot(dPlus).dot(u.transpose()); + } +} // namespace nc::linalg \ No newline at end of file diff --git a/runexamples/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp b/runexamples/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp new file mode 100644 index 0000000..80dbb67 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/pivotLU_decomposition.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix pivot LU decomposition +/// +/// Code modified under MIT license from https://github.com/Ben1980/linAlg +/// as posted in +/// https://thoughts-on-coding.com/2019/06/12/numerical-methods-with-c-part-4-introduction-into-decomposition-methods-of-linear-equation-systems/ +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/zeros_like.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix pivot LU decomposition PA = LU + /// + /// @param inMatrix: NdArray to be decomposed + /// + /// @return std::tuple of the decomposed L, U, and P matrices + /// + template + std::tuple, NdArray, NdArray> pivotLU_decomposition(const NdArray& inMatrix) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto shape = inMatrix.shape(); + + if (!shape.issquare()) + { + THROW_RUNTIME_ERROR("Input matrix should be square."); + } + + NdArray lMatrix = zeros_like(inMatrix); + NdArray uMatrix = inMatrix.template astype(); + NdArray pMatrix = eye(shape.rows); + + for (uint32 k = 0; k < shape.rows; ++k) + { + double max = 0.; + uint32 pk = 0; + for (uint32 i = k; i < shape.rows; ++i) + { + double s = 0.; + for (uint32 j = k; j < shape.cols; ++j) + { + s += std::fabs(uMatrix(i, j)); + } + + const double q = std::fabs(uMatrix(i, k)) / s; + if (q > max) + { + max = q; + pk = i; + } + } + + if (utils::essentiallyEqual(max, double{ 0. })) + { + THROW_RUNTIME_ERROR("Division by 0."); + } + + if (pk != k) + { + for (uint32 j = 0; j < shape.cols; ++j) + { + std::swap(pMatrix(k, j), pMatrix(pk, j)); + std::swap(lMatrix(k, j), lMatrix(pk, j)); + std::swap(uMatrix(k, j), uMatrix(pk, j)); + } + } + + for (uint32 i = k + 1; i < shape.rows; ++i) + { + lMatrix(i, k) = uMatrix(i, k) / uMatrix(k, k); + + for (uint32 j = k; j < shape.cols; ++j) + { + uMatrix(i, j) = uMatrix(i, j) - lMatrix(i, k) * uMatrix(k, j); + } + } + } + + for (uint32 k = 0; k < shape.rows; ++k) + { + lMatrix(k, k) = 1.; + } + + return std::make_tuple(lMatrix, uMatrix, pMatrix); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/solve.hpp b/runexamples/cpp/include/NumCpp/Linalg/solve.hpp new file mode 100644 index 0000000..34e69f8 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/solve.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix svd +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// Solve a linear matrix equation, or system of linear scalar equations. + /// Computes the “exact” solution, x, of the well-determined, i.e., full rank, + /// linear matrix equation ax = b. + /// + /// https://numpy.org/doc/stable/reference/generated/numpy.linalg.solve.html + /// + /// @param inA + /// @param inB + /// @return NdArray Solution to the system a x = b. Returned shape is identical to b + /// + template + NdArray solve(const NdArray& inA, const NdArray& inB) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (!inA.issquare()) + { + THROW_INVALID_ARGUMENT_ERROR("input array a must be square."); + } + + if (!inB.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("input array b must be flat."); + } + + if (inA.numCols() != inB.size()) + { + THROW_INVALID_ARGUMENT_ERROR("input array b size must be the same as the square size of a."); + } + + return dot(inv(inA), inB.template astype().reshape(inB.size(), 1)).reshape(inB.shape()); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/svd.hpp b/runexamples/cpp/include/NumCpp/Linalg/svd.hpp new file mode 100644 index 0000000..5996c0f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/svd.hpp @@ -0,0 +1,64 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// matrix svd +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Linalg/svd/SVDClass.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::linalg +{ + //============================================================================ + // Method Description: + /// matrix svd + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.svd.html#numpy.linalg.svd + /// + /// @param inArray: NdArray to be SVDed + /// @param outU: NdArray output U + /// @param outS: NdArray output S + /// @param outVt: NdArray output V transpose + /// + template + void svd(const NdArray& inArray, NdArray& outU, NdArray& outS, NdArray& outVt) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + SVD svdSolver(inArray.template astype()); + outU = svdSolver.u(); + + NdArray vt = svdSolver.v().transpose(); + outVt = std::move(vt); + + NdArray s = diagflat(svdSolver.s(), 0); + outS = std::move(s); + } +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp b/runexamples/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp new file mode 100644 index 0000000..42084e1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Linalg/svd/SVDClass.hpp @@ -0,0 +1,646 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2020 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Performs the singular value decomposition of a general matrix, +/// taken and adapted from Numerical Recipes Third Edition svd.h +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::linalg +{ + // ============================================================================= + // Class Description: + /// performs the singular value decomposition of a general matrix, + /// taken and adapted from Numerical Recipes Third Edition svd.h + class SVD + { + public: + // ============================================================================= + // Description: + /// Constructor + /// + /// @param inMatrix: matrix to perform SVD on + /// + explicit SVD(const NdArray& inMatrix) : + m_(inMatrix.shape().rows), + n_(inMatrix.shape().cols), + u_(inMatrix), + v_(n_, n_), + s_(1, n_), + eps_(std::numeric_limits::epsilon()) + { + decompose(); + reorder(); + tsh_ = 0.5 * std::sqrt(m_ + n_ + 1.) * s_.front() * eps_; + } + + // ============================================================================= + // Description: + /// the resultant u matrix + /// + /// @return u matrix + /// + const NdArray& u() noexcept + { + return u_; + } + + // ============================================================================= + // Description: + /// the resultant v matrix + /// + /// @return v matrix + /// + const NdArray& v() noexcept + { + return v_; + } + + // ============================================================================= + // Description: + /// the resultant w matrix + /// + /// @return s matrix + /// + const NdArray& s() noexcept + { + return s_; + } + + // ============================================================================= + // Description: + /// solves the linear least squares problem + /// + /// @param inInput + /// @param inThresh (default -1.) + /// + /// @return NdArray + /// + NdArray solve(const NdArray& inInput, double inThresh = -1.) + { + double ss{}; + + if (inInput.size() != m_) + { + THROW_INVALID_ARGUMENT_ERROR("bad sizes."); + } + + NdArray returnArray(1, n_); + + NdArray tmp(1, n_); + + tsh_ = (inThresh >= 0. ? inThresh : 0.5 * sqrt(m_ + n_ + 1.) * s_.front() * eps_); + + for (uint32 j = 0; j < n_; j++) + { + ss = 0.; + if (s_[j] > tsh_) + { + for (uint32 i = 0; i < m_; i++) + { + ss += u_(i, j) * inInput[i]; + } + ss /= s_[j]; + } + tmp[j] = ss; + } + + for (uint32 j = 0; j < n_; j++) + { + ss = 0.; + for (uint32 jj = 0; jj < n_; jj++) + { + ss += v_(j, jj) * tmp[jj]; + } + + returnArray[j] = ss; + } + + return returnArray; + } + + private: + // ============================================================================= + // Description: + /// returns the SIGN of two values + /// + /// @param inA + /// @param inB + /// + /// @return value + /// + static double SIGN(double inA, double inB) noexcept + { + return inB >= 0 ? (inA >= 0 ? inA : -inA) : (inA >= 0 ? -inA : inA); + } + + // ============================================================================= + // Description: + /// decomposes the input matrix + /// + void decompose() + { + bool flag{}; + uint32 i{}; + uint32 its{}; + uint32 j{}; + uint32 jj{}; + uint32 k{}; + uint32 l{}; + uint32 nm{}; + + double anorm{}; + double c{}; + double f{}; + double g{}; + double h{}; + double ss{}; + double scale{}; + double x{}; + double y{}; + double z{}; + + NdArray rv1(n_, 1); + + for (i = 0; i < n_; ++i) + { + l = i + 2; + rv1[i] = scale * g; + g = ss = scale = 0.; + + if (i < m_) + { + for (k = i; k < m_; ++k) + { + scale += std::abs(u_(k, i)); + } + + if (!utils::essentiallyEqual(scale, 0.)) + { + for (k = i; k < m_; ++k) + { + u_(k, i) /= scale; + ss += u_(k, i) * u_(k, i); + } + + f = u_(i, i); + g = -SIGN(std::sqrt(ss), f); + h = f * g - ss; + u_(i, i) = f - g; + + for (j = l - 1; j < n_; ++j) + { + for (ss = 0., k = i; k < m_; ++k) + { + ss += u_(k, i) * u_(k, j); + } + + f = ss / h; + + for (k = i; k < m_; ++k) + { + u_(k, j) += f * u_(k, i); + } + } + + for (k = i; k < m_; ++k) + { + u_(k, i) *= scale; + } + } + } + + s_[i] = scale * g; + g = ss = scale = 0.; + + if (i + 1 <= m_ && i + 1 != n_) + { + for (k = l - 1; k < n_; ++k) + { + scale += std::abs(u_(i, k)); + } + + if (!utils::essentiallyEqual(scale, 0.)) + { + for (k = l - 1; k < n_; ++k) + { + u_(i, k) /= scale; + ss += u_(i, k) * u_(i, k); + } + + f = u_(i, l - 1); + g = -SIGN(std::sqrt(ss), f); + h = f * g - ss; + u_(i, l - 1) = f - g; + + for (k = l - 1; k < n_; ++k) + { + rv1[k] = u_(i, k) / h; + } + + for (j = l - 1; j < m_; ++j) + { + for (ss = 0., k = l - 1; k < n_; ++k) + { + ss += u_(j, k) * u_(i, k); + } + + for (k = l - 1; k < n_; ++k) + { + u_(j, k) += ss * rv1[k]; + } + } + + for (k = l - 1; k < n_; ++k) + { + u_(i, k) *= scale; + } + } + } + + anorm = std::max(anorm, (std::abs(s_[i]) + std::abs(rv1[i]))); + } + + for (i = n_ - 1; i != static_cast(-1); --i) + { + if (i < n_ - 1) + { + if (!utils::essentiallyEqual(g, 0.)) + { + for (j = l; j < n_; ++j) + { + v_(j, i) = (u_(i, j) / u_(i, l)) / g; + } + + for (j = l; j < n_; ++j) + { + for (ss = 0., k = l; k < n_; ++k) + { + ss += u_(i, k) * v_(k, j); + } + + for (k = l; k < n_; ++k) + { + v_(k, j) += ss * v_(k, i); + } + } + } + + for (j = l; j < n_; ++j) + { + v_(i, j) = v_(j, i) = 0.; + } + } + + v_(i, i) = 1.; + g = rv1[i]; + l = i; + } + + for (i = std::min(m_, n_) - 1; i != static_cast(-1); --i) + { + l = i + 1; + g = s_[i]; + + for (j = l; j < n_; ++j) + { + u_(i, j) = 0.; + } + + if (!utils::essentiallyEqual(g, 0.)) + { + g = 1. / g; + + for (j = l; j < n_; ++j) + { + for (ss = 0., k = l; k < m_; ++k) + { + ss += u_(k, i) * u_(k, j); + } + + f = (ss / u_(i, i)) * g; + + for (k = i; k < m_; ++k) + { + u_(k, j) += f * u_(k, i); + } + } + + for (j = i; j < m_; ++j) + { + u_(j, i) *= g; + } + } + else + { + for (j = i; j < m_; ++j) + { + u_(j, i) = 0.; + } + } + + ++u_(i, i); + } + + for (k = n_ - 1; k != static_cast(-1); --k) + { + for (its = 0; its < 30; ++its) + { + flag = true; + for (l = k; l != static_cast(-1); --l) + { + nm = l - 1; + if (l == 0 || std::abs(rv1[l]) <= eps_ * anorm) + { + flag = false; + break; + } + + if (std::abs(s_[nm]) <= eps_ * anorm) + { + break; + } + } + + if (flag) + { + c = 0.; + ss = 1.; + for (i = l; i < k + 1; ++i) + { + f = ss * rv1[i]; + rv1[i] = c * rv1[i]; + + if (std::abs(f) <= eps_ * anorm) + { + break; + } + + g = s_[i]; + h = pythag(f, g); + s_[i] = h; + h = 1. / h; + c = g * h; + ss = -f * h; + + for (j = 0; j < m_; ++j) + { + y = u_(j, nm); + z = u_(j, i); + u_(j, nm) = y * c + z * ss; + u_(j, i) = z * c - y * ss; + } + } + } + + z = s_[k]; + if (l == k) + { + if (z < 0.) + { + s_[k] = -z; + for (j = 0; j < n_; ++j) + { + v_(j, k) = -v_(j, k); + } + } + break; + } + + if (its == 29) + { + THROW_INVALID_ARGUMENT_ERROR("no convergence in 30 svdcmp iterations"); + } + + x = s_[l]; + nm = k - 1; + y = s_[nm]; + g = rv1[nm]; + h = rv1[k]; + f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2. * h * y); + g = pythag(f, 1.); + f = ((x - z) * (x + z) + h * ((y / (f + SIGN(g, f))) - h)) / x; + c = ss = 1.; + + for (j = l; j <= nm; j++) + { + i = j + 1; + g = rv1[i]; + y = s_[i]; + h = ss * g; + g = c * g; + z = pythag(f, h); + rv1[j] = z; + c = f / z; + ss = h / z; + f = x * c + g * ss; + g = g * c - x * ss; + h = y * ss; + y *= c; + + for (jj = 0; jj < n_; ++jj) + { + x = v_(jj, j); + z = v_(jj, i); + v_(jj, j) = x * c + z * ss; + v_(jj, i) = z * c - x * ss; + } + + z = pythag(f, h); + s_[j] = z; + + if (!utils::essentiallyEqual(z, 0.)) + { + z = 1. / z; + c = f * z; + ss = h * z; + } + + f = c * g + ss * y; + x = c * y - ss * g; + + for (jj = 0; jj < m_; ++jj) + { + y = u_(jj, j); + z = u_(jj, i); + u_(jj, j) = y * c + z * ss; + u_(jj, i) = z * c - y * ss; + } + } + rv1[l] = 0.; + rv1[k] = f; + s_[k] = x; + } + } + } + + // ============================================================================= + // Description: + /// reorders the input matrix + /// + void reorder() + { + uint32 i = 0; + uint32 j = 0; + uint32 k = 0; + uint32 ss = 0; + uint32 inc = 1; + + double sw{}; + NdArray su(m_, 1); + NdArray sv(n_, 1); + + do + { + inc *= 3; + ++inc; + } while (inc <= n_); + + do + { + inc /= 3; + for (i = inc; i < n_; ++i) + { + sw = s_[i]; + for (k = 0; k < m_; ++k) + { + su[k] = u_(k, i); + } + + for (k = 0; k < n_; ++k) + { + sv[k] = v_(k, i); + } + + j = i; + while (s_[j - inc] < sw) + { + s_[j] = s_[j - inc]; + + for (k = 0; k < m_; ++k) + { + u_(k, j) = u_(k, j - inc); + } + + for (k = 0; k < n_; ++k) + { + v_(k, j) = v_(k, j - inc); + } + + j -= inc; + + if (j < inc) + { + break; + } + } + + s_[j] = sw; + + for (k = 0; k < m_; ++k) + { + u_(k, j) = su[k]; + } + + for (k = 0; k < n_; ++k) + { + v_(k, j) = sv[k]; + } + } + } while (inc > 1); + + for (k = 0; k < n_; ++k) + { + ss = 0; + + for (i = 0; i < m_; i++) + { + if (u_(i, k) < 0.) + { + ss++; + } + } + + for (j = 0; j < n_; ++j) + { + if (v_(j, k) < 0.) + { + ss++; + } + } + + if (ss > (m_ + n_) / 2) + { + for (i = 0; i < m_; ++i) + { + u_(i, k) = -u_(i, k); + } + + for (j = 0; j < n_; ++j) + { + v_(j, k) = -v_(j, k); + } + } + } + } + + // ============================================================================= + // Description: + /// performs pythag of input values + /// + /// @param inA + /// @param inB + /// + /// @return resultant value + /// + static double pythag(double inA, double inB) noexcept + { + const double absa = std::abs(inA); + const double absb = std::abs(inB); + return (absa > absb + ? absa * std::sqrt(1. + utils::sqr(absb / absa)) + : (utils::essentiallyEqual(absb, 0.) ? 0. : absb * std::sqrt(1. + utils::sqr(absa / absb)))); + } + + private: + // ===============================Attributes==================================== + const uint32 m_{}; + const uint32 n_{}; + NdArray u_{}; + NdArray v_{}; + NdArray s_{}; + double eps_{}; + double tsh_{}; + }; +} // namespace nc::linalg diff --git a/runexamples/cpp/include/NumCpp/NdArray.hpp b/runexamples/cpp/include/NumCpp/NdArray.hpp new file mode 100644 index 0000000..a7b0ff9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/NdArray.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds 1D and 2D arrays, the main work horse of the NumCpp library +/// +#pragma once + +#include "NumCpp/NdArray/NdArrayCore.hpp" +#include "NumCpp/NdArray/NdArrayOperators.hpp" diff --git a/runexamples/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp b/runexamples/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp new file mode 100644 index 0000000..3bbbc51 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/NdArray/NdArrayBroadcast.hpp @@ -0,0 +1,289 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Broadcasting for NdArray functions +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray/NdArrayCore.hpp" + +namespace nc::broadcast +{ + //============================================================================ + // Method Description: + /// Broadcasting template function for in-place operations + /// + /// @param function + /// @param inArray1 + /// @param inArray2 + /// @param additionalFunctionArgs + /// + /// @return NdArray + /// + template + NdArray& broadcaster(NdArray& inArray1, + const NdArray& inArray2, + const Function& function, + const AdditionalFunctionArgs&&... additionalFunctionArgs) + { + if (inArray1.shape() == inArray2.shape()) + { + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + inArray1.begin(), + [&function, &additionalFunctionArgs...](const auto& inValue1, const auto& inValue2) -> dtypeIn1 { + return function(inValue1, + inValue2, + std::forward(additionalFunctionArgs)...); + }); + } + else if (inArray2.isscalar()) + { + const auto value = inArray2.item(); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray1.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 + { return function(inValue, value, std::forward(additionalFunctionArgs)...); }); + } + else if (inArray2.isflat()) + { + if (inArray2.numRows() > 1 && inArray2.numRows() == inArray1.numRows()) + { + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + const auto value = inArray2[row]; + stl_algorithms::transform( + inArray1.cbegin(row), + inArray1.cend(row), + inArray1.begin(row), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + } + else if (inArray2.numCols() > 1 && inArray2.numCols() == inArray1.numCols()) + { + for (uint32 col = 0; col < inArray1.numCols(); ++col) + { + const auto value = inArray2[col]; + stl_algorithms::transform( + inArray1.ccolbegin(col), + inArray1.ccolend(col), + inArray1.colbegin(col), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeIn1 { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + + return inArray1; + } + + //============================================================================ + // Method Description: + /// Broadcasting template function + /// + /// @param function + /// @param inArray1 + /// @param inArray2 + /// @param additionalFunctionArgs + /// + /// @return NdArray + /// + template + NdArray broadcaster(const NdArray& inArray1, + const NdArray& inArray2, + const Function& function, + const AdditionalFunctionArgs&&... additionalFunctionArgs) + { + if (inArray1.shape() == inArray2.shape()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + inArray2.cbegin(), + returnArray.begin(), + [&function, &additionalFunctionArgs...](const auto& inValue1, const auto& inValue2) -> dtypeOut { + return function(inValue1, + inValue2, + std::forward(additionalFunctionArgs)...); + }); + + return returnArray; + }(); + } + else if (inArray1.isscalar()) + { + const auto value = inArray1.item(); + return [&inArray2, &value, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray2.shape()); + stl_algorithms::transform( + inArray2.cbegin(), + inArray2.cend(), + returnArray.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + return returnArray; + }(); + } + else if (inArray2.isscalar()) + { + const auto value = inArray2.item(); + return [&inArray1, &value, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + stl_algorithms::transform( + inArray1.cbegin(), + inArray1.cend(), + returnArray.begin(), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + return returnArray; + }(); + } + else if (inArray1.isflat() && inArray2.isflat()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + const auto numRows = std::max(inArray1.numRows(), inArray2.numRows()); + const auto numCols = std::max(inArray1.numCols(), inArray2.numCols()); + NdArray returnArray(numRows, numCols); + if (inArray1.numRows() > 1) + { + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + for (uint32 col = 0; col < inArray2.numCols(); ++col) + { + returnArray(row, col) = + function(inArray1[row], + inArray2[col], + std::forward(additionalFunctionArgs)...); + } + } + } + else + { + for (uint32 row = 0; row < inArray2.numRows(); ++row) + { + for (uint32 col = 0; col < inArray1.numCols(); ++col) + { + returnArray(row, col) = + function(inArray1[col], + inArray2[row], + std::forward(additionalFunctionArgs)...); + } + } + } + return returnArray; + }(); + } + else if (inArray1.isflat()) + { + return broadcaster(inArray2, + inArray1, + function, + std::forward(additionalFunctionArgs)...); + } + else if (inArray2.isflat()) + { + if (inArray2.numRows() > 1 && inArray2.numRows() == inArray1.numRows()) + { + return [&inArray1, &inArray2, &function, &additionalFunctionArgs...] + { + NdArray returnArray(inArray1.shape()); + for (uint32 row = 0; row < inArray1.numRows(); ++row) + { + const auto value = inArray2[row]; + stl_algorithms::transform( + inArray1.cbegin(row), + inArray1.cend(row), + returnArray.begin(row), + [&value, &function, &additionalFunctionArgs...](const auto& inValue) -> dtypeOut { + return function(inValue, + value, + std::forward(additionalFunctionArgs)...); + }); + } + return returnArray; + }(); + } + else if (inArray2.numCols() > 1 && inArray2.numCols() == inArray1.numCols()) + { + return broadcaster(inArray1.transpose(), + inArray2.transpose(), + function, + std::forward(additionalFunctionArgs)...) + .transpose(); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + } + else + { + THROW_INVALID_ARGUMENT_ERROR("operands could not be broadcast together"); + } + + return {}; // get rid of compiler warning + } +} // namespace nc::broadcast diff --git a/runexamples/cpp/include/NumCpp/NdArray/NdArrayCore.hpp b/runexamples/cpp/include/NumCpp/NdArray/NdArrayCore.hpp new file mode 100644 index 0000000..ee09277 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/NdArray/NdArrayCore.hpp @@ -0,0 +1,4881 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds 1D and 2D arrays, the main work horse of the NumCpp library +/// +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Constants.hpp" +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Endian.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Slice.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray/NdArrayIterators.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/essentiallyEqualComplex.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Utils/value2str.hpp" + +namespace nc +{ + namespace type_traits + { + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index type for NdArray + /// + template + struct is_ndarray_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is a valid index typefor NdArray + /// + + template + struct is_ndarray_int> + { + static constexpr bool value = std::is_integral_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_int_v = is_ndarray_int::value; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is an unsigned integer type + /// + template + struct is_ndarray_signed_int : std::false_type + { + }; + + //============================================================================ + // Class Description: + /// Template class for determining if dtype is an unsigned integer type + /// + + template + struct is_ndarray_signed_int> + { + static constexpr bool value = std::is_signed_v; + }; + + //============================================================================ + // Class Description: + /// is_ndarray_int helper + /// + template + constexpr bool is_ndarray_signed_int_v = is_ndarray_signed_int::value; + + //============================================================================ + // Class Description: + /// is_ndarray_int + /// + template + using ndarray_int_concept = std::enable_if_t, int>; + } // namespace type_traits + + //================================================================================ + // Class Description: + /// Holds 1D and 2D arrays, the main work horse of the NumCpp library + template> + class NdArray + { + private: + STATIC_ASSERT_VALID_DTYPE(dtype); + static_assert(std::is_same_v, + "value_type and Allocator::value_type must match"); + + using AllocType = typename std::allocator_traits::template rebind_alloc; + using AllocTraits = std::allocator_traits; + + public: + using self_type = NdArray; + using value_type = dtype; + using allocator_type = Allocator; + using pointer = typename AllocTraits::pointer; + using const_pointer = typename AllocTraits::const_pointer; + using reference = dtype&; + using const_reference = const dtype&; + using size_type = uint32; + using index_type = int32; + using difference_type = typename AllocTraits::difference_type; + + using iterator = NdArrayIterator; + using const_iterator = NdArrayConstIterator; + using reverse_iterator = std::reverse_iterator; + using const_reverse_iterator = std::reverse_iterator; + + using column_iterator = NdArrayColumnIterator; + using const_column_iterator = NdArrayConstColumnIterator; + using reverse_column_iterator = std::reverse_iterator; + using const_reverse_column_iterator = std::reverse_iterator; + + //============================================================================ + // Method Description: + /// Defualt Constructor, not very usefull... + /// + NdArray() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inSquareSize: square number of rows and columns + /// + explicit NdArray(size_type inSquareSize) : + shape_(inSquareSize, inSquareSize), + size_(inSquareSize * inSquareSize) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inNumRows + /// @param inNumCols + /// + NdArray(size_type inNumRows, size_type inNumCols) : + shape_(inNumRows, inNumCols), + size_(inNumRows * inNumCols) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inShape + /// + explicit NdArray(const Shape& inShape) : + shape_(inShape), + size_(shape_.size()) + { + newArray(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + NdArray(std::initializer_list inList) : + shape_(1, static_cast(inList.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inList.begin(), inList.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList: 2D initializer list + /// + NdArray(const std::initializer_list>& inList) : + shape_(static_cast(inList.size()), 0) + { + for (const auto& list : inList) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(list.size()); + } + else if (list.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR( + "All rows of the initializer list needs to have the same number of elements"); + } + } + + size_ = shape_.size(); + newArray(); + uint32 row = 0; + for (const auto& list : inList) + { + const auto ptr = begin() += row * shape_.cols; + stl_algorithms::copy(list.begin(), list.end(), ptr); + ++row; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template, int> = 0> + NdArray(std::array& inArray, bool copy = true) : + shape_(1, static_cast(ArraySize)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inArray.begin(), inArray.end(), begin()); + } + } + else + { + array_ = inArray.data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template + NdArray(std::array, Dim0Size>& in2dArray, bool copy = true) : + shape_(static_cast(Dim0Size), static_cast(Dim1Size)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + const auto start = in2dArray.front().begin(); + stl_algorithms::copy(start, start + size_, begin()); + } + } + else + { + array_ = in2dArray.front().data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inVector + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template, int> = 0> + NdArray(std::vector& inVector, bool copy = true) : + shape_(1, static_cast(inVector.size())), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inVector.begin(), inVector.end(), begin()); + } + } + else + { + array_ = inVector.data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dVector + /// + explicit NdArray(const std::vector>& in2dVector) : + shape_(static_cast(in2dVector.size()), 0) + { + for (const auto& row : in2dVector) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(row.size()); + } + else if (row.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("All rows of the 2d vector need to have the same number of elements"); + } + } + + size_ = shape_.size(); + + newArray(); + auto currentPosition = begin(); + for (const auto& row : in2dVector) + { + stl_algorithms::copy(row.begin(), row.end(), currentPosition); + currentPosition += shape_.cols; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dArray + /// @param copy: (optional) boolean for whether to make a copy and own the data, or + /// act as a non-owning shell. Default true. + /// + template + NdArray(std::vector>& in2dArray, bool copy = true) : + shape_(static_cast(in2dArray.size()), static_cast(Dim1Size)), + size_(shape_.size()) + { + if (copy) + { + newArray(); + if (size_ > 0) + { + const auto start = in2dArray.front().begin(); + stl_algorithms::copy(start, start + size_, begin()); + } + } + else + { + array_ = in2dArray.front().data(); + ownsPtr_ = false; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inDeque + /// + template, int> = 0> + explicit NdArray(const std::deque& inDeque) : + shape_(1, static_cast(inDeque.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inDeque.begin(), inDeque.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param in2dDeque + /// + explicit NdArray(const std::deque>& in2dDeque) : + shape_(static_cast(in2dDeque.size()), 0) + { + for (const auto& row : in2dDeque) + { + if (shape_.cols == 0) + { + shape_.cols = static_cast(row.size()); + } + else if (row.size() != shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("All rows of the 2d vector need to have the same number of elements"); + } + } + + size_ = shape_.size(); + + newArray(); + auto currentPosition = begin(); + for (const auto& row : in2dDeque) + { + stl_algorithms::copy(row.begin(), row.end(), currentPosition); + currentPosition += shape_.cols; + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + explicit NdArray(const std::list& inList) : + shape_(1, static_cast(inList.size())), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inList.begin(), inList.end(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inFirst + /// @param inLast + /// + template::value_type, dtype>, int> = 0> + NdArray(Iterator inFirst, Iterator inLast) : + shape_(1, static_cast(std::distance(inFirst, inLast))), + size_(shape_.size()) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inFirst, inLast, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Copies the contents of the buffer into + /// the array. + /// + /// @param inPtr: const_pointer to beginning of buffer + /// @param size: number of elements in buffer + /// + NdArray(const_pointer inPtr, size_type size) : + shape_(1, size), + size_(size) + { + newArray(); + if (inPtr != nullptr && size_ > 0) + { + stl_algorithms::copy(inPtr, inPtr + size_, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Copies the contents of the buffer into + /// the array. + /// + /// @param inPtr: const_pointer to beginning of buffer + /// @param numRows: number of rows of the buffer + /// @param numCols: number of cols of the buffer + /// + template, int> = 0, + std::enable_if_t, int> = 0> + NdArray(const_pointer inPtr, UIntType1 numRows, UIntType2 numCols) : + shape_(numRows, numCols), + size_(shape_.size()) + { + newArray(); + if (inPtr != nullptr && size_ > 0) + { + stl_algorithms::copy(inPtr, inPtr + size_, begin()); + } + } + + //============================================================================ + // Method Description: + /// Constructor. Operates as a shell around an already existing + /// array of data. + /// + /// @param inPtr: pointer to beginning of the array + /// @param size: the number of elements in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// + template, int> = 0> + NdArray(pointer inPtr, size_type size, BoolType takeOwnership) noexcept : + shape_(1, size), + size_(size), + array_(inPtr), + ownsPtr_(takeOwnership) + { + } + + //============================================================================ + // Method Description: + /// Constructor. Operates as a shell around an already existing + /// array of data. + /// + /// @param inPtr: pointer to beginning of the array + /// @param numRows: the number of rows in the array + /// @param numCols: the nubmer of column in the array + /// @param takeOwnership: whether or not to take ownership of the data + /// and call delete[] in the destructor. + /// + template, int> = 0> + NdArray(pointer inPtr, size_type numRows, size_type numCols, BoolType takeOwnership) noexcept : + shape_(numRows, numCols), + size_(numRows * numCols), + array_(inPtr), + ownsPtr_(takeOwnership) + { + } + + //============================================================================ + // Method Description: + /// Copy Constructor + /// + /// @param inOtherArray + /// + NdArray(const self_type& inOtherArray) : + shape_(inOtherArray.shape_), + size_(inOtherArray.size_), + endianess_(inOtherArray.endianess_) + { + newArray(); + if (size_ > 0) + { + stl_algorithms::copy(inOtherArray.cbegin(), inOtherArray.cend(), begin()); + } + } + + //============================================================================ + // Method Description: + /// Move Constructor + /// + /// @param inOtherArray + /// + NdArray(self_type&& inOtherArray) noexcept : + shape_(inOtherArray.shape_), + size_(inOtherArray.size_), + endianess_(inOtherArray.endianess_), + array_(inOtherArray.array_), + ownsPtr_(inOtherArray.ownsPtr_) + { + inOtherArray.shape_.rows = inOtherArray.shape_.cols = 0; + inOtherArray.size_ = 0; + inOtherArray.ownsPtr_ = false; + inOtherArray.array_ = nullptr; + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~NdArray() noexcept + { + deleteArray(); + } + + //============================================================================ + // Method Description: + /// Assignment operator, performs a deep copy + /// + /// @param rhs + /// @return NdArray + /// + self_type& operator=(const self_type& rhs) + { + if (&rhs != this) + { + if (rhs.size_ > 0) + { + newArray(rhs.shape_); + endianess_ = rhs.endianess_; + + stl_algorithms::copy(rhs.cbegin(), rhs.cend(), begin()); + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Assignment operator, sets the entire array to a single + /// scalar value. + /// + /// @param inValue + /// @return NdArray + /// + self_type& operator=(value_type inValue) noexcept + { + if (array_ != nullptr) + { + stl_algorithms::fill(begin(), end(), inValue); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Move operator, performs a deep move + /// + /// @param rhs + /// @return NdArray + /// + self_type& operator=(self_type&& rhs) noexcept + { + if (&rhs != this) + { + deleteArray(); + shape_ = rhs.shape_; + size_ = rhs.size_; + endianess_ = rhs.endianess_; + array_ = rhs.array_; + ownsPtr_ = rhs.ownsPtr_; + + rhs.shape_.rows = rhs.shape_.cols = rhs.size_ = 0; + rhs.array_ = nullptr; + rhs.ownsPtr_ = false; + } + + return *this; + } + + //============================================================================ + // Method Description: + /// 1D access operator with no bounds checking + /// + /// @param inIndex + /// @return value + /// + reference operator[](index_type inIndex) noexcept + { + return const_cast(const_cast(this)->operator[](inIndex)); + } + + //============================================================================ + // Method Description: + /// const 1D access operator with no bounds checking + /// + /// @param inIndex + /// @return value + /// + [[nodiscard]] const_reference operator[](index_type inIndex) const noexcept + { + if (inIndex < 0) + { + inIndex += size_; + } + + return array_[inIndex]; + } + + //============================================================================ + // Method Description: + /// 2D access operator with no bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + reference operator()(index_type inRowIndex, index_type inColIndex) noexcept + { + return const_cast(const_cast(this)->operator()(inRowIndex, inColIndex)); + } + + //============================================================================ + // Method Description: + /// const 2D access operator with no bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + [[nodiscard]] const_reference operator()(index_type inRowIndex, index_type inColIndex) const noexcept + { + if (inRowIndex < 0) + { + inRowIndex += shape_.rows; + } + + if (inColIndex < 0) + { + inColIndex += shape_.cols; + } + + return array_[inRowIndex * shape_.cols + inColIndex]; + } + + //============================================================================ + // Method Description: + /// 1D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator[](Slice inSlice) const + { + return operator[](toIndices(inSlice, Axis::NONE)); + } + + //============================================================================ + // Method Description: + /// Returns the values from the input mask with no bounds checking + /// + /// @param inMask + /// @return NdArray + /// + [[nodiscard]] self_type operator[](const NdArray& inMask) const + { + return operator[](inMask.flatnonzero()); + } + + //============================================================================ + // Method Description: + /// Returns the values from the input indices with no bounds checking + /// + /// @param inIndices + /// @return NdArray + /// + /// + template = 0> + [[nodiscard]] self_type operator[](const Indices& inIndices) const + { + auto outArray = self_type(1, static_cast(inIndices.size())); + size_type i = 0; + for (auto& index : inIndices) + { + outArray[i++] = operator[](static_cast(index)); + } + + return outArray; + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowSlice + /// @param inColSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator()(Slice inRowSlice, Slice inColSlice) const + { + return operator()(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowSlice + /// @param inColIndex + /// @return NdArray + /// + [[nodiscard]] self_type operator()(Slice inRowSlice, index_type inColIndex) const + { + const NdArray colIndices = { inColIndex }; + return operator()(toIndices(inRowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// 2D Slicing access operator with no bounds checking + /// returned array is of the range [start, stop). + /// + /// @param inRowIndex + /// @param inColSlice + /// @return NdArray + /// + [[nodiscard]] self_type operator()(index_type inRowIndex, Slice inColSlice) const + { + const NdArray rowIndices = { inRowIndex }; + return operator()(rowIndices, toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colIndex + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(const Indices& rowIndices, index_type colIndex) const + { + const NdArray colIndices = { colIndex }; + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colSlice + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(const Indices& rowIndices, Slice colSlice) const + { + return operator()(rowIndices, toIndices(colSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndex + /// @param colIndices + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(index_type rowIndex, const Indices& colIndices) const + { + const NdArray rowIndices = { rowIndex }; + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowSlice + /// @param colIndices + /// @return NdArray + /// + template = 0> + [[nodiscard]] self_type operator()(Slice rowSlice, const Indices& colIndices) const + { + return operator()(toIndices(rowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// 2D index access operator with no bounds checking + /// returned array is of the range. + /// + /// @param rowIndices + /// @param colIndices + /// @return NdArray + /// + template = 0, + type_traits::ndarray_int_concept = 0> + [[nodiscard]] self_type operator()(const RowIndices& rowIndices, const ColIndices& colIndices) const + { + self_type returnArray(rowIndices.size(), colIndices.size()); + + size_type rowCounter = 0; + for (auto rowIter = rowIndices.begin(); rowIter != rowIndices.end(); ++rowIter) + { + size_type colCounter = 0; + for (auto colIter = colIndices.begin(); colIter != colIndices.end(); ++colIter) + { + returnArray(rowCounter, colCounter++) = operator()(*rowIter, *colIter); + } + + ++rowCounter; + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns a Slice object for slicing a row to the end of + /// array. + /// + /// @param inStartIdx (default 0) + /// @param inStepSize (default 1) + /// @return Slice + /// + [[nodiscard]] Slice cSlice(index_type inStartIdx = 0, size_type inStepSize = 1) const + { + return Slice(inStartIdx, shape_.cols, inStepSize); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns a Slice object for slicing a column to the end + /// of the array. + /// + /// @param inStartIdx (default 0) + /// @param inStepSize (default 1) + /// @return Slice + /// + [[nodiscard]] Slice rSlice(index_type inStartIdx = 0, size_type inStepSize = 1) const + { + return Slice(inStartIdx, shape_.rows, inStepSize); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// 1D access method with bounds checking + /// + /// @param inIndex + /// @return value + /// + reference at(index_type inIndex) + { + return const_cast(const_cast(this)->at(inIndex)); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inIndex + /// @return value + /// + [[nodiscard]] const_reference at(index_type inIndex) const + { + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inIndex) > static_cast(size_ - 1)) + { + std::string errStr = "Input index " + utils::num2str(inIndex); + errStr += " is out of bounds for array of size " + utils::num2str(size_) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + return operator[](inIndex); // cppcheck-suppress returnTempReference + } + + //============================================================================ + // Method Description: + /// 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + reference at(index_type inRowIndex, index_type inColIndex) + { + return const_cast(const_cast(this)->at(inRowIndex, inColIndex)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColIndex + /// @return value + /// + [[nodiscard]] const_reference at(index_type inRowIndex, index_type inColIndex) const + { + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inRowIndex) > static_cast(shape_.rows - 1)) + { + std::string errStr = "Row index " + utils::num2str(inRowIndex); + errStr += " is out of bounds for array of size " + utils::num2str(shape_.rows) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + // this doesn't allow for calling the first element as -size_... + // but why would you really want to do that anyway? + if (std::abs(inColIndex) > static_cast(shape_.cols - 1)) + { + std::string errStr = "Column index " + utils::num2str(inColIndex); + errStr += " is out of bounds for array of size " + utils::num2str(shape_.cols) + "."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + return operator()(inRowIndex, inColIndex); // cppcheck-suppress returnTempReference + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inSlice) const + { + return at(toIndices(inSlice, Axis::NONE)); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inMask + /// @return Ndarray + /// + [[nodiscard]] self_type at(const NdArray& inMask) const + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("Input mask must have the same dimensions as array."); + } + + return operator[](inMask); + } + + //============================================================================ + // Method Description: + /// const 1D access method with bounds checking + /// + /// @param inIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& inIndices) const + { + stl_algorithms::for_each(inIndices.begin(), + inIndices.end(), + [this](auto index) + { + auto indexSigned = static_cast(index); + if (indexSigned < 0) + { + indexSigned += size_; + } + + if (indexSigned < 0 || indexSigned > static_cast(size_ - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Index exceeds matrix dimensions"); + } + }); + + return operator[](inIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowSlice + /// @param inColSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inRowSlice, const Slice& inColSlice) const + { + return at(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowSlice + /// @param inColIndex + /// @return Ndarray + /// + [[nodiscard]] self_type at(const Slice& inRowSlice, index_type inColIndex) const + { + const NdArray colIndices = { inColIndex }; + return at(toIndices(inRowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param inRowIndex + /// @param inColSlice + /// @return Ndarray + /// + [[nodiscard]] self_type at(index_type inRowIndex, const Slice& inColSlice) const + { + const NdArray rowIndices = { inRowIndex }; + return at(rowIndices, toIndices(inColSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colIndex + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& rowIndices, index_type colIndex) const + { + const NdArray colIndices = { colIndex }; + return at(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colSlice + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(const Indices& rowIndices, Slice colSlice) const + { + return at(rowIndices, toIndices(colSlice, Axis::COL)); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndex + /// @param colIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(index_type rowIndex, const Indices& colIndices) const + { + const NdArray rowIndices = { rowIndex }; + return at(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowSlice + /// @param colIndices + /// @return Ndarray + /// + template = 0> + [[nodiscard]] self_type at(Slice rowSlice, const Indices& colIndices) const + { + return at(toIndices(rowSlice, Axis::ROW), colIndices); + } + + //============================================================================ + // Method Description: + /// const 2D access method with bounds checking + /// + /// @param rowIndices + /// @param colIndices + /// @return Ndarray + /// + template = 0, + type_traits::ndarray_int_concept = 0> + [[nodiscard]] self_type at(const RowIndices& rowIndices, const ColIndices& colIndices) const + { + stl_algorithms::for_each(rowIndices.begin(), + rowIndices.end(), + [this](auto row) + { + auto rowSigned = static_cast(row); + if (rowSigned < 0) + { + rowSigned += shape_.rows; + } + + if (rowSigned < 0 || rowSigned > static_cast(shape_.rows - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Row index exceeds matrix dimensions"); + } + }); + + stl_algorithms::for_each(colIndices.begin(), + colIndices.end(), + [this](auto col) + { + auto colSigned = static_cast(col); + if (colSigned < 0) + { + colSigned += shape_.cols; + } + + if (colSigned < 0 || colSigned > static_cast(shape_.cols - 1)) + { + THROW_INVALID_ARGUMENT_ERROR("Column index exceeds matrix dimensions"); + } + }); + + return operator()(rowIndices, colIndices); + } + + //============================================================================ + // Method Description: + /// iterator to the beginning of the flattened array + /// @return iterator + /// + [[nodiscard]] iterator begin() noexcept + { + return iterator(array_); + } + + //============================================================================ + // Method Description: + /// iterator to the beginning of the input row + /// + /// @param inRow + /// @return iterator + /// + [[nodiscard]] iterator begin(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return begin() += (inRow * shape_.cols); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin() const noexcept + { + return cbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator begin(size_type inRow) const + { + return cbegin(inRow); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin() const noexcept + { + return const_iterator(array_); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator cbegin(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return cbegin() += (inRow * shape_.cols); + } + + //============================================================================ + // Method Description: + /// column_iterator to the beginning of the flattened array + /// @return column_iterator + /// + [[nodiscard]] column_iterator colbegin() noexcept + { + return column_iterator(array_, shape_.rows, shape_.cols); + } + + //============================================================================ + // Method Description: + /// column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return column_iterator + /// + [[nodiscard]] column_iterator colbegin(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return colbegin() += (inCol * shape_.rows); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the beginning of the flattened array + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colbegin() const noexcept + { + return ccolbegin(); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colbegin(size_type inCol) const + { + return ccolbegin(inCol); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to the beginning of the flattened array + /// + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolbegin() const noexcept + { + return const_column_iterator(array_, shape_.rows, shape_.cols); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolbegin(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return ccolbegin() += (inCol * shape_.rows); + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the beginning of the flattened array + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the beginning of the input row + /// + /// @param inRow + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rbegin(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return rbegin() += (shape_.rows - inRow - 1) * shape_.cols; + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_reverse_iterator rbegin(size_type inRow) const + { + return crbegin(inRow); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the beginning of the flattened array + /// + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the beginning of the input row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crbegin(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return crbegin() += (shape_.rows - inRow - 1) * shape_.cols; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the beginning of the flattened array + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolbegin() noexcept + { + return reverse_column_iterator(colend()); + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolbegin(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return rcolbegin() += (shape_.cols - inCol - 1) * shape_.rows; + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolbegin() const noexcept + { + return crcolbegin(); + } + + //============================================================================ + // Method Description: + /// const iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolbegin(size_type inCol) const + { + return crcolbegin(inCol); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the beginning of the flattened array + /// + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolbegin() const noexcept + { + return const_reverse_column_iterator(ccolend()); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the beginning of the input column + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolbegin(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return crcolbegin() += (shape_.cols - inCol - 1) * shape_.rows; + } + + //============================================================================ + // Method Description: + /// iterator to 1 past the end of the flattened array + /// @return iterator + /// + [[nodiscard]] iterator end() noexcept + { + return begin() += size_; + } + + //============================================================================ + // Method Description: + /// iterator to the 1 past end of the row + /// + /// @param inRow + /// @return iterator + /// + [[nodiscard]] iterator end(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return begin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the flattened array + /// @return const_iterator + /// + [[nodiscard]] const_iterator end() const noexcept + { + return cend(); + } + + //============================================================================ + // Method Description: + /// const iterator to the 1 past end of the row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator end(size_type inRow) const + { + return cend(inRow); + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the flattened array + /// + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend() const noexcept + { + return cbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const iterator to 1 past the end of the input row + /// + /// @param inRow + /// @return const_iterator + /// + [[nodiscard]] const_iterator cend(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return cbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// reverse_iterator to 1 past the end of the flattened array + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rend() noexcept + { + return rbegin() += size_; + } + + //============================================================================ + // Method Description: + /// reverse_iterator to the 1 past end of the row + /// + /// @param inRow + /// @return reverse_iterator + /// + [[nodiscard]] reverse_iterator rend(size_type inRow) + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return rbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the flattened array + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator rend() const noexcept + { + return crend(); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to the 1 past end of the row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator rend(size_type inRow) const + { + return crend(inRow); + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the flattened array + /// + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crend() const noexcept + { + return crbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_reverse_iterator to 1 past the end of the input row + /// + /// @param inRow + /// @return const_reverse_iterator + /// + [[nodiscard]] const_reverse_iterator crend(size_type inRow) const + { + if (inRow >= shape_.rows) + { + THROW_INVALID_ARGUMENT_ERROR("input row is greater than the number of rows in the array."); + } + + return crbegin(inRow) += shape_.cols; + } + + //============================================================================ + // Method Description: + /// column_iterator to 1 past the end of the flattened array + /// @return column_iterator + /// + [[nodiscard]] column_iterator colend() noexcept + { + return colbegin() += size_; + } + + //============================================================================ + // Method Description: + /// column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return column_iterator + /// + [[nodiscard]] column_iterator colend(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return colbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// const column_iterator to 1 past the end of the flattened array + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colend() const noexcept + { + return ccolend(); + } + + //============================================================================ + // Method Description: + /// const column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator colend(size_type inCol) const + { + return ccolend(inCol); + } + + //============================================================================ + // Method Description: + /// const_column_iterator to 1 past the end of the flattened array + /// + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolend() const noexcept + { + return ccolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_column_iterator to 1 past the end of the input col + /// + /// @param inCol + /// @return const_column_iterator + /// + [[nodiscard]] const_column_iterator ccolend(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return ccolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to 1 past the end of the flattened array + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolend() noexcept + { + return rcolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// reverse_column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return reverse_column_iterator + /// + [[nodiscard]] reverse_column_iterator rcolend(size_type inCol) + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return rcolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the flattened array + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolend() const noexcept + { + return crcolend(); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to the 1 past end of the column + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator rcolend(size_type inCol) const + { + return crcolend(inCol); + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the flattened array + /// + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolend() const noexcept + { + return crcolbegin() += size_; + } + + //============================================================================ + // Method Description: + /// const_reverse_column_iterator to 1 past the end of the input col + /// + /// @param inCol + /// @return const_reverse_column_iterator + /// + [[nodiscard]] const_reverse_column_iterator crcolend(size_type inCol) const + { + if (inCol >= shape_.cols) + { + THROW_INVALID_ARGUMENT_ERROR("input col is greater than the number of cols in the array."); + } + + return crcolbegin(inCol) += shape_.rows; + } + + //============================================================================ + // Method Description: + /// Returns True if all elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.all.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray all(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::all_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::all_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().all(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns True if any elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.any.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray any(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::any_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::any_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().any(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return indices of the maximum values along the given axis. + /// Only the first index is returned. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argmax.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argmax(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { static_cast( + stl_algorithms::max_element(cbegin(), cend(), comparitor) - cbegin()) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = static_cast( + stl_algorithms::max_element(cbegin(row), cend(row), comparitor) - cbegin(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().argmax(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return indices of the minimum values along the given axis. + /// Only the first index is returned. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argmin.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argmin(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { static_cast( + stl_algorithms::min_element(cbegin(), cend(), comparitor) - cbegin()) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = static_cast( + stl_algorithms::min_element(cbegin(row), cend(row), comparitor) - cbegin(row)); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().argmin(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns the indices that would sort this array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.argsort.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray argsort(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + std::vector idx(size_); + std::iota(idx.begin(), idx.end(), 0); + + const auto function = [this](size_type i1, size_type i2) noexcept -> bool + { return (*this)[i1] < (*this)[i2]; }; + + stl_algorithms::stable_sort(idx.begin(), idx.end(), function); + return NdArray(idx); // NOLINT(modernize-return-braced-init-list) + } + case Axis::COL: + { + NdArray returnArray(shape_); + std::vector idx(shape_.cols); + + for (index_type row = 0; row < static_cast(shape_.rows); ++row) + { + std::iota(idx.begin(), idx.end(), 0); + + const auto function = [this, row](size_type i1, size_type i2) noexcept -> bool + { return operator()(row, i1) < operator()(row, i2); }; + + stl_algorithms::stable_sort(idx.begin(), idx.end(), function); + + for (index_type col = 0; col < static_cast(shape_.cols); ++col) + { + returnArray(row, col) = idx[static_cast(col)]; + } + } + return returnArray; + } + case Axis::ROW: + { + return transpose().argsort(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Arithmetic to Arithmetic + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + if constexpr (std::is_same_v) + { + return *this; + } + else + { + NdArray outArray(shape_); + stl_algorithms::transform(cbegin(), + cend(), + outArray.begin(), + [](dtype value) -> dtypeOut { return static_cast(value); }); + + return outArray; + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Arithmetic to Complex + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + NdArray outArray(shape_); + + const auto function = [](const_reference value) -> dtypeOut + { return std::complex(value); }; + + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Complex to Complex + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + if constexpr (std::is_same_v) + { + return *this; + } + else + { + const auto function = [](const_reference value) noexcept -> dtypeOut + { return complex_cast(value); }; + + NdArray outArray(shape_); + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + return outArray; + } + } + + //============================================================================ + // Method Description: + /// Returns a copy of the array, cast to a specified type. + /// Complex to Arithmetic + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.astype.html + /// + /// @return NdArray + /// + template, int> = 0, + std::enable_if_t, int> = 0, + std::enable_if_t, int> = 0> + [[nodiscard]] NdArray astype() const + { + NdArray outArray(shape_); + + const auto function = [](const_reference value) -> dtypeOut { return static_cast(value.real()); }; + + stl_algorithms::transform(cbegin(), cend(), outArray.begin(), function); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the last element of the flattened array. + /// + /// @return dtype + /// + [[nodiscard]] const_reference back() const noexcept + { + return *(cend() - 1); + } + + //============================================================================ + // Method Description: + /// Returns a reference the last element of the flattened array. + /// + /// @return dtype + /// + reference back() noexcept + { + return *(end() - 1); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the last element of the input row. + /// + /// @return dtype + /// + [[nodiscard]] const_reference back(size_type row) const + { + return *(cend(row) - 1); + } + + //============================================================================ + // Method Description: + /// Returns a reference the last element of the input row. + /// + /// @return dtype + /// + reference back(size_type row) + { + return *(end(row) - 1); + } + + //============================================================================ + // Method Description: + /// Swap the bytes of the array elements in place + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.byteswap.html + /// + /// @return NdArray + /// + self_type& byteswap() noexcept + { + STATIC_ASSERT_INTEGER(dtype); + + stl_algorithms::for_each(begin(), + end(), + [](dtype& value) noexcept -> void { value = endian::byteSwap(value); }); + + switch (endianess_) + { + case Endian::NATIVE: + { + endianess_ = endian::isLittleEndian() ? Endian::BIG : Endian::LITTLE; + break; + } + case Endian::LITTLE: + { + endianess_ = Endian::BIG; + break; + } + case Endian::BIG: + { + endianess_ = Endian::LITTLE; + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Returns an array whose values are limited to [min, max]. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.clip.html + /// + /// @param inMin: min value to clip to + /// @param inMax: max value to clip to + /// @return clipped value + /// + [[nodiscard]] self_type clip(value_type inMin, value_type inMax) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + self_type outArray(shape_); + stl_algorithms::transform(cbegin(), + cend(), + outArray.begin(), + [inMin, inMax](dtype value) noexcept -> dtype + { +#ifdef __cpp_lib_clamp + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; + + return std::clamp(value, inMin, inMax, comparitor); +#else + if (value < inMin) + { + return inMin; + } + else if (value > inMax) + { + return inMax; + } + + return value; +#endif + }); + + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns the full column of the array + /// + /// + /// @return Shape + /// + [[nodiscard]] self_type column(size_type inColumn) + { + return operator()(rSlice(), inColumn); + } + + //============================================================================ + // Method Description: + /// returns whether or not a value is included the array + /// + /// @param inValue + /// @param inAxis (Optional, default NONE) + /// @return bool + /// + [[nodiscard]] NdArray contains(value_type inValue, Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::find(cbegin(), cend(), inValue) != cend() }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (size_type row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::find(cbegin(row), cend(row), inValue) != cend(row); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().contains(inValue, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return a copy of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.copy.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type copy() const + { + return self_type(*this); + } + + //============================================================================ + // Method Description: + /// Return the cumulative product of the elements along the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.cumprod.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type cumprod(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray(1, size_); + returnArray[0] = front(); + for (size_type i = 1; i < size_; ++i) + { + returnArray[i] = returnArray[i - 1] * array_[i]; + } + + return returnArray; + } + case Axis::COL: + { + self_type returnArray(shape_); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(row, 0) = operator()(row, 0); + for (uint32 col = 1; col < shape_.cols; ++col) + { + returnArray(row, col) = returnArray(row, col - 1) * operator()(row, col); + } + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().cumprod(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the cumulative sum of the elements along the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.cumsum.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type cumsum(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray(1, size_); + returnArray[0] = front(); + for (size_type i = 1; i < size_; ++i) + { + returnArray[i] = returnArray[i - 1] + array_[i]; + } + + return returnArray; + } + case Axis::COL: + { + self_type returnArray(shape_); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(row, 0) = operator()(row, 0); + for (uint32 col = 1; col < shape_.cols; ++col) + { + returnArray(row, col) = returnArray(row, col - 1) + operator()(row, col); + } + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().cumsum(Axis::COL).transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns the raw pointer to the underlying data + /// @return pointer + /// + [[nodiscard]] pointer data() noexcept + { + return array_; + } + + //============================================================================ + // Method Description: + /// Returns the raw pointer to the underlying data + /// @return const_pointer + /// + [[nodiscard]] const_pointer data() const noexcept + { + return array_; + } + + //============================================================================ + // Method Description: + /// Releases the internal data pointer so that the destructor + /// will not call delete on it, and returns the raw pointer + /// to the underlying data. + /// @return pointer + /// + [[nodiscard]] pointer dataRelease() noexcept + { + ownsPtr_ = false; + return data(); + } + + //============================================================================ + // Method Description: + /// Return specified diagonals. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.diagonal.html + /// + /// @param inOffset: Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults + /// to 0. + /// @param inAxis: (Optional, default ROW) axis the offset is applied to + /// @return NdArray + /// + [[nodiscard]] self_type diagonal(index_type inOffset = 0, Axis inAxis = Axis::ROW) const + { + switch (inAxis) + { + case Axis::COL: + { + std::vector diagnolValues; + size_type col = 0; + for (index_type row = inOffset; row < static_cast(shape_.rows); ++row) + { + if (row < 0) + { + ++col; + continue; + } + if (col >= shape_.cols) + { + break; + } + + diagnolValues.push_back(operator()(static_cast(row), col)); + ++col; + } + + return self_type(diagnolValues); + } + case Axis::ROW: + { + return transpose().diagonal(inOffset, Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return size of the axis dimension + /// + /// @param inAxis: the array axis + /// @return size of the dimension + /// + [[nodiscard]] size_type dimSize(Axis inAxis) const noexcept + { + switch (inAxis) + { + case Axis::NONE: + { + return size(); + } + case Axis::ROW: + { + return numRows(); + } + case Axis::COL: + { + return numCols(); + } + default: + { + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Dot product of two arrays. + /// + /// For 2-D arrays it is equivalent to matrix multiplication, + /// and for 1-D arrays to inner product of vectors. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dot.html + /// + /// @param inOtherArray + /// @return dot product + /// + [[nodiscard]] self_type dot(const self_type& inOtherArray) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (shape_ == inOtherArray.shape_ && (shape_.rows == 1 || shape_.cols == 1)) + { + dtype dotProduct = std::inner_product(cbegin(), cend(), inOtherArray.cbegin(), dtype{ 0 }); + self_type returnArray = { dotProduct }; + return returnArray; + } + if (shape_.cols == inOtherArray.shape_.rows) + { + // 2D array, use matrix multiplication + self_type returnArray(shape_.rows, inOtherArray.shape_.cols); + auto otherArrayT = inOtherArray.transpose(); + + for (uint32 i = 0; i < shape_.rows; ++i) + { + for (uint32 j = 0; j < otherArrayT.shape_.rows; ++j) + { + returnArray(i, j) = + std::inner_product(otherArrayT.cbegin(j), otherArrayT.cend(j), cbegin(i), dtype{ 0 }); + } + } + + return returnArray; + } + + std::string errStr = "shapes of [" + utils::num2str(shape_.rows) + ", " + utils::num2str(shape_.cols) + "]"; + errStr += " and [" + utils::num2str(inOtherArray.shape_.rows) + ", " + + utils::num2str(inOtherArray.shape_.cols) + "]"; + errStr += " are not consistent."; + THROW_INVALID_ARGUMENT_ERROR(errStr); + + return self_type(); // get rid of compiler warning + } + + //============================================================================ + // Method Description: + /// Dump a binary file of the array to the specified file. + /// The array can be read back with nc::load. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.dump.html + /// + /// @param inFilename + /// + void dump(const std::string& inFilename) const + { + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("bin"); + } + + std::ofstream ofile(f.c_str(), std::ios::binary); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Unable to open the input file:\n\t" + inFilename); + } + + if (array_ != nullptr) + { + ofile.write(reinterpret_cast(array_), size_ * sizeof(dtype)); + } + ofile.close(); + } + + //============================================================================ + // Method Description: + /// Return the NdArrays endianess + /// + /// @return Endian + /// + [[nodiscard]] Endian endianess() const noexcept + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return endianess_; + } + + //============================================================================ + // Method Description: + /// Fill the array with a scalar value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.fill.html + /// + /// @param inFillValue + /// @return None + /// + self_type& fill(value_type inFillValue) noexcept + { + stl_algorithms::fill(begin(), end(), inFillValue); + return *this; + } + + //============================================================================ + // Method Description: + /// Return the indices of the flattened array of the + /// elements that are non-zero. + /// + /// @return NdArray + /// + [[nodiscard]] NdArray flatnonzero() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::vector indices; + size_type idx = 0; + for (auto value : *this) + { + if (!utils::essentiallyEqual(value, dtype{ 0 })) + { + indices.push_back(idx); + } + ++idx; + } + + return NdArray(indices); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Return a copy of the array collapsed into one dimension. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.flatten.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type flatten() const + { + self_type outArray(1, size_); + stl_algorithms::copy(cbegin(), cend(), outArray.begin()); + return outArray; + } + + //============================================================================ + // Method Description: + /// Returns a copy of the first element of the flattened array. + /// + /// @return dtype + /// + [[nodiscard]] const_reference front() const noexcept + { + return *cbegin(); + } + + //============================================================================ + // Method Description: + /// Returns a reference to the first element of the flattened array. + /// + /// @return dtype + /// + reference front() noexcept + { + return *begin(); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the first element of the input row. + /// + /// @return dtype + /// + [[nodiscard]] const_reference front(size_type row) const + { + return *cbegin(row); + } + + //============================================================================ + // Method Description: + /// Returns a reference to the first element of the input row. + /// + /// @return dtype + /// + reference front(size_type row) + { + return *begin(row); + } + + //============================================================================ + // Method Description: + /// Returns a new flat array with the givin flat input indices. + /// + /// @param inIndices + /// @return values + /// + [[nodiscard]] self_type getByIndices(const NdArray& inIndices) const + { + return operator[](inIndices); + } + + //============================================================================ + // Method Description: + /// Takes in a boolean mask the same size as the array + /// and returns a flattened array with the values cooresponding + /// to the input mask. + /// + /// @param inMask + /// @return values + /// + [[nodiscard]] self_type getByMask(const NdArray& inMask) const + { + return operator[](inMask); + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is empty. ie the default constructor + /// was used. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isempty() const noexcept + { + return size_ == 0; + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is flat. ie the number of columns or + /// rows is equal to one. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isflat() const noexcept + { + return !isscalar() && (shape_.rows == 1 || shape_.cols == 1); + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is scalar + /// + /// @return boolean + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool isscalar() const noexcept + { + return size_ == 1; + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is sorted. + /// + /// @param inAxis + /// @return boolean + /// + [[nodiscard]] NdArray issorted(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + return { stl_algorithms::is_sorted(cbegin(), cend(), comparitor) }; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::is_sorted(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().issorted(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return if the NdArray is square. + /// + /// @return boolean + /// + // NOLINTNEXTLINE(modernize-use-nodiscard) + bool issquare() const noexcept + { + return shape_.issquare(); + } + + //============================================================================ + // Method Description: + /// Copy an element of an array to a standard C++ scalar and return it. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.item.html + /// + /// @return array element + /// + [[nodiscard]] value_type item() const + { + if (!isscalar()) + { + THROW_INVALID_ARGUMENT_ERROR("Can only convert an array of size 1 to a C++ scalar"); + } + + return front(); + } + + //============================================================================ + // Method Description: + /// Return the maximum along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.max.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type max(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { *stl_algorithms::max_element(cbegin(), cend(), comparitor) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = *stl_algorithms::max_element(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().max(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the minimum along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.min.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type min(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { *stl_algorithms::min_element(cbegin(), cend(), comparitor) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = *stl_algorithms::min_element(cbegin(row), cend(row), comparitor); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().min(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the median along a given axis. + /// If the dtype is floating point then the middle elements will be + /// averaged for arrays of even number of elements. + /// If the dtype is integral then the middle elements will be intager + /// averaged (rounded down to integer) for arrays of even number of elements. + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type median(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + if (size_ == 0) + { + THROW_RUNTIME_ERROR("Median is undefined for an array of size = 0."); + } + + switch (inAxis) + { + case Axis::NONE: + { + self_type copyArray(*this); + + const size_type middleIdx = size_ / 2; // integer division + stl_algorithms::nth_element(copyArray.begin(), + copyArray.begin() + middleIdx, + copyArray.end(), + comparitor); + + dtype medianValue = copyArray.array_[middleIdx]; + if (size_ % 2 == 0) + { + const size_type lhsIndex = middleIdx - 1; + stl_algorithms::nth_element(copyArray.begin(), + copyArray.begin() + lhsIndex, + copyArray.end(), + comparitor); + medianValue = + (medianValue + copyArray.array_[lhsIndex]) / dtype{ 2 }; // potentially integer division, ok + } + + return { medianValue }; + } + case Axis::COL: + { + self_type copyArray(*this); + self_type returnArray(1, shape_.rows); + + const bool isEven = shape_.cols % 2 == 0; + for (uint32 row = 0; row < shape_.rows; ++row) + { + const uint32 middleIdx = shape_.cols / 2; // integer division + stl_algorithms::nth_element(copyArray.begin(row), + copyArray.begin(row) + middleIdx, + copyArray.end(row), + comparitor); + + dtype medianValue = copyArray(row, middleIdx); + if (isEven) + { + const size_type lhsIndex = middleIdx - 1; + stl_algorithms::nth_element(copyArray.begin(row), + copyArray.begin(row) + lhsIndex, + copyArray.end(row), + comparitor); + medianValue = (medianValue + copyArray(row, lhsIndex)) / + dtype{ 2 }; // potentially integer division, ok + } + + returnArray(0, row) = medianValue; + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().median(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Fills the array with nans. + /// + /// + self_type& nans() noexcept + + { + STATIC_ASSERT_FLOAT(dtype); + + fill(constants::nan); + return *this; + } + + //============================================================================ + // Method Description: + /// Returns the number of bytes held by the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.nbytes.html + /// + /// @return number of bytes + /// + [[nodiscard]] uint64 nbytes() const noexcept + { + return static_cast(sizeof(dtype) * size_); + } + + //============================================================================ + // Method Description: + /// Return the array with the same data viewed with a + /// different byte order. only works for integer types. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.newbyteorder.html + /// + /// @param inEndianess + /// @return NdArray + /// + [[nodiscard]] self_type newbyteorder(Endian inEndianess) const + { + STATIC_ASSERT_INTEGER(dtype); + + const bool nativeIsLittle = endian::isLittleEndian(); + + switch (endianess_) + { + case Endian::NATIVE: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + return NdArray(*this); + } + case Endian::BIG: + { + if (nativeIsLittle) + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::BIG; + return outArray; + } + else + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::BIG; + return outArray; + } + } + case Endian::LITTLE: + { + if (nativeIsLittle) + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + else + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + case Endian::BIG: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + if (nativeIsLittle) + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + else + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + } + case Endian::BIG: + { + return NdArray(*this); + } + case Endian::LITTLE: + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::LITTLE; + return outArray; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + case Endian::LITTLE: + { + switch (inEndianess) + { + case Endian::NATIVE: + { + if (nativeIsLittle) + { + auto outArray = NdArray(*this); + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + else + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::NATIVE; + return outArray; + } + } + case Endian::BIG: + { + self_type outArray(shape_); + + stl_algorithms::transform(cbegin(), end(), outArray.begin(), endian::byteSwap); + + outArray.endianess_ = Endian::BIG; + return outArray; + } + case Endian::LITTLE: + { + return NdArray(*this); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + break; + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented endian type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Returns True if none elements evaluate to True or non zero + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.any.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] NdArray none(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype i) -> bool { return !utils::essentiallyEqual(i, dtype{ 0 }); }; + + switch (inAxis) + { + case Axis::NONE: + { + NdArray returnArray = { stl_algorithms::none_of(cbegin(), cend(), function) }; + return returnArray; + } + case Axis::COL: + { + NdArray returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = stl_algorithms::none_of(cbegin(row), cend(row), function); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().none(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Return the row/col indices of the array of the + /// elements that are non-zero. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.nonzero.html + /// + /// @return std::pair where first is the row indices and second is the + /// column indices + /// + [[nodiscard]] std::pair, NdArray> nonzero() const; + + //============================================================================ + // Method Description: + /// Returns the number of columns in the array + /// + /// + /// @return size_type + /// + [[nodiscard]] size_type numCols() const noexcept + { + return shape_.cols; + } + + //============================================================================ + // Method Description: + /// Returns the number of rows in the array + /// + /// + /// @return size_type + /// + [[nodiscard]] size_type numRows() const noexcept + { + return shape_.rows; + } + + //============================================================================ + // Method Description: + /// Fills the array with ones + /// + /// + self_type& ones() noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + fill(dtype{ 1 }); + return *this; + } + + //============================================================================ + // Method Description: + /// Returns whether or not the array object owns the underlying data + /// + /// @return bool + /// + bool ownsInternalData() noexcept + { + return ownsPtr_; + } + + //============================================================================ + // Method Description: + /// Rearranges the elements in the array in such a way that + /// value of the element in kth position is in the position it + /// would be in a sorted array. All elements smaller than the kth + /// element are moved before this element and all equal or greater + /// are moved behind it. The ordering of the elements in the two + /// partitions is undefined. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.partition.html + /// + /// @param inKth: kth element + /// @param inAxis (Optional, default NONE) + /// @return None + /// + self_type& partition(size_type inKth, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; // cppcheck-suppress returnTempReference + + switch (inAxis) + { + case Axis::NONE: + { + if (inKth >= size_) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(size_) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + stl_algorithms::nth_element(begin(), begin() + inKth, end(), comparitor); + break; + } + case Axis::COL: + { + if (inKth >= shape_.cols) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(shape_.cols) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + for (uint32 row = 0; row < shape_.rows; ++row) + { + stl_algorithms::nth_element(begin(row), begin(row) + inKth, end(row), comparitor); + } + break; + } + case Axis::ROW: + { + if (inKth >= shape_.rows) + { + std::string errStr = "kth(=" + utils::num2str(inKth); + errStr += ") out of bounds (" + utils::num2str(shape_.rows) + ")"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + self_type transposedArray = transpose(); + for (uint32 row = 0; row < transposedArray.shape_.rows; ++row) + { + stl_algorithms::nth_element(transposedArray.begin(row), + transposedArray.begin(row) + inKth, + transposedArray.end(row), + comparitor); + } + *this = transposedArray.transpose(); + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Prints the array to the console. + /// + /// + void print() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::cout << *this; + } + + //============================================================================ + // Method Description: + /// Return the product of the array elements over the given axis + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.prod.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type prod(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + dtype product = std::accumulate(cbegin(), cend(), dtype{ 1 }, std::multiplies()); + self_type returnArray = { product }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = + std::accumulate(cbegin(row), cend(row), dtype{ 1 }, std::multiplies()); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().prod(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Peak to peak (maximum - minimum) value along a given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.ptp.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type ptp(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool { return lhs < rhs; }; + + switch (inAxis) + { + case Axis::NONE: + { + const auto result = stl_algorithms::minmax_element(cbegin(), cend(), comparitor); + self_type returnArray = { *result.second - *result.first }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + const auto result = stl_algorithms::minmax_element(cbegin(row), cend(row), comparitor); + returnArray(0, row) = *result.second - *result.first; + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().ptp(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// set the flat index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndex + /// @param inValue + /// + self_type& put(index_type inIndex, const value_type& inValue) + { + at(inIndex) = inValue; + + return *this; + } + + //============================================================================ + // Method Description: + /// set the 2D row/col index element to the value + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRow + /// @param inCol + /// @param inValue + /// + self_type& put(index_type inRow, index_type inCol, const value_type& inValue) + { + at(inRow, inCol) = inValue; + + return *this; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inIndices, const value_type& inValue) + { + for (auto index : inIndices) + { + put(index, inValue); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Set a.flat[n] = values[n] for all n in indices. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inIndices, const self_type& inValues) + { + if (inValues.isscalar()) + { + return put(inIndices, inValues.item()); + } + else if (inIndices.size() != inValues.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Input indices do not match values dimensions."); + } + + size_type counter = 0; + for (auto index : inIndices) + { + put(index, inValues[counter++]); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inSlice, const value_type& inValue) + { + return put(toIndices(inSlice, Axis::NONE), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(const Slice& inSlice, const self_type& inValues) + { + return put(toIndices(inSlice, Axis::NONE), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + self_type& put(const RowIndices& inRowIndices, const ColIndices& inColIndices, const value_type& inValue) + { + stl_algorithms::for_each(inRowIndices.begin(), + inRowIndices.end(), + [this, &inColIndices, &inValue](const auto row) + { + stl_algorithms::for_each(inColIndices.begin(), + inColIndices.end(), + [this, row, &inValue](const auto col) + { this->put(row, col, inValue); }); + }); + + return *this; + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const RowIndices& inRowIndices, const Slice& inColSlice, const value_type& inValue) + { + return put(inRowIndices, toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Slice& inRowSlice, const ColIndices& inColIndices, const value_type& inValue) + { + return put(toIndices(inRowSlice, Axis::ROW), inColIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, const Slice& inColSlice, const value_type& inValue) + { + return put(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inRowIndices, index_type inColIndex, const value_type& inValue) + { + const NdArray colIndices = { inColIndex }; + return put(inRowIndices, colIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndex + /// @param inValue + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, index_type inColIndex, const value_type& inValue) + { + const NdArray colIndices = { inColIndex }; + return put(toIndices(inRowSlice, Axis::ROW), colIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColIndices + /// @param inValue + /// @return reference to self + /// + template = 0> + self_type& put(index_type inRowIndex, const Indices& inColIndices, const value_type& inValue) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, inColIndices, inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input value. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColSlice + /// @param inValue + /// @return reference to self + /// + self_type& put(index_type inRowIndex, const Slice& inColSlice, const value_type& inValue) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, toIndices(inColSlice, Axis::COL), inValue); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0, + type_traits::ndarray_int_concept = 0> + self_type& put(const RowIndices& inRowIndices, const ColIndices& inColIndices, const self_type& inValues) + { + std::vector indices; + indices.reserve(inRowIndices.size() * inColIndices.size()); + std::for_each(inRowIndices.begin(), + inRowIndices.end(), + [this, &inColIndices, &indices](auto row) + { + if constexpr (std::is_signed_v) + { + if (row < 0) + { + row += shape_.rows; + } + // still + if (row < 0) + { + THROW_INVALID_ARGUMENT_ERROR("row index exceeds matrix dimensions"); + } + } + std::for_each(inColIndices.begin(), + inColIndices.end(), + [this, row, &indices](auto col) + { + if constexpr (std::is_signed_v) + { + if (col < 0) + { + col += shape_.cols; + } + // still + if (col < 0) + { + THROW_INVALID_ARGUMENT_ERROR( + "col index exceeds matrix dimensions"); + } + } + indices.push_back(row * shape_.cols + col); + }); + }); + + return put(NdArray(indices.data(), indices.size(), false), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const RowIndices& inRowIndices, Slice inColSlice, const self_type& inValues) + { + return put(inRowIndices, toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(Slice inRowSlice, const ColIndices& inColIndices, const self_type& inValues) + { + return put(toIndices(inRowSlice, Axis::ROW), inColIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(Slice inRowSlice, Slice inColSlice, const self_type& inValues) + { + return put(toIndices(inRowSlice, Axis::ROW), toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndices + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(const Indices& inRowIndices, index_type inColIndex, const self_type& inValues) + { + const NdArray colIndices = { inColIndex }; + return put(inRowIndices, colIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowSlice + /// @param inColIndex + /// @param inValues + /// @return reference to self + /// + self_type& put(const Slice& inRowSlice, index_type inColIndex, const self_type& inValues) + { + const NdArray colIndices = { inColIndex }; + return put(toIndices(inRowSlice, Axis::ROW), colIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColIndices + /// @param inValues + /// @return reference to self + /// + template = 0> + self_type& put(index_type inRowIndex, const Indices& inColIndices, const self_type& inValues) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, inColIndices, inValues); + } + + //============================================================================ + // Method Description: + /// Set the slice indices to the input values. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.put.html + /// + /// @param inRowIndex + /// @param inColSlice + /// @param inValues + /// @return reference to self + /// + self_type& put(index_type inRowIndex, const Slice& inColSlice, const self_type& inValues) + { + const NdArray rowIndices = { inRowIndex }; + return put(rowIndices, toIndices(inColSlice, Axis::COL), inValues); + } + + //============================================================================ + // Method Description: + /// Set the mask indices to the input value. + /// + /// @param inMask + /// @param inValue + /// + self_type& putMask(const NdArray& inMask, const value_type& inValue) + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the array it is masking."); + } + + return put(inMask.flatnonzero(), inValue); + } + + //============================================================================ + // Method Description: + /// Set the mask indices to the input values. + /// + /// @param inMask + /// @param inValues + /// + self_type& putMask(const NdArray& inMask, const self_type& inValues) + { + if (inMask.shape() != shape_) + { + THROW_INVALID_ARGUMENT_ERROR("input inMask must be the same shape as the array it is masking."); + } + + if (inValues.isscalar()) + { + put(inMask.flatnonzero(), inValues.item()); + } + else + { + put(inMask.flatnonzero(), inValues); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Flattens the array but does not make a copy. + /// + /// Numpy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html + /// + /// @return NdArray + /// + self_type& ravel() + { + reshape(size_); + return *this; + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.repeat.html + /// + /// @param inNumRows + /// @param inNumCols + /// @return NdArray + /// + [[nodiscard]] self_type repeat(size_type inNumRows, size_type inNumCols) const + { + self_type returnArray(shape_.rows * inNumRows, shape_.cols * inNumCols); + + for (size_type row = 0; row < inNumRows; ++row) + { + for (size_type col = 0; col < inNumCols; ++col) + { + std::vector indices(shape_.size()); + + const size_type rowStart = row * shape_.rows; + const size_type colStart = col * shape_.cols; + + const size_type rowEnd = (row + 1) * shape_.rows; + const size_type colEnd = (col + 1) * shape_.cols; + + size_type counter = 0; + for (size_type rowIdx = rowStart; rowIdx < rowEnd; ++rowIdx) + { + for (size_type colIdx = colStart; colIdx < colEnd; ++colIdx) + { + indices[counter++] = rowIdx * returnArray.shape_.cols + colIdx; + } + } + + returnArray.put(NdArray(indices), *this); + } + } + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Repeat elements of an array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.repeat.html + /// + /// @param inRepeatShape + /// @return NdArray + /// + [[nodiscard]] self_type repeat(const Shape& inRepeatShape) const + { + return repeat(inRepeatShape.rows, inRepeatShape.cols); + } + + //============================================================================ + // Method Description: + /// Replaces a value of the array with another value + /// + /// @param oldValue: the value to replace + /// @param newValue: the value to replace with + /// + self_type& replace(value_type oldValue, value_type newValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + stl_algorithms::replace(begin(), end(), oldValue, newValue); + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inSize + /// + self_type& reshape(size_type inSize) + { + if (inSize != size_) + { + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into shape "; + errStr += "[" + utils::num2str(1) + ", " + utils::num2str(inSize) + "]"; + THROW_RUNTIME_ERROR(errStr); + } + + shape_.rows = 1; + shape_.cols = inSize; + + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inNumRows + /// @param inNumCols + /// + self_type& reshape(index_type inNumRows, index_type inNumCols) + { + if (inNumRows < 0) + { + if (size_ % inNumCols == 0) + { + return reshape(size_ / inNumCols, inNumCols); + } + + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into a shape "; + errStr += "with " + utils::num2str(inNumCols) + " columns"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + if (inNumCols < 0) + { + if (size_ % inNumRows == 0) + { + return reshape(inNumRows, size_ / inNumRows); + } + + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into a shape "; + errStr += "with " + utils::num2str(inNumRows) + " rows"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + if (static_cast(inNumRows * inNumCols) != size_) + { + std::string errStr = "Cannot reshape array of size " + utils::num2str(size_) + " into shape "; + errStr += "[" + utils::num2str(inNumRows) + ", " + utils::num2str(inNumCols) + "]"; + THROW_INVALID_ARGUMENT_ERROR(errStr); + } + + shape_.rows = static_cast(inNumRows); + shape_.cols = static_cast(inNumCols); + + return *this; + } + + //============================================================================ + // Method Description: + /// The new shape should be compatible with the original shape. If an single integer, + /// then the result will be a 1-D array of that length. One shape dimension + /// can be -1. In this case, the value is inferred from the length of the + /// array and remaining dimensions. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.reshape.html + /// + /// @param inShape + /// + self_type& reshape(const Shape& inShape) + { + return reshape(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inNumRows + /// @param inNumCols + /// + self_type& resizeFast(size_type inNumRows, size_type inNumCols) + { + newArray(Shape(inNumRows, inNumCols)); + return *this; + } + + //============================================================================ + // Method Description: + /// Change shape and size of array in-place. All previous + /// data of the array is lost. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inShape + /// + self_type& resizeFast(const Shape& inShape) + { + return resizeFast(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inNumRows + /// @param inNumCols + /// + self_type& resizeSlow(size_type inNumRows, size_type inNumCols) + { + std::vector oldData(size_); + stl_algorithms::copy(begin(), end(), oldData.begin()); + + const Shape inShape(inNumRows, inNumCols); + const Shape oldShape = shape_; + + newArray(inShape); + + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 0; col < inShape.cols; ++col) + { + if (row >= oldShape.rows || col >= oldShape.cols) + { + operator()(row, col) = dtype{ 0 }; // zero fill + } + else + { + operator()(row, col) = oldData[row * oldShape.cols + col]; + } + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Return a new array with the specified shape. If new shape + /// is larger than old shape then array will be padded with zeros. + /// If new shape is smaller than the old shape then the data will + /// be discarded. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.resize.html + /// + /// @param inShape + /// + self_type& resizeSlow(const Shape& inShape) + { + return resizeSlow(inShape.rows, inShape.cols); + } + + //============================================================================ + // Method Description: + /// Return a with each element rounded to the given number + /// of decimals. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.round.html + /// + /// @param inNumDecimals (default 0) + /// @return NdArray + /// + [[nodiscard]] self_type round(uint8 inNumDecimals = 0) const + { + STATIC_ASSERT_FLOAT(dtype); + + self_type returnArray(shape_); + const double multFactor = utils::power(10., inNumDecimals); + const auto function = [multFactor](dtype value) noexcept -> dtype + { return static_cast(std::nearbyint(static_cast(value) * multFactor) / multFactor); }; + + stl_algorithms::transform(cbegin(), cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns the full row of the array + /// + /// + /// @return Shape + /// + [[nodiscard]] self_type row(size_type inRow) + { + return self_type(cbegin(inRow), cend(inRow)); + } + + //============================================================================ + // Method Description: + /// Return the shape of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.shape.html + /// + /// @return Shape + /// + [[nodiscard]] Shape shape() const noexcept + { + return shape_; + } + + //============================================================================ + // Method Description: + /// Return the size of the array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.size.html + /// + /// @return size + /// + [[nodiscard]] size_type size() const noexcept + { + return size_; + } + + //============================================================================ + // Method Description: + /// Sort an array, in-place. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.sort.html + /// + /// @param inAxis (Optional, default NONE) + /// @return size + /// + self_type& sort(Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto comparitor = [](dtype lhs, dtype rhs) noexcept -> bool + { return lhs < rhs; }; // cppcheck-suppress returnTempReference + + switch (inAxis) + { + case Axis::NONE: + { + stl_algorithms::sort(begin(), end(), comparitor); + break; + } + case Axis::COL: + { + for (uint32 row = 0; row < shape_.rows; ++row) + { + stl_algorithms::sort(begin(row), end(row), comparitor); + } + break; + } + case Axis::ROW: + { + self_type transposedArray = transpose(); + for (uint32 row = 0; row < transposedArray.shape_.rows; ++row) + { + stl_algorithms::sort(transposedArray.begin(row), transposedArray.end(row), comparitor); + } + + *this = transposedArray.transpose(); + break; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// returns the NdArray as a string representation + /// + /// @return string + /// + [[nodiscard]] std::string str() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::string out; + out += "["; + for (uint32 row = 0; row < shape_.rows; ++row) + { + out += "["; + for (uint32 col = 0; col < shape_.cols; ++col) + { + out += utils::value2str(operator()(row, col)) + ", "; + } + + if (row == shape_.rows - 1) + { + out += "]"; + } + else + { + out += "]\n"; + } + } + out += "]\n"; + return out; + } + + //============================================================================ + // Method Description: + /// Return the sum of the array elements over the given axis. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.sum.html + /// + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + [[nodiscard]] self_type sum(Axis inAxis = Axis::NONE) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + self_type returnArray = { std::accumulate(cbegin(), cend(), dtype{ 0 }) }; + return returnArray; + } + case Axis::COL: + { + self_type returnArray(1, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + returnArray(0, row) = std::accumulate(cbegin(row), cend(row), dtype{ 0 }); + } + + return returnArray; + } + case Axis::ROW: + { + return transpose().sum(Axis::COL); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } + + //============================================================================ + // Method Description: + /// Interchange two axes of an array. Equivalent to transpose... + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.swapaxes.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type swapaxes() const + { + return transpose(); + } + + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param colIdx1 + /// @param colIdx2 + /// @return reference to self + /// + self_type& swapCols(index_type colIdx1, index_type colIdx2) noexcept + { + for (index_type row = 0; row < static_cast(shape_.rows); ++row) + { + std::swap(operator()(row, colIdx1), operator()(row, colIdx2)); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Swaps rows of the array + /// + /// @param rowIdx1 + /// @param rowIdx2 + /// + /// @return reference to self + self_type& swapRows(index_type rowIdx1, index_type rowIdx2) noexcept + { + for (index_type col = 0; col < static_cast(shape_.cols); ++col) + { + std::swap(operator()(rowIdx1, col), operator()(rowIdx2, col)); + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Write array to a file as binary. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.tofile.html + /// + /// @param inFilename + /// @return None + /// + void tofile(const std::string& inFilename) const + { + dump(inFilename); + } + + //============================================================================ + // Method Description: + /// Write array to a file as text. + /// The data produced by this method can be recovered + /// using the function fromfile(). + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.tofile.html + /// + /// @param inFilename + /// @param inSep: Separator between array items for text output. + /// @return None + /// + void tofile(const std::string& inFilename, const char inSep) const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::filesystem::path f(inFilename); + if (!f.has_extension()) + { + f.replace_extension("txt"); + } + + std::ofstream ofile(f.c_str()); + if (!ofile.good()) + { + THROW_RUNTIME_ERROR("Input file could not be opened:\n\t" + inFilename); + } + + size_type counter = 0; + for (auto value : *this) + { + ofile << value; + if (counter++ != size_ - 1) + { + ofile << inSep; + } + } + ofile.close(); + } + + //============================================================================ + // Method Description: + /// Converts the slice object to an NdArray of indices for this array + /// + /// @param inSlice: the slice object + /// @param inAxis: the array axis + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toIndices(Slice inSlice, Axis inAxis = Axis::NONE) const + { + size_type numElements = 0; + switch (inAxis) + { + case Axis::NONE: + { + numElements = inSlice.numElements(size_); + break; + } + case Axis::ROW: + { + numElements = inSlice.numElements(shape_.rows); + break; + } + case Axis::COL: + { + numElements = inSlice.numElements(shape_.cols); + break; + } + default: + { + // not actually possible, getting rid of compiler warning + THROW_INVALID_ARGUMENT_ERROR("Invalid 'inAxis' option"); + } + } + + if (numElements == 0) + { + return {}; + } + + NdArray indices(1, numElements); + indices[0] = static_cast(inSlice.start); + for (size_type i = 1; i < indices.size(); ++i) + { + indices[static_cast(i)] = static_cast( + indices[static_cast(i - size_type{ 1 })] + static_cast(inSlice.step)); + } + + return indices; + } + + //============================================================================ + // Method Description: + /// Write flattened array to an STL vector + /// + /// @return std::vector + /// + [[nodiscard]] std::vector toStlVector() const + { + return std::vector(cbegin(), cend()); + } + + //============================================================================ + // Method Description: + /// Return the sum along diagonals of the array. + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.trace.html + /// + /// @param inOffset: Offset of the diagonal from the main diagonal. Can be both positive and negative. Defaults + /// to 0. + /// @param inAxis: (Optional, default ROW) Axis to offset from + /// + /// @return value + /// + [[nodiscard]] value_type trace(size_type inOffset = 0, Axis inAxis = Axis::ROW) const noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + size_type rowStart = 0; + size_type colStart = 0; + switch (inAxis) + { + case Axis::ROW: + { + rowStart += inOffset; + break; + } + case Axis::COL: + { + colStart += inOffset; + break; + } + default: + { + // if the user input NONE, override back to ROW + inAxis = Axis::ROW; + break; + } + } + + if (rowStart >= shape_.rows || colStart >= shape_.cols) + { + return dtype{ 0 }; + } + + size_type col = colStart; + dtype sum = 0; + for (size_type row = rowStart; row < shape_.rows; ++row) + { + if (col >= shape_.cols) + { + break; + } + sum += operator()(row, col++); + } + + return sum; + } + + //============================================================================ + // Method Description: + /// Tranpose the rows and columns of an array + /// + /// Numpy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.ndarray.transpose.html + /// + /// @return NdArray + /// + [[nodiscard]] self_type transpose() const + { + self_type transArray(shape_.cols, shape_.rows); + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + transArray(col, row) = operator()(row, col); + } + } + return transArray; + } + + //============================================================================ + // Method Description: + /// Fills the array with zeros + /// + /// + self_type& zeros() noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + fill(dtype{ 0 }); + return *this; + } + + private: + //====================================Attributes============================== + allocator_type allocator_{}; + Shape shape_{ 0, 0 }; + size_type size_{ 0 }; + Endian endianess_{ Endian::NATIVE }; + pointer array_{ nullptr }; + bool ownsPtr_{ false }; + + //============================================================================ + // Method Description: + /// Deletes the internal array + /// + void deleteArray() noexcept + { + if (ownsPtr_ && array_ != nullptr) + { + allocator_.deallocate(array_, size_); + } + + array_ = nullptr; + shape_.rows = shape_.cols = 0; + size_ = 0; + ownsPtr_ = false; + endianess_ = Endian::NATIVE; + } + + //============================================================================ + // Method Description: + /// Creates a new internal array + /// + void newArray() + { + if (size_ > 0) + { + array_ = allocator_.allocate(size_); + ownsPtr_ = true; + } + } + + //============================================================================ + // Method Description: + /// Creates a new internal array + /// + /// @param inShape + /// + void newArray(const Shape& inShape) + { + deleteArray(); + + shape_ = inShape; + size_ = inShape.size(); + newArray(); + } + }; + + // NOTE: this needs to be defined outside of the class to get rid of a compiler + // error in Visual Studio + template + [[nodiscard]] std::pair, NdArray> NdArray::nonzero() const + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::vector rowIndices; + std::vector colIndices; + + for (uint32 row = 0; row < shape_.rows; ++row) + { + for (uint32 col = 0; col < shape_.cols; ++col) + { + if (!utils::essentiallyEqual(operator()(row, col), dtype{ 0 })) + { + rowIndices.push_back(row); + colIndices.push_back(col); + } + } + } + + return std::make_pair(NdArray(rowIndices), NdArray(colIndices)); + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp b/runexamples/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp new file mode 100644 index 0000000..ca29b4b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/NdArray/NdArrayIterators.hpp @@ -0,0 +1,987 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Custom iterators for the NdArray class +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc +{ + //================================================================================ + // Class Description: + /// Custom const_iterator for NdArray + template + class NdArrayConstIterator + { + private: + using self_type = NdArrayConstIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using pointer = PointerType; + using reference = const value_type&; + using difference_type = DifferenceType; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + NdArrayConstIterator() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ptr: the iterator pointer + /// + explicit NdArrayConstIterator(pointer ptr) : + ptr_(ptr) + { + if (ptr == nullptr) + { + THROW_RUNTIME_ERROR("NdArray has not been initialized."); + } + } + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return *ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + ++ptr_; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + ++*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + --ptr_; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + --*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + ptr_ += offset; + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + return *this += -offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param rhs + /// @return difference_type + /// + difference_type operator-(const self_type& rhs) const noexcept + { + return ptr_ - rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return *(*this + offset); + } + + //============================================================================ + // Method Description: + /// Iterator equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const self_type& rhs) const noexcept + { + return ptr_ == rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator not-equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const self_type& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Iterator less than operator + /// + /// @param rhs + /// @return bool + /// + bool operator<(const self_type& rhs) const noexcept + { + return ptr_ < rhs.ptr_; + } + + //============================================================================ + // Method Description: + /// Iterator greater than operator + /// + /// @param rhs + /// @return bool + /// + bool operator>(const self_type& rhs) const noexcept + { + return rhs < *this; + } + + //============================================================================ + // Method Description: + /// Iterator less than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator<=(const self_type& rhs) const noexcept + { + return !(rhs < *this); + } + + //============================================================================ + // Method Description: + /// Iterator greater than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator>=(const self_type& rhs) const noexcept + { + return !(*this < rhs); + } + + private: + pointer ptr_{ nullptr }; + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayConstIterator + operator+(typename NdArrayConstIterator::difference_type offset, + NdArrayConstIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom iterator for NdArray + template + class NdArrayIterator : public NdArrayConstIterator + { + private: + using MyBase = NdArrayConstIterator; + using self_type = NdArrayIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using pointer = PointerType; + using reference = value_type&; + using difference_type = DifferenceType; + + using MyBase::MyBase; + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return const_cast(MyBase::operator*()); + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return const_cast(MyBase::operator->()); + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + MyBase::operator++(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + MyBase:: operator++(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + MyBase::operator--(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + MyBase:: operator--(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + MyBase::operator+=(offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + MyBase::operator-=(offset); + return *this; + } + + using MyBase::operator-; + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return const_cast(MyBase::operator[](offset)); + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return NdArrayIterator + /// + template + NdArrayIterator + operator+(typename NdArrayIterator::difference_type offset, + NdArrayIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom column const_iterator for NdArray + template + class NdArrayConstColumnIterator + { + private: + using self_type = NdArrayConstColumnIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using size_type = SizeType; + using pointer = PointerType; + using reference = const value_type&; + using difference_type = DifferenceType; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + NdArrayConstColumnIterator() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ptr: the iterator pointer + /// @param numRows: the number of rows in the array + /// @param numCols: the number of cols in the array + /// + NdArrayConstColumnIterator(pointer ptr, SizeType numRows, SizeType numCols) noexcept : + ptr_(ptr), + currPtr_(ptr), + numRows_(static_cast(numRows)), + numCols_(static_cast(numCols)), + size_(numRows_ * numCols_) + { + } + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return *currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + return *this += 1; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + ++*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + return *this -= 1; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + --*this; + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + currPtr_ = colIdx2Ptr(ptr2ColIdx(currPtr_) + offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + return *this += -offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param rhs + /// @return difference_type + /// + difference_type operator-(const self_type& rhs) const noexcept + { + return ptr2ColIdx(currPtr_) - ptr2ColIdx(rhs.currPtr_); + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return *(*this + offset); + } + + //============================================================================ + // Method Description: + /// Iterator equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const self_type& rhs) const noexcept + { + return currPtr_ == rhs.currPtr_; + } + + //============================================================================ + // Method Description: + /// Iterator not-equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const self_type& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Iterator less than operator + /// + /// @param rhs + /// @return bool + /// + bool operator<(const self_type& rhs) const noexcept + { + return *this - rhs < 0; + } + + //============================================================================ + // Method Description: + /// Iterator greater than operator + /// + /// @param rhs + /// @return bool + /// + bool operator>(const self_type& rhs) const noexcept + { + return *this - rhs > 0; + } + + //============================================================================ + // Method Description: + /// Iterator less than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator<=(const self_type& rhs) const noexcept + { + return !(rhs < *this); + } + + //============================================================================ + // Method Description: + /// Iterator greater than equal operator + /// + /// @param rhs + /// @return bool + /// + bool operator>=(const self_type& rhs) const noexcept + { + return !(*this < rhs); + } + + private: + pointer ptr_{}; + pointer currPtr_{}; + difference_type numRows_{ 0 }; + difference_type numCols_{ 0 }; + difference_type size_{ 0 }; + + //============================================================================ + // Method Description: + /// Converts a pointer to column order index + /// + /// @param ptr + /// @return difference_type + /// + difference_type ptr2ColIdx(pointer ptr) const noexcept + { + if (ptr == nullptr) + { + return size_; + } + + const auto rowIdx = ptr - ptr_; + if (rowIdx >= size_) + { + return size_; + } + + const auto row = rowIdx / numCols_; + const auto col = rowIdx % numCols_; + return row + col * numRows_; + } + + //============================================================================ + // Method Description: + /// Converts column order index to a pointer + /// + /// @param colIdx + /// @return pointer + /// + pointer colIdx2Ptr(difference_type colIdx) const noexcept + { + if (colIdx >= size_) + { + return nullptr; + } + + const auto row = colIdx % numRows_; + const auto col = colIdx / numRows_; + const auto rowIdx = col + row * numCols_; + return ptr_ + rowIdx; + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayConstColumnIterator operator+( + typename NdArrayConstColumnIterator::difference_type offset, + NdArrayConstColumnIterator next) noexcept + { + return next += offset; + } + + //================================================================================ + // Class Description: + /// Custom column iterator for NdArray + template + class NdArrayColumnIterator : public NdArrayConstColumnIterator + { + private: + using MyBase = NdArrayConstColumnIterator; + using self_type = NdArrayColumnIterator; + + public: + using iterator_category = std::random_access_iterator_tag; + using value_type = dtype; + using size_type = SizeType; + using pointer = PointerType; + using reference = value_type&; + using difference_type = DifferenceType; + + using MyBase::MyBase; + + //============================================================================ + // Method Description: + /// Iterator dereference + /// + /// @return reference + /// + reference operator*() const noexcept + { + return const_cast(MyBase::operator*()); + } + + //============================================================================ + // Method Description: + /// Iterator pointer operator + /// + /// @return pointer + /// + pointer operator->() const noexcept + { + return const_cast(MyBase::operator->()); + } + + //============================================================================ + // Method Description: + /// Iterator prefix incrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator++() noexcept + { + MyBase::operator++(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix incrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator++(int) noexcept + { + self_type tmp = *this; + MyBase:: operator++(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator prefix decrament operator + /// + /// @return NdArrayConstIterator& + /// + self_type& operator--() noexcept + { + MyBase::operator--(); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator postfix decrament operator + /// + /// @return NdArrayConstIterator + /// + self_type operator--(int) noexcept + { + self_type tmp = *this; + MyBase:: operator--(); + return tmp; + } + + //============================================================================ + // Method Description: + /// Iterator addition assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator+=(const difference_type offset) noexcept + { + MyBase::operator+=(offset); + return *this; + } + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator+(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp += offset; + } + + //============================================================================ + // Method Description: + /// Iterator subtraction assignement operator + /// + /// @param offset + /// @return NdArrayConstIterator& + /// + self_type& operator-=(const difference_type offset) noexcept + { + MyBase::operator-=(offset); + return *this; + } + + using MyBase::operator-; + + //============================================================================ + // Method Description: + /// Iterator difference operator + /// + /// @param offset + /// @return NdArrayConstIterator + /// + self_type operator-(const difference_type offset) const noexcept + { + self_type tmp = *this; + return tmp -= offset; + } + + //============================================================================ + // Method Description: + /// Iterator access operator + /// + /// @param offset + /// @return reference + /// + reference operator[](const difference_type offset) const noexcept + { + return const_cast(MyBase::operator[](offset)); + } + }; + + //============================================================================ + // Method Description: + /// Iterator addition operator + /// + /// @param offset + /// @param next + /// @return bool + /// + template + NdArrayColumnIterator + operator+(typename NdArrayColumnIterator::difference_type offset, + NdArrayColumnIterator next) noexcept + { + return next += offset; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp b/runexamples/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp new file mode 100644 index 0000000..66ba14d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/NdArray/NdArrayOperators.hpp @@ -0,0 +1,2022 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Operators for the NdArray class +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" +#include "NumCpp/Functions/complex.hpp" +#include "NumCpp/NdArray/NdArrayBroadcast.hpp" +#include "NumCpp/NdArray/NdArrayCore.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/essentiallyEqualComplex.hpp" + +namespace nc +{ + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator+=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::plus()); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator+=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 + val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator+=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value += rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator+=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value += rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::plus()); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 + val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Adds the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray>& lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(NdArray lhs, dtype rhs) + { + lhs += rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator+(dtype lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value + rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(const std::complex& lhs, const NdArray& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(NdArray> lhs, dtype rhs) + { + lhs += rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator+(dtype lhs, const NdArray>& rhs) + { + return rhs + lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator-=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::minus()); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator-=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 - val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator-=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value -= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator-=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value -= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::minus()); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 - val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 - val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(NdArray lhs, dtype rhs) + { + lhs -= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator-(dtype lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [lhs](dtype value) -> dtype { return lhs - value; }; + + NdArray returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value - rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(const std::complex& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](dtype value) -> std::complex { return lhs - value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(NdArray> lhs, dtype rhs) + { + lhs -= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator-(dtype lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](std::complex value) -> std::complex { return lhs - value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Negative Operator + /// + /// @return NdArray + /// + template + NdArray operator-(const NdArray& inArray) + { + const auto function = [](dtype value) -> dtype { return -value; }; + + auto returnArray = NdArray(inArray.shape()); + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator*=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::multiplies()); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator*=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 * val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator*=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value *= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator*=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value *= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::multiplies()); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 * val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Multiplies the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray>& lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(NdArray lhs, dtype rhs) + { + lhs *= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator*(dtype lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value * rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(const std::complex& lhs, const NdArray& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(NdArray> lhs, dtype rhs) + { + lhs *= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Multiplies the scalar to the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator*(dtype lhs, const NdArray>& rhs) + { + return rhs * lhs; + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator/=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::divides()); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator/=(NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const std::complex& val1, dtype val2) -> std::complex + { return val1 / val2; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator/=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value /= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray>& operator/=(NdArray>& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](std::complex& value) -> std::complex { return value /= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (1) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return broadcast::broadcaster(lhs, rhs, std::divides()); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (2) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray& lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 / val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the elements of two arrays (3) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray>& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](const auto& val1, const auto& val2) -> std::complex { return val1 / val2; }; + return broadcast::broadcaster>(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (4) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(NdArray lhs, dtype rhs) + { + lhs /= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (5) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator/(dtype lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [lhs](dtype value) -> dtype { return lhs / value; }; + + NdArray returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (6) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const NdArray& lhs, const std::complex& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [rhs](dtype value) -> std::complex { return value / rhs; }; + + NdArray> returnArray(lhs.shape()); + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (7) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(const std::complex& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](dtype value) -> std::complex { return lhs / value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (8) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(NdArray> lhs, dtype rhs) + { + lhs /= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Divides the scalar from the array (9) + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray> operator/(dtype lhs, const NdArray>& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [lhs](const std::complex& value) -> std::complex { return lhs / value; }; + + NdArray> returnArray(rhs.shape()); + + stl_algorithms::transform(rhs.cbegin(), rhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Modulus the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray& operator%=(NdArray& lhs, const NdArray& rhs) + { + if constexpr (std::is_integral_v) + { + return broadcast::broadcaster(lhs, rhs, std::modulus()); + } + else + { + const auto function = [](const dtype value1, const dtype value2) -> dtype + { return std::fmod(value1, value2); }; + return broadcast::broadcaster(lhs, rhs, function); + } + } + + //============================================================================ + // Method Description: + /// Modulus the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray& operator%=(NdArray& lhs, dtype rhs) + { + if constexpr (std::is_integral_v) + { + const auto function = [rhs](dtype& value) -> dtype { return value %= rhs; }; + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + } + else + { + const auto function = [rhs](dtype& value) -> void { value = std::fmod(value, rhs); }; + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + } + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the modulus of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template || std::is_floating_point_v, int> = 0> + NdArray operator%(const NdArray& lhs, const NdArray& rhs) + { + if constexpr (std::is_integral_v) + { + return broadcast::broadcaster(lhs, rhs, std::modulus()); + } + else + { + const auto function = [](dtype value1, dtype value2) -> dtype { return std::fmod(value1, value2); }; + return broadcast::broadcaster(lhs, rhs, function); + } + } + + //============================================================================ + // Method Description: + /// Modulus of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator%(NdArray lhs, dtype rhs) + { + lhs %= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Modulus of the scalar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template, int> = 0> + NdArray operator%(dtype lhs, const NdArray& rhs) + { + NdArray returnArray(rhs.shape()); + stl_algorithms::transform(rhs.begin(), + rhs.end(), + returnArray.begin(), + [lhs](dtype value) -> dtype { return lhs % value; }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Modulus of the scalar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template, int> = 0> + NdArray operator%(dtype lhs, const NdArray& rhs) + { + NdArray returnArray(rhs.shape()); + stl_algorithms::transform(rhs.begin(), + rhs.end(), + returnArray.begin(), + [lhs](dtype value) -> dtype { return std::fmod(lhs, value); }); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitwise or the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator|=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_or()); + } + + //============================================================================ + // Method Description: + /// Bitwise or the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator|=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value |= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_or()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(NdArray lhs, dtype rhs) + { + lhs |= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise or of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator|(dtype lhs, const NdArray& rhs) + { + return rhs | lhs; + } + + //============================================================================ + // Method Description: + /// Bitwise and the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator&=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_and()); + } + + //============================================================================ + // Method Description: + /// Bitwise and the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator&=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value &= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_and()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(NdArray lhs, dtype rhs) + { + lhs &= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise and of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&(dtype lhs, const NdArray& rhs) + { + return rhs & lhs; + } + + //============================================================================ + // Method Description: + /// Bitwise xor the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator^=(NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_xor()); + } + + //============================================================================ + // Method Description: + /// Bitwise xor the scalar to the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray& operator^=(NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [rhs](dtype& value) -> dtype { return value ^= rhs; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_INTEGER(dtype); + + return broadcast::broadcaster(lhs, rhs, std::bit_xor()); + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(NdArray lhs, dtype rhs) + { + lhs ^= rhs; + return lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise xor of the sclar and the array + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator^(dtype lhs, const NdArray& rhs) + { + return rhs ^ lhs; + } + + //============================================================================ + // Method Description: + /// Takes the bitwise not of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray operator~(const NdArray& inArray) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [](dtype value) -> dtype { return ~value; }; + + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the and of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype value1, dtype value2) -> bool + { return !utils::essentiallyEqual(value1, dtype{ 0 }) && !utils::essentiallyEqual(value2, dtype{ 0 }); }; + + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Takes the and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(const NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [rhs](dtype value) -> bool { return value && rhs; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the and of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator&&(dtype lhs, const NdArray& rhs) + { + return rhs && lhs; + } + + //============================================================================ + // Method Description: + /// Takes the or of the elements of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype value1, dtype value2) -> bool + { return !utils::essentiallyEqual(value1, dtype{ 0 }) || !utils::essentiallyEqual(value2, dtype{ 0 }); }; + + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Takes the or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(const NdArray& lhs, dtype rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [rhs](dtype value) -> bool { return value || rhs; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Takes the or of the array and the scalar + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator||(dtype lhs, const NdArray& rhs) + { + return rhs || lhs; + } + + //============================================================================ + // Method Description: + /// Takes the not of the array + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray operator!(const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [](dtype value) -> dtype { return !value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator==(const NdArray& lhs, const NdArray& rhs) + { + const auto equalTo = [](dtype lhs_, dtype rhs_) noexcept -> bool + { return utils::essentiallyEqual(lhs_, rhs_); }; + + return broadcast::broadcaster(lhs, rhs, equalTo); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator==(const NdArray& lhs, dtype inValue) + { + NdArray returnArray(lhs.shape()); + + const auto equalTo = [inValue](dtype value) noexcept -> bool + { return utils::essentiallyEqual(inValue, value); }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), equalTo); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator==(dtype inValue, const NdArray& inArray) + { + return inArray == inValue; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator!=(const NdArray& lhs, const NdArray& rhs) + { + const auto notEqualTo = [](dtype lhs_, dtype rhs_) noexcept -> bool + { return !utils::essentiallyEqual(lhs_, rhs_); }; + + return broadcast::broadcaster(lhs, rhs, notEqualTo); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator!=(const NdArray& lhs, dtype inValue) + { + NdArray returnArray(lhs.shape()); + + const auto notEqualTo = [inValue](dtype value) noexcept -> bool + { return !utils::essentiallyEqual(inValue, value); }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), notEqualTo); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// an array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator!=(dtype inValue, const NdArray& inArray) + { + return inArray != inValue; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator<(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ < rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator<(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value < inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator<(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue < value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator>(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ > rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator>(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value > inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator>(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue > value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator<=(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ <= rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator<=(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value <= inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator<=(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue <= value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// of two arrays + /// + /// @param lhs + /// @param rhs + /// @return NdArray + /// + template + NdArray operator>=(const NdArray& lhs, const NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + const auto function = [](dtype lhs_, dtype rhs_) noexcept -> bool { return lhs_ >= rhs_; }; + return broadcast::broadcaster(lhs, rhs, function); + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param lhs + /// @param inValue + /// @return NdArray + /// + template + NdArray operator>=(const NdArray& lhs, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(lhs.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return value >= inValue; }; + + stl_algorithms::transform(lhs.cbegin(), lhs.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Returns an array of booleans of element wise comparison + /// the array and a scalar + /// + /// @param inValue + /// @param inArray + /// @return NdArray + /// + template + NdArray operator>=(dtype inValue, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + NdArray returnArray(inArray.shape()); + + const auto function = [inValue](dtype value) noexcept -> bool { return inValue >= value; }; + + stl_algorithms::transform(inArray.cbegin(), inArray.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitshifts left the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray& operator<<=(NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [inNumBits](dtype& value) -> void { value <<= inNumBits; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Bitshifts left the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray operator<<(const NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(lhs); + returnArray <<= inNumBits; + return returnArray; + } + + //============================================================================ + // Method Description: + /// Bitshifts right the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray& operator>>=(NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + const auto function = [inNumBits](dtype& value) -> void { value >>= inNumBits; }; + + stl_algorithms::for_each(lhs.begin(), lhs.end(), function); + + return lhs; + } + + //============================================================================ + // Method Description: + /// Bitshifts right the elements of the array + /// + /// @param lhs + /// @param inNumBits + /// @return NdArray + /// + template + NdArray operator>>(const NdArray& lhs, uint8 inNumBits) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(lhs); + returnArray >>= inNumBits; + return returnArray; + } + + //============================================================================ + // Method Description: + /// prefix incraments the elements of an array + /// + /// @return NdArray + /// + template + NdArray& operator++(NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype& value) -> void { ++value; }; + + stl_algorithms::for_each(rhs.begin(), rhs.end(), function); + + return rhs; + } + + //============================================================================ + // Method Description: + /// postfix increments the elements of an array + /// + /// @param lhs + /// @return NdArray + /// + template + NdArray operator++(NdArray& lhs, int) + { + auto copy = NdArray(lhs); + ++lhs; + return copy; + } + + //============================================================================ + // Method Description: + /// prefix decrements the elements of an array + /// + /// @return NdArray + /// + template + NdArray& operator--(NdArray& rhs) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto function = [](dtype& value) -> void { --value; }; + + stl_algorithms::for_each(rhs.begin(), rhs.end(), function); + + return rhs; + } + + //============================================================================ + // Method Description: + /// postfix decrements the elements of an array + /// + /// @param lhs + /// @return NdArray + /// + template + NdArray operator--(NdArray& lhs, int) + { + auto copy = NdArray(lhs); + --lhs; + return copy; + } + + //============================================================================ + // Method Description: + /// io operator for the NdArray class + /// + /// @param inOStream + /// @param inArray + /// @return std::ostream + /// + template + std::ostream& operator<<(std::ostream& inOStream, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + inOStream << inArray.str(); + return inOStream; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Polynomial.hpp b/runexamples/cpp/include/NumCpp/Polynomial.hpp new file mode 100644 index 0000000..78a6ed9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial.hpp @@ -0,0 +1,37 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Polynomial/Poly1d.hpp" +#include "NumCpp/Polynomial/chebyshev_t.hpp" +#include "NumCpp/Polynomial/chebyshev_u.hpp" +#include "NumCpp/Polynomial/hermite.hpp" +#include "NumCpp/Polynomial/laguerre.hpp" +#include "NumCpp/Polynomial/legendre_p.hpp" +#include "NumCpp/Polynomial/legendre_q.hpp" +#include "NumCpp/Polynomial/spherical_harmonic.hpp" diff --git a/runexamples/cpp/include/NumCpp/Polynomial/Poly1d.hpp b/runexamples/cpp/include/NumCpp/Polynomial/Poly1d.hpp new file mode 100644 index 0000000..95326e4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/Poly1d.hpp @@ -0,0 +1,603 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Class for dealing with 1D polynomials +/// +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/diagflat.hpp" +#include "NumCpp/Linalg/inv.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" + +namespace nc::polynomial +{ + //================================================================================ + /// A one-dimensional polynomial class. + /// A convenience class, used to encapsulate "natural" + /// operations on polynomials + template + class Poly1d + { + private: + STATIC_ASSERT_ARITHMETIC(dtype); + + public: + //============================================================================ + // Method Description: + /// Default Constructor (not very usefull, but needed for other + /// containers. + /// + Poly1d() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inValues: (polynomial coefficients in ascending order of power if second input is false, + /// polynomial roots if second input is true) + /// @param isRoots + /// + Poly1d(const NdArray& inValues, bool isRoots = false) + { + if (inValues.size() > DtypeInfo::max()) + { + THROW_INVALID_ARGUMENT_ERROR("can only make a polynomial of order " + + utils::num2str(DtypeInfo::max())); + } + + if (isRoots) + { + coefficients_.push_back(1); + for (auto value : inValues) + { + NdArray coeffs = { -(value), static_cast(1) }; + *this *= Poly1d(coeffs, !isRoots); + } + } + else + { + coefficients_.resize(inValues.size()); + stl_algorithms::copy(inValues.begin(), inValues.end(), coefficients_.begin()); + } + } + + //============================================================================ + // Method Description: + /// Returns the area under the curve between the two bounds + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return double + /// + [[nodiscard]] double area(double a, double b) const + { + if (a > b) + { + std::swap(a, b); + } + + auto polyIntegral = integ(); + return polyIntegral(b) - polyIntegral(a); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the polynomial of the new type + /// + /// @return Poly1d + /// + template + Poly1d astype() const + { + auto newCoefficients = NdArray(1, static_cast(coefficients_.size())); + + const auto function = [](dtype value) -> dtypeOut { return static_cast(value); }; + + stl_algorithms::transform(coefficients_.begin(), coefficients_.end(), newCoefficients.begin(), function); + + return Poly1d(newCoefficients); + } + + //============================================================================ + // Method Description: + /// Returns the Poly1d coefficients + /// + /// @return NdArray + /// + [[nodiscard]] NdArray coefficients() const + { + auto coefficientsCopy = coefficients_; + return NdArray(coefficientsCopy); + } + + //============================================================================ + // Method Description: + /// Takes the derivative of the polynomial + /// + /// @return Poly1d + [[nodiscard]] Poly1d deriv() const + { + const auto numCoefficients = static_cast(coefficients_.size()); + if (numCoefficients == 0) + { + return {}; + } + if (numCoefficients == 1) + { + return Poly1d({ 0 }); + } + + NdArray derivativeCofficients(1, numCoefficients - 1); + + uint32 counter = 0; + for (uint32 i = 1; i < numCoefficients; ++i) + { + derivativeCofficients[counter++] = coefficients_[i] * i; + } + + return Poly1d(derivativeCofficients); + } + + //============================================================================ + // Method Description: + /// Polynomial linear least squares regression: Ax = b + /// + /// @param xValues: the x measurements [1, n] or [n, 1] array + /// @param yValues: the y measurements [n, 1] array + /// @param polyOrder: the order of the poly nomial to fit + /// @return Poly1d + static Poly1d fit(const NdArray& xValues, const NdArray& yValues, uint8 polyOrder) + { + const auto numMeasurements = xValues.size(); + + if (yValues.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size."); + } + + if (!xValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array."); + } + + if (!yValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array."); + } + + NdArray a(numMeasurements, polyOrder + 1); + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto xDouble = static_cast(xValues[measIdx]); + for (uint8 order = 0; order < a.numCols(); ++order) + { + a(measIdx, order) = utils::power(xDouble, order); + } + } + + NdArray aInv; + if (a.issquare()) + { + aInv = linalg::inv(a); + } + else + { + // psuedo-inverse + auto aT = a.transpose(); + auto aTaInv = linalg::inv(aT.dot(a)); + aInv = aTaInv.dot(aT); + } + + auto x = aInv.dot(yValues.template astype()); + return Poly1d(x); + } + + //============================================================================ + // Method Description: + /// Polynomial linear least squares regression: Ax = b + /// + /// @param xValues: the x measurements [1, n] or [n, 1] array + /// @param yValues: the y measurements [n, 1] array + /// @param weights: the measurement weights [1, n] or [n, 1] array + /// @param polyOrder: the order of the poly nomial to fit + /// @return Poly1d + static Poly1d fit(const NdArray& xValues, + const NdArray& yValues, + const NdArray& weights, + uint8 polyOrder) + { + const auto numMeasurements = xValues.size(); + + if (yValues.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and y arrays must be of equal size."); + } + + if (weights.size() != numMeasurements) + { + THROW_INVALID_ARGUMENT_ERROR("Input x and weights arrays must be of equal size."); + } + + if (!xValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input x must be a flattened [1, n] or [n, 1] array."); + } + + if (!yValues.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input y must be a flattened [n, 1] array."); + } + + if (!weights.isflat()) + { + THROW_INVALID_ARGUMENT_ERROR("Input weights must be a flattened [1, n] or [n, 1] array."); + } + + NdArray a(numMeasurements, polyOrder + 1); + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto xDouble = static_cast(xValues[measIdx]); + for (uint8 order = 0; order < a.numCols(); ++order) + { + a(measIdx, order) = utils::power(xDouble, order); + } + } + + NdArray aWeighted(a.shape()); + NdArray yWeighted(yValues.shape()); + + for (uint32 measIdx = 0; measIdx < numMeasurements; ++measIdx) + { + const auto weight = static_cast(weights[measIdx]); + + yWeighted[measIdx] = yValues[measIdx] * weight; + for (uint8 order = 0; order < a.numCols(); ++order) + { + aWeighted(measIdx, order) = a(measIdx, order) * weight; + } + } + + NdArray aInv; + if (aWeighted.issquare()) + { + aInv = linalg::inv(aWeighted); + } + else + { + // psuedo-inverse + auto aT = a.transpose(); + auto aTaInv = linalg::inv(aT.dot(aWeighted)); + aInv = aTaInv.dot(aT); + } + + auto x = aInv.dot(yWeighted); + return Poly1d(x); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Calculates the integral of the polynomial + /// + /// @return Poly1d + [[nodiscard]] Poly1d integ() const + { + const auto numCoefficients = static_cast(coefficients_.size()); + if (numCoefficients == 0) + { + return {}; + } + + NdArray integralCofficients(1, numCoefficients + 1); + integralCofficients[0] = 0.; + + for (uint32 i = 0; i < numCoefficients; ++i) + { + integralCofficients[i + 1] = static_cast(coefficients_[i]) / static_cast(i + 1); + } + + return Poly1d(integralCofficients); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the order of the Poly1d + /// + /// @return NdArray + /// + [[nodiscard]] uint32 order() const noexcept + { + return static_cast(coefficients_.size() - 1); + } + + //============================================================================ + // Method Description: + /// Prints the string representation of the Poly1d object + /// to the console + /// + void print() const + { + std::cout << *this << std::endl; + } + + //============================================================================ + // Method Description: + /// Converts the polynomial to a string representation + /// + /// @return Poly1d + /// + [[nodiscard]] std::string str() const + { + const auto numCoeffients = static_cast(coefficients_.size()); + + std::string repr = "Poly1d<"; + uint32 power = 0; + for (auto& coefficient : coefficients_) + { + if (utils::essentiallyEqual(coefficient, static_cast(0))) + { + ++power; + continue; + } + + repr += utils::num2str(coefficient); + + if (power > 1) + { + repr += "x^" + utils::num2str(power); + } + else if (power == 1) + { + repr += "x"; + } + + ++power; + + if (power < numCoeffients) + { + repr += " + "; + } + } + + return repr + ">"; + } + + //============================================================================ + // Method Description: + /// Evaluates the Poly1D object for the input value + /// + /// @param inValue + /// @return Poly1d + /// + dtype operator()(dtype inValue) const noexcept + { + uint8 power = 0; + return std::accumulate(coefficients_.begin(), + coefficients_.end(), + dtype{ 0 }, + [&power, inValue](dtype polyValue, const auto& coefficient) noexcept -> dtype + { return polyValue + coefficient * utils::power(inValue, power++); }); + } + + //============================================================================ + // Method Description: + /// Adds the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator+(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) += inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Adds the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator+=(const Poly1d& inOtherPoly) + { + if (this->coefficients_.size() < inOtherPoly.coefficients_.size()) + { + for (size_t i = 0; i < coefficients_.size(); ++i) + { + coefficients_[i] += inOtherPoly.coefficients_[i]; + } + for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_.push_back(inOtherPoly.coefficients_[i]); + } + } + else + { + for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_[i] += inOtherPoly.coefficients_[i]; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator-(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) -= inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Subtracts the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator-=(const Poly1d& inOtherPoly) + { + if (this->coefficients_.size() < inOtherPoly.coefficients_.size()) + { + for (size_t i = 0; i < coefficients_.size(); ++i) + { + coefficients_[i] -= inOtherPoly.coefficients_[i]; + } + for (size_t i = coefficients_.size(); i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_.push_back(-inOtherPoly.coefficients_[i]); + } + } + else + { + for (size_t i = 0; i < inOtherPoly.coefficients_.size(); ++i) + { + coefficients_[i] -= inOtherPoly.coefficients_[i]; + } + } + + return *this; + } + + //============================================================================ + // Method Description: + /// Multiplies the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d operator*(const Poly1d& inOtherPoly) const + { + return Poly1d(*this) *= inOtherPoly; + } + + //============================================================================ + // Method Description: + /// Multiplies the two Poly1d objects + /// + /// @param inOtherPoly + /// @return Poly1d + /// + Poly1d& operator*=(const Poly1d& inOtherPoly) + { + const uint32 finalCoefficientsSize = order() + inOtherPoly.order() + 1; + std::vector coeffsA(finalCoefficientsSize, 0); + std::vector coeffsB(finalCoefficientsSize, 0); + stl_algorithms::copy(coefficients_.begin(), coefficients_.end(), coeffsA.begin()); + stl_algorithms::copy(inOtherPoly.coefficients_.cbegin(), inOtherPoly.coefficients_.cend(), coeffsB.begin()); + + // now multiply out the coefficients + std::vector finalCoefficients(finalCoefficientsSize, 0); + for (uint32 i = 0; i < finalCoefficientsSize; ++i) + { + for (uint32 k = 0; k <= i; ++k) + { + finalCoefficients[i] += coeffsA[k] * coeffsB[i - k]; + } + } + + this->coefficients_ = finalCoefficients; + return *this; + } + + //============================================================================ + // Method Description: + /// Raise the Poly1d to an integer power + /// + /// @param inPower + /// @return Poly1d + /// + Poly1d operator^(uint32 inPower) const + { + return Poly1d(*this) ^= inPower; + } + + //============================================================================ + // Method Description: + /// Raise the Poly1d to an integer power + /// + /// @param inPower + /// @return Poly1d + /// + Poly1d& operator^=(uint32 inPower) + { + if (inPower == 0) + { + coefficients_.clear(); + coefficients_.push_back(1); + return *this; + } + if (inPower == 1) + { + return *this; + } + + auto thisPoly(*this); + for (uint32 power = 1; power < inPower; ++power) + { + *this *= thisPoly; + } + + return *this; + } + + //============================================================================ + // Method Description: + /// io operator for the Poly1d class + /// + /// @param inOStream + /// @param inPoly + /// @return std::ostream + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Poly1d& inPoly) + { + inOStream << inPoly.str() << std::endl; + return inOStream; + } + + private: + std::vector coefficients_{}; + }; +} // namespace nc::polynomial diff --git a/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp b/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp new file mode 100644 index 0000000..d79f6ce --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_t.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/chebyshev.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param x: the input value + /// @return double + /// + template + double chebyshev_t(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::chebyshev_t(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray chebyshev_t(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return chebyshev_t(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp b/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp new file mode 100644 index 0000000..db34aa0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/chebyshev_u.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/chebyshev.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param x: the input value + /// @return double + /// + template + double chebyshev_u(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::chebyshev_u(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Chebyshev Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the chebyshev polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray chebyshev_u(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return chebyshev_u(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Polynomial/hermite.hpp b/runexamples/cpp/include/NumCpp/Polynomial/hermite.hpp new file mode 100644 index 0000000..f46423d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/hermite.hpp @@ -0,0 +1,89 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/hermite.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Hermite Polynomial + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the hermite polynomial + /// @param x: the input value + /// @return double + /// + template + double hermite(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::hermite(n, static_cast(x)); +#else + return boost::math::hermite(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Hermite Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the hermite polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray hermite(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return hermite(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Polynomial/laguerre.hpp b/runexamples/cpp/include/NumCpp/Polynomial/laguerre.hpp new file mode 100644 index 0000000..cb03340 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/laguerre.hpp @@ -0,0 +1,135 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/laguerre.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param x: the input value + /// @return double + /// + template + double laguerre(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::laguerre(n, static_cast(x)); +#else + return boost::math::laguerre(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Associated Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param m: the degree of the legendre polynomial + /// @param x: the input value + /// @return double + /// + template + double laguerre(uint32 n, uint32 m, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::assoc_laguerre(m, n, static_cast(x)); +#else + return boost::math::laguerre(m, n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray laguerre(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return laguerre(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Associated Laguerre Polynomial. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the order of the leguerre polynomial + /// @param m: the degree of the legendre polynomial + /// @param inArrayX: the input value + /// @return NdArray + /// + template + NdArray laguerre(uint32 n, uint32 m, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n, m](dtype x) -> double { return laguerre(n, m, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Polynomial/legendre_p.hpp b/runexamples/cpp/include/NumCpp/Polynomial/legendre_p.hpp new file mode 100644 index 0000000..ab609a6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/legendre_p.hpp @@ -0,0 +1,176 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/legendre.hpp" +#endif + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the degree of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_p(uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + +#ifdef __cpp_lib_math_special_functions + return std::legendre(n, static_cast(x)); +#else + return boost::math::legendre_p(n, static_cast(x)); +#endif + } + + //============================================================================ + // Method Description: + /// Associated Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param m: the order of the legendre polynomial + /// @param n: the degree of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_p(uint32 m, uint32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + +#ifdef __cpp_lib_math_special_functions + + auto value = std::assoc_legendre(n, m, static_cast(x)); + +#ifdef __GNUC__ +#if __GNUC__ != 7 && __GNUC__ != 8 + + // gcc std::assoc_legendre is not standard compliant + value *= n % 2 == 0 ? 1 : -1; + +#endif // #if __GNUC__ != 7 && __GNUC__ != 8 +#endif // #ifdef __GNUC__ + +#ifdef __clang__ +#if __clang_major__ != 7 && __clang_major__ != 8 + + // clang uses gcc headers where std::assoc_legendre is not standard compliant + value *= n % 2 == 0 ? 1 : -1; + +#endif // #if __clang_major__ != 6 && __clang_major__ != 7 && __clang_major__ != 8 +#endif // #ifdef __clang__ + +#ifdef _MSC_VER + + value *= n % 2 == 0 ? 1 : -1; + +#endif // #ifdef _MSC_VER + + return value; + +#else // #ifdef __cpp_lib_math_special_functions + + return boost::math::legendre_p(n, m, static_cast(x)); + +#endif // #ifdef __cpp_lib_math_special_functions + } + + //============================================================================ + // Method Description: + /// Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param n: the degree of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_p(uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return legendre_p(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } + + //============================================================================ + // Method Description: + /// Associated Legendre Polynomial of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param m: the order of the legendre polynomial + /// @param n: the degree of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_p(uint32 m, uint32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [m, n](dtype x) -> double { return legendre_p(m, n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Polynomial/legendre_q.hpp b/runexamples/cpp/include/NumCpp/Polynomial/legendre_q.hpp new file mode 100644 index 0000000..d62f5ed --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/legendre_q.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/legendre.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Legendre Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the legendre polynomial + /// @param x: the input value. Requires -1 <= x <= 1 + /// @return double + /// + template + double legendre_q(int32 n, dtype x) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (x < -1. || x > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input x must be of the range [-1, 1]."); + } + + return boost::math::legendre_q(n, static_cast(x)); + } + + //============================================================================ + // Method Description: + /// Legendre Polynomial of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the order of the legendre polynomial + /// @param inArrayX: the input value. Requires -1 <= x <= 1 + /// @return NdArray + /// + template + NdArray legendre_q(int32 n, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + const auto function = [n](dtype x) -> double { return legendre_q(n, x); }; + + stl_algorithms::transform(inArrayX.cbegin(), inArrayX.cend(), returnArray.begin(), function); + + return returnArray; + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp b/runexamples/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp new file mode 100644 index 0000000..25f0b3f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Polynomial/spherical_harmonic.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/spherical_harmonic.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::polynomial +{ + //============================================================================ + // Method Description: + /// Returns the value of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + std::complex spherical_harmonic(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic(m, n, static_cast(phi), static_cast(theta)); + } + + //============================================================================ + // Method Description: + /// Returns the real part of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + double spherical_harmonic_r(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic_r(m, n, static_cast(phi), static_cast(theta)); + } + + //============================================================================ + // Method Description: + /// Returns the imaginary part of the Spherical Harmonic Ynm(theta, phi). + /// The spherical harmonics Ynm(theta, phi) are the angular portion of the + /// solution to Laplace's equation in spherical coordinates where azimuthal + /// symmetry is not present. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: order of the harmonic + /// @param m: degree of the harmonic + /// @param theta: Azimuthal (longitudinal) coordinate; must be in [0, 2*pi]. + /// @param phi: Polar (colatitudinal) coordinate; must be in [0, pi]. + /// @return double + /// + template + double spherical_harmonic_i(uint32 n, int32 m, dtype1 theta, dtype2 phi) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::spherical_harmonic_i(m, n, static_cast(phi), static_cast(theta)); + } +} // namespace nc::polynomial + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/PythonInterface.hpp b/runexamples/cpp/include/NumCpp/PythonInterface.hpp new file mode 100644 index 0000000..61463b2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/PythonInterface.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python +/// +#pragma once + +#include "NumCpp/PythonInterface/BoostInterface.hpp" +#include "NumCpp/PythonInterface/PybindInterface.hpp" diff --git a/runexamples/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp b/runexamples/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp new file mode 100644 index 0000000..6e32273 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/PythonInterface/BoostInterface.hpp @@ -0,0 +1,169 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python with boost interface +/// +#pragma once + +#if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) + +#include +#include + +#include "boost/python.hpp" +#include "boost/python/numpy.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp" + +namespace nc +{ + namespace boostPythonInterface + { + //============================================================================ + /// Converts from a boost ndarray to a NumCpp NdArray + /// + /// @param inArray + /// + /// @return NdArray + /// + template + inline NdArray boost2Nc(const boost::python::numpy::ndarray& inArray) + { + BoostNdarrayHelper helper(inArray); + if (helper.numDimensions() > 2) + { + THROW_RUNTIME_ERROR("Can only convert 1 and 2 dimensional arrays."); + } + + Shape arrayShape; + if (helper.numDimensions() == 1) + { + arrayShape.rows = 1; + arrayShape.cols = static_cast(helper.shape().front()); + + NdArray returnArray(arrayShape); + for (uint32 i = 0; i < arrayShape.size(); ++i) + { + returnArray[i] = helper(i); + } + + return returnArray; + } + + arrayShape.rows = static_cast(helper.shape().front()); + arrayShape.cols = static_cast(helper.shape()[1]); + + NdArray returnArray(arrayShape); + for (uint32 row = 0; row < arrayShape.rows; ++row) + { + for (uint32 col = 0; col < arrayShape.cols; ++col) + { + returnArray(row, col) = helper(row, col); + } + } + + return returnArray; + } + + //============================================================================ + /// Converts from a NumCpp NdArray to a boost ndarray + /// + /// @param inArray + /// + /// @return ndarray + /// + template + inline boost::python::numpy::ndarray nc2Boost(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + boost::python::tuple shape = boost::python::make_tuple(inShape.rows, inShape.cols); + BoostNdarrayHelper newNdArrayHelper(shape); + + for (uint32 row = 0; row < inShape.rows; ++row) + { + for (uint32 col = 0; col < inShape.cols; ++col) + { + newNdArrayHelper(row, col) = inArray(row, col); + } + } + return newNdArrayHelper.getArray(); + } + + //============================================================================ + /// converts a boost python list to a std::vector + /// + /// @param inList + /// + /// @return std::vector + /// + template + inline std::vector list2vector(const boost::python::list& inList) + { + return std::vector(boost::python::stl_input_iterator(inList), boost::python::stl_input_iterator()); + } + + //============================================================================ + /// converts a std::vector to a boost python list + /// + /// @param inVector + /// + /// @return boost::python::list + /// + template + inline boost::python::list vector2list(std::vector& inVector) + { + boost::python::list outList; + for (auto& value : inVector) + { + outList.append(value); + } + + return outList; + } + + //============================================================================ + /// converts a std::map in to a boost python dictionary + /// + /// @param inMap + /// + /// @return boost::python::dict + /// + template + inline boost::python::dict map2dict(const std::map& inMap) + { + boost::python::dict dictionary; + for (auto& keyValue : inMap) + { + dictionary[keyValue.first] = keyValue.second; + } + return dictionary; + } + } // namespace boostPythonInterface +} // namespace nc + +#endif // #if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp b/runexamples/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp new file mode 100644 index 0000000..a82e1ce --- /dev/null +++ b/runexamples/cpp/include/NumCpp/PythonInterface/BoostNumpyNdarrayHelper.hpp @@ -0,0 +1,339 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A wrapper class for interacting with the boost numpy arrays +/// +#pragma once + +#if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) + +#include +#include +#include +#include +#include + +#include "boost/python.hpp" +#include "boost/python/numpy.hpp" + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Utils/num2str.hpp" + +namespace nc +{ + namespace boostPythonInterface + { + //================================================================================ + /// Helper class for ndarray + template + class BoostNdarrayHelper + { + public: + //================================================================================ + /// C or Fortran ordering from python + enum class Order + { + F, + C + }; + + //============================================================================ + /// Constructor + /// + /// @param inArray: ndarray + /// + explicit BoostNdarrayHelper(const boost::python::numpy::ndarray& inArray) : + theArray_(inArray.astype(boost::python::numpy::dtype::get_builtin())), + numDimensions_(static_cast(inArray.get_nd())), + shape_(numDimensions_), + strides_(numDimensions_), + order_(Order::C) + + { + Py_intptr_t const* shapePtr = inArray.get_shape(); + for (uint8 i = 0; i < numDimensions_; ++i) + { + strides_[i] = static_cast(theArray_.strides(i)); + shape_[i] = shapePtr[i]; + } + + if (numDimensions_ > 1 && inArray.strides(0) < inArray.strides(1)) + { + order_ = Order::F; + } + } + + //============================================================================ + /// Constructor + /// + /// @param inShape + /// + explicit BoostNdarrayHelper(boost::python::tuple inShape) : + theArray_(boost::python::numpy::zeros(inShape, boost::python::numpy::dtype::get_builtin())), + numDimensions_(static_cast(theArray_.get_nd())), + shape_(numDimensions_), + strides_(numDimensions_), + order_(Order::C) + { + Py_intptr_t const* shapePtr = theArray_.get_shape(); + for (uint8 i = 0; i < numDimensions_; ++i) + { + strides_[i] = static_cast(theArray_.strides(i)); + shape_[i] = shapePtr[i]; + } + + if (numDimensions_ > 1 && theArray_.strides(0) < theArray_.strides(1)) + { + order_ = Order::F; + } + } + + //============================================================================ + /// Returns the internaly held ndarray + /// + /// @return reference to the held ndarray + /// + const boost::python::numpy::ndarray& getArray() noexcept + { + return theArray_; + } + + //============================================================================ + /// Returns the internaly held ndarray as a numpy matrix + /// + /// @return matrix + /// + boost::python::numpy::matrix getArrayAsMatrix() + { + return boost::python::numpy::matrix(theArray_); + } + + //============================================================================ + /// Returns the number of dimensions of the array + /// + /// @return num dimensions + /// + uint8 numDimensions() noexcept + { + return numDimensions_; + } + + //============================================================================ + /// Returns the shape of the array + /// + /// @return vector + /// + const std::vector& shape() noexcept + { + return shape_; + } + + //============================================================================ + /// Returns the size of the array + /// + /// @return size + /// + uint32 size() + { + uint32 theSize = 1; + for (auto dimSize : shape_) + { + theSize *= static_cast(dimSize); + } + return theSize; + } + + //============================================================================ + /// Returns the strides of the array + /// + /// @return vector + /// + const std::vector& strides() + { + return strides_; + } + + //============================================================================ + /// Returns the memory order of the array (C or Fortran) + /// + /// @return Order + /// + Order order() + { + return order_; + } + + //============================================================================ + /// Returns if the shapes of the two array helpers are equal + /// + /// @param otherNdarrayHelper + /// + /// @return boolean + /// + bool shapeEqual(BoostNdarrayHelper& otherNdarrayHelper) + { + if (shape_.size() != otherNdarrayHelper.shape_.size()) + { + return false; + } + + return stl_algorithms::equal(shape_.begin(), shape_.end(), otherNdarrayHelper.shape_.begin()); + } + + //============================================================================ + /// 1D access operator + /// + /// @param index + /// + /// @return dtype + /// + dtype& operator()(uint32 index) + { + checkIndices1D(index); + + return *reinterpret_cast(theArray_.get_data() + strides_.front() * index); + } + + //============================================================================ + /// 2D access operator + /// + /// @param index1 + /// @param index2 + /// + /// @return dtype + /// + dtype& operator()(uint32 index1, uint32 index2) + { + checkIndices2D(index1, index2); + + return *reinterpret_cast(theArray_.get_data() + strides_.front() * index1 + + strides_[1] * index2); + } + + //============================================================================ + /// Prints a 1D array + /// + void printArray1D() + { + printf("array = \n"); + if (numDimensions_ != 1) + { + std::cout << "printArray1D can only be used on a 1D array." << std::endl; + return; + } + + for (int32 i = 0; i < shape_.front(); ++i) + { + printf("\t%f\n", operator()(i)); + } + } + + //============================================================================ + /// Prints a 2D array + /// + void printArray2D() + { + printf("array = \n"); + if (numDimensions_ != 2) + { + std::cout << "printArray2D can only be used on a 2D array." << std::endl; + return; + } + + for (int32 index1 = 0; index1 < shape_.front(); ++index1) + { + for (int32 index2 = 0; index2 < shape_.back(); ++index2) + { + printf("\t%f", operator()(index1, index2)); + } + printf('\n'); + } + } + + private: + //====================================Attributes============================== + boost::python::numpy::ndarray theArray_; + uint8 numDimensions_; + std::vector shape_; + std::vector strides_; + Order order_; + + //============================================================================ + /// Generic check of input indices + /// + /// @param indices + /// + void checkIndicesGeneric(boost::python::tuple indices) + { + if (boost::python::len(indices) != numDimensions_) + { + std::string errStr = + "Error: BoostNdarrayHelper::checkIndicesGeneric: Array has " + utils::num2str(numDimensions_); + errStr += " dimensions, you asked for " + + utils::num2str(static_cast(boost::python::len(indices))) + "!"; + PyErr_SetString(PyExc_RuntimeError, errStr.c_str()); + } + + for (int i = 0; i < numDimensions_; ++i) + { + int index = boost::python::extract(indices[i]); + if (index > shape_[i]) + { + std::string errStr = + "Error: BoostNdarrayHelper::checkIndicesGeneric: Input index [" + utils::num2str(index); + errStr += "] is larger than the size of the array [" + utils::num2str(shape_[i]) + "]."; + PyErr_SetString(PyExc_RuntimeError, errStr.c_str()); + } + } + } + + //============================================================================ + /// Checks 1D input indices + /// + /// @param index + /// + void checkIndices1D(uint32 index) + { + boost::python::tuple indices = boost::python::make_tuple(index); + checkIndicesGeneric(indices); + } + + //============================================================================ + /// Checks 2D input indices + /// + /// @param index1 + /// @param index2 + /// + void checkIndices2D(uint32 index1, uint32 index2) + { + boost::python::tuple indices = boost::python::make_tuple(index1, index2); + checkIndicesGeneric(indices); + } + }; + } // namespace boostPythonInterface +} // namespace nc + +#endif // #if defined(NUMCPP_INCLUDE_BOOST_PYTHON_INTERFACE) && !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp b/runexamples/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp new file mode 100644 index 0000000..aac3a89 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/PythonInterface/PybindInterface.hpp @@ -0,0 +1,201 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// A module for interacting with python with pybind11 interface +/// +#pragma once + +#ifdef NUMCPP_INCLUDE_PYBIND_PYTHON_INTERFACE + +#include "pybind11/numpy.h" +#include "pybind11/pybind11.h" + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::pybindInterface +{ + /// Enum for the pybind array return policy + enum class ReturnPolicy + { + COPY, + REFERENCE, + TAKE_OWNERSHIP + }; + + static const std::map returnPolicyStringMap = { { ReturnPolicy::COPY, "COPY" }, + { ReturnPolicy::REFERENCE, "REFERENCE" }, + { ReturnPolicy::TAKE_OWNERSHIP, + "TAKE_OWNERSHIP" } }; + + template + using pbArray = pybind11::array_t; + using pbArrayGeneric = pybind11::array; + + //============================================================================ + /// converts a numpy array to a numcpp NdArray using pybind bindings + /// Python will still own the underlying data. + /// + /// @param numpyArray + /// + /// @return NdArray + /// + template + NdArray pybind2nc(pbArray& numpyArray) + { + const auto dataPtr = numpyArray.mutable_data(); + switch (numpyArray.ndim()) + { + case 0: + { + return NdArray(dataPtr, 0, 0, false); + } + case 1: + { + const auto size = static_cast(numpyArray.size()); + return NdArray(dataPtr, 1, size, false); + } + case 2: + { + const auto numRows = static_cast(numpyArray.shape(0)); + const auto numCols = static_cast(numpyArray.shape(1)); + return NdArray(dataPtr, numRows, numCols, false); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input array must be no more than 2 dimensional."); + return {}; + } + } + } + + //============================================================================ + /// converts a numpy array to a numcpp NdArray using pybind bindings + /// Python will still own the underlying data. + /// + /// @param numpyArray + /// + /// @return NdArray + /// + template + NdArray pybind2nc_copy(const pbArray& numpyArray) + { + const auto dataPtr = numpyArray.data(); + switch (numpyArray.ndim()) + { + case 0: + { + return NdArray(dataPtr, 0, 0); + } + case 1: + { + const auto size = static_cast(numpyArray.size()); + return NdArray(dataPtr, 1, size); + } + case 2: + { + const auto numRows = static_cast(numpyArray.shape(0)); + const auto numCols = static_cast(numpyArray.shape(1)); + return NdArray(dataPtr, numRows, numCols); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("input array must be no more than 2 dimensional."); + return {}; + } + } + } + + //============================================================================ + /// converts a numcpp NdArray to numpy array using pybind bindings + /// + /// @param inArray: the input array + /// + /// @return pybind11::array_t + /// + template + pbArrayGeneric nc2pybind(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + const std::vector shape{ static_cast(inShape.rows), + static_cast(inShape.cols) }; + const std::vector strides{ static_cast(inShape.cols * sizeof(dtype)), + static_cast(sizeof(dtype)) }; + return pbArrayGeneric(shape, strides, inArray.data()); + } + + //============================================================================ + /// converts a numcpp NdArray to numpy array using pybind bindings + /// + /// @param inArray: the input array + /// @param returnPolicy: the return policy + /// + /// @return pybind11::array_t + /// + template + pbArrayGeneric nc2pybind(NdArray& inArray, ReturnPolicy returnPolicy) + { + const Shape inShape = inArray.shape(); + const std::vector shape{ static_cast(inShape.rows), + static_cast(inShape.cols) }; + const std::vector strides{ static_cast(inShape.cols * sizeof(dtype)), + static_cast(sizeof(dtype)) }; + + switch (returnPolicy) + { + case ReturnPolicy::COPY: + { + return nc2pybind(inArray); + } + case ReturnPolicy::REFERENCE: + { + typename pybind11::capsule reference(inArray.data(), [](void* /*ptr*/) {}); + return pbArrayGeneric(shape, strides, inArray.data(), reference); + } + case ReturnPolicy::TAKE_OWNERSHIP: + { + typename pybind11::capsule garbageCollect(inArray.dataRelease(), + [](void* ptr) + { + auto* dataPtr = reinterpret_cast(ptr); + delete[] dataPtr; + }); + return pbArrayGeneric(shape, strides, inArray.data(), garbageCollect); + } + default: + { + std::stringstream sstream; + sstream << "ReturnPolicy " << returnPolicyStringMap.at(returnPolicy) << " has not been implemented yet" + << std::endl; + THROW_INVALID_ARGUMENT_ERROR(sstream.str()); + } + } + } +} // namespace nc::pybindInterface +#endif diff --git a/runexamples/cpp/include/NumCpp/Random.hpp b/runexamples/cpp/include/NumCpp/Random.hpp new file mode 100644 index 0000000..4e5be43 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random.hpp @@ -0,0 +1,61 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Random number distributions +/// +#pragma once + +#include "NumCpp/Random/RNG.hpp" +#include "NumCpp/Random/bernoulli.hpp" +#include "NumCpp/Random/beta.hpp" +#include "NumCpp/Random/binomial.hpp" +#include "NumCpp/Random/cauchy.hpp" +#include "NumCpp/Random/chiSquare.hpp" +#include "NumCpp/Random/choice.hpp" +#include "NumCpp/Random/discrete.hpp" +#include "NumCpp/Random/exponential.hpp" +#include "NumCpp/Random/extremeValue.hpp" +#include "NumCpp/Random/f.hpp" +#include "NumCpp/Random/gamma.hpp" +#include "NumCpp/Random/generator.hpp" +#include "NumCpp/Random/geometric.hpp" +#include "NumCpp/Random/laplace.hpp" +#include "NumCpp/Random/lognormal.hpp" +#include "NumCpp/Random/negativeBinomial.hpp" +#include "NumCpp/Random/nonCentralChiSquared.hpp" +#include "NumCpp/Random/normal.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/poisson.hpp" +#include "NumCpp/Random/rand.hpp" +#include "NumCpp/Random/randFloat.hpp" +#include "NumCpp/Random/randInt.hpp" +#include "NumCpp/Random/randN.hpp" +#include "NumCpp/Random/shuffle.hpp" +#include "NumCpp/Random/standardNormal.hpp" +#include "NumCpp/Random/studentT.hpp" +#include "NumCpp/Random/triangle.hpp" +#include "NumCpp/Random/uniform.hpp" +#include "NumCpp/Random/uniformOnSphere.hpp" +#include "NumCpp/Random/weibull.hpp" diff --git a/runexamples/cpp/include/NumCpp/Random/RNG.hpp b/runexamples/cpp/include/NumCpp/Random/RNG.hpp new file mode 100644 index 0000000..e25d7dd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/RNG.hpp @@ -0,0 +1,1116 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Random Number Generater Class with non-global state +/// +#pragma once + +#include + +#include "NumCpp/Random/bernoulli.hpp" +#include "NumCpp/Random/beta.hpp" +#include "NumCpp/Random/binomial.hpp" +#include "NumCpp/Random/cauchy.hpp" +#include "NumCpp/Random/chiSquare.hpp" +#include "NumCpp/Random/choice.hpp" +#include "NumCpp/Random/discrete.hpp" +#include "NumCpp/Random/exponential.hpp" +#include "NumCpp/Random/extremeValue.hpp" +#include "NumCpp/Random/f.hpp" +#include "NumCpp/Random/gamma.hpp" +#include "NumCpp/Random/geometric.hpp" +#include "NumCpp/Random/laplace.hpp" +#include "NumCpp/Random/lognormal.hpp" +#include "NumCpp/Random/negativeBinomial.hpp" +#include "NumCpp/Random/nonCentralChiSquared.hpp" +#include "NumCpp/Random/normal.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/poisson.hpp" +#include "NumCpp/Random/rand.hpp" +#include "NumCpp/Random/randFloat.hpp" +#include "NumCpp/Random/randInt.hpp" +#include "NumCpp/Random/randN.hpp" +#include "NumCpp/Random/shuffle.hpp" +#include "NumCpp/Random/standardNormal.hpp" +#include "NumCpp/Random/studentT.hpp" +#include "NumCpp/Random/triangle.hpp" +#include "NumCpp/Random/uniform.hpp" +#include "NumCpp/Random/uniformOnSphere.hpp" +#include "NumCpp/Random/weibull.hpp" + +namespace nc::random +{ + //============================================================================ + // Class Description: + /// Random Number Generater Class with non-global state + /// + template + class RNG + { + public: + //============================================================================ + // Method Description: + /// Defualt Constructor + /// + RNG() = default; + + //============================================================================ + // Method Description: + /// Seed Constructor + /// + /// @param seed: the seed value + /// + explicit RNG(int seed) : + generator_(seed){}; + + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + bool bernoulli(double inP = 0.5) + { + return detail::bernoulli(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + NdArray bernoulli(const Shape& inShape, double inP = 0.5) + { + return detail::bernoulli(generator_, inShape, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inAlpha, inBeta); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(const Shape& inShape, dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inShape, inAlpha, inBeta); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inShape, inN, inP); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(dtype inDof) + { + return detail::chiSquare(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(const Shape& inShape, dtype inDof) + { + return detail::chiSquare(generator_, inShape, inDof); + } + + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param inArray + /// @return NdArray + /// + template + dtype choice(const NdArray& inArray) + { + return detail::choice(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray choice(const NdArray& inArray, uint32 inNum, bool replace = true) + { + return detail::choice(generator_, inArray, inNum, replace); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(const NdArray& inWeights) + { + return detail::discrete(generator_, inWeights); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(const Shape& inShape, const NdArray& inWeights) + { + return detail::discrete(generator_, inShape, inWeights); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(dtype inScaleValue = 1) + { + return detail::exponential(generator_, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(const Shape& inShape, dtype inScaleValue = 1) + { + return detail::exponential(generator_, inShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inShape, inA, inB); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(const Shape& inShape, dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inShape, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inShape, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(double inP = 0.5) + { + return detail::geometric(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(const Shape& inShape, double inP = 0.5) + { + return detail::geometric(generator_, inShape, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inLoc, inScale); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inShape, inLoc, inScale); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inShape, inN, inP); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inK, inLambda); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray nonCentralChiSquared(const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inShape, inK, inLambda); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inShape, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(dtype inValue) + { + return detail::permutation(generator_, inValue); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(const NdArray& inArray) + { + return detail::permutation(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(double inMean = 1) + { + return detail::poisson(generator_, inMean); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(const Shape& inShape, double inMean = 1) + { + return detail::poisson(generator_, inShape, inMean); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @return NdArray + /// + template + dtype rand() + { + return detail::rand(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(const Shape& inShape) + { + return detail::rand(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inShape, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inShape, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @return dtype + /// + template + dtype randN() + { + return detail::randN(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(const Shape& inShape) + { + return detail::randN(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Seed Constructor + /// + /// @param value: the seed value + /// + void seed(int value) noexcept + { + generator_.seed(value); + } + + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param inArray + /// + template + void shuffle(NdArray& inArray) + { + return detail::shuffle(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @return NdArray + /// + template + dtype standardNormal() + { + return detail::standardNormal(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(const Shape& inShape) + { + return detail::standardNormal(generator_, inShape); + } + + //============================================================================ + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(dtype inDof) + { + return detail::studentT(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(const Shape& inShape, dtype inDof) + { + return detail::studentT(generator_, inShape, inDof); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inA, inB, inC); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray triangle(const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inShape, inA, inB, inC); + } +#endif + + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(const Shape& inShape, dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inShape, inLow, inHigh); + } + +#ifndef NUMCPP_NO_USE_BOOST + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(uint32 inNumPoints, uint32 inDims = 2) + { + return detail::uniformOnSphere(generator_, inNumPoints, inDims); + } +#endif + + //============================================================================ + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inShape, inA, inB); + } + + private: + GeneratorType generator_{}; + }; +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/bernoulli.hpp b/runexamples/cpp/include/NumCpp/Random/bernoulli.hpp new file mode 100644 index 0000000..7717fb2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/bernoulli.hpp @@ -0,0 +1,119 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "bernoulli" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param generator: instance of a random number generator + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + template + bool bernoulli(GeneratorType& generator, double inP = 0.5) + { + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1]."); + } + + std::bernoulli_distribution dist(inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + template + NdArray bernoulli(GeneratorType& generator, const Shape& inShape, double inP = 0.5) + { + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of success must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::bernoulli_distribution dist(inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](bool& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "bernoulli" distribution. + /// + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + inline bool bernoulli(double inP = 0.5) + { + return detail::bernoulli(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "bernoulli" distribution. + /// + /// @param inShape + /// @param inP (probability of success [0, 1]). Default 0.5 + /// @return NdArray + /// + inline NdArray bernoulli(const Shape& inShape, double inP = 0.5) + { + return detail::bernoulli(generator_, inShape, inP); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/beta.hpp b/runexamples/cpp/include/NumCpp/Random/beta.hpp new file mode 100644 index 0000000..d314058 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/beta.hpp @@ -0,0 +1,160 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "beta" distribution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/beta_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param generator: instance of a random number generator + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(GeneratorType& generator, dtype inAlpha, dtype inBeta) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inAlpha < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input alpha must be greater than zero."); + } + + if (inBeta < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input beta must be greater than zero."); + } + + boost::random::beta_distribution dist(inAlpha, inBeta); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(GeneratorType& generator, const Shape& inShape, dtype inAlpha, dtype inBeta) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inAlpha < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input alpha must be greater than zero."); + } + + if (inBeta < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input beta must be greater than zero."); + } + + NdArray returnArray(inShape); + + boost::random::beta_distribution dist(inAlpha, inBeta); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + dtype beta(dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inAlpha, inBeta); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "beta" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.beta.html#numpy.random.beta + /// + /// @param inShape + /// @param inAlpha + /// @param inBeta + /// @return NdArray + /// + template + NdArray beta(const Shape& inShape, dtype inAlpha, dtype inBeta) + { + return detail::beta(generator_, inShape, inAlpha, inBeta); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Random/binomial.hpp b/runexamples/cpp/include/NumCpp/Random/binomial.hpp new file mode 100644 index 0000000..9d391f1 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/binomial.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "binomial" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param generator: instance of a random number generator + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(GeneratorType& generator, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::binomial_distribution dist(inN, inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(GeneratorType& generator, const Shape& inShape, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::binomial_distribution dist(inN, inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype binomial(dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.binomial.html#numpy.random.binomial + /// + /// @param inShape + /// @param inN (number of trials) + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray binomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::binomial(generator_, inShape, inN, inP); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/cauchy.hpp b/runexamples/cpp/include/NumCpp/Random/cauchy.hpp new file mode 100644 index 0000000..ab7f7a7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/cauchy.hpp @@ -0,0 +1,133 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "cauchy" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::cauchy_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::cauchy_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "cauchy" distrubution. + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype cauchy(dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "cauchy" distrubution. + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray cauchy(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::cauchy(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/chiSquare.hpp b/runexamples/cpp/include/NumCpp/Random/chiSquare.hpp new file mode 100644 index 0000000..188262d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/chiSquare.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "chi square" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param generator: instance of a random number generator + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(GeneratorType& generator, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom must be greater than zero."); + } + + std::chi_squared_distribution dist(inDof); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(GeneratorType& generator, const Shape& inShape, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::chi_squared_distribution dist(inDof); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + dtype chiSquare(dtype inDof) + { + return detail::chiSquare(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "chi square" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.chisquare.html#numpy.random.chisquare + /// + /// @param inShape + /// @param inDof (independent random variables) + /// @return NdArray + /// + template + NdArray chiSquare(const Shape& inShape, dtype inDof) + { + return detail::chiSquare(generator_, inShape, inDof); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/choice.hpp b/runexamples/cpp/include/NumCpp/Random/choice.hpp new file mode 100644 index 0000000..c9f5a7c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/choice.hpp @@ -0,0 +1,118 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Chooses a random sample from an input array. +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/permutation.hpp" +#include "NumCpp/Random/randInt.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @return NdArray + /// + template + dtype choice(GeneratorType& generator, const NdArray& inArray) + { + uint32 randIdx = detail::randInt(generator, inArray.size()); + return inArray[randIdx]; + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray + choice(GeneratorType& generator, const NdArray& inArray, uint32 inNum, bool replace = true) + { + if (!replace && inNum > inArray.size()) + { + THROW_INVALID_ARGUMENT_ERROR("when 'replace' == false 'inNum' must be <= inArray.size()"); + } + + if (replace) + { + NdArray outArray(1, inNum); + std::for_each(outArray.begin(), + outArray.end(), + [&generator, &inArray](dtype& value) -> void { value = choice(generator, inArray); }); + + return outArray; + } + + return detail::permutation(generator, inArray)[Slice(inNum)]; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Chooses a random sample from an input array. + /// + /// @param inArray + /// @return NdArray + /// + template + dtype choice(const NdArray& inArray) + { + return detail::choice(generator_, inArray); + } + + //============================================================================ + // Method Description: + /// Chooses inNum random samples from an input array. + /// + /// @param inArray + /// @param inNum + /// @param replace: Whether the sample is with or without replacement + /// @return NdArray + /// + template + NdArray choice(const NdArray& inArray, uint32 inNum, bool replace = true) + { + return detail::choice(generator_, inArray, inNum, replace = true); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/discrete.hpp b/runexamples/cpp/include/NumCpp/Random/discrete.hpp new file mode 100644 index 0000000..07843d6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/discrete.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "discrete" distrubution. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param generator: instance of a random number generator + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(GeneratorType& generator, const NdArray& inWeights) + { + STATIC_ASSERT_INTEGER(dtype); + + std::discrete_distribution dist(inWeights.cbegin(), inWeights.cend()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(GeneratorType& generator, const Shape& inShape, const NdArray& inWeights) + { + STATIC_ASSERT_INTEGER(dtype); + + NdArray returnArray(inShape); + + std::discrete_distribution dist(inWeights.cbegin(), inWeights.cend()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the from the + /// "discrete" distrubution. It produces integers in the + /// range [0, n) with the probability of producing each value + /// is specified by the parameters of the distribution. + /// + /// @param inWeights + /// @return NdArray + /// + template + dtype discrete(const NdArray& inWeights) + { + return detail::discrete(generator_, inWeights); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "discrete" distrubution. It produces + /// integers in the range [0, n) with the probability of + /// producing each value is specified by the parameters + /// of the distribution. + /// + /// @param inShape + /// @param inWeights + /// @return NdArray + /// + template + NdArray discrete(const Shape& inShape, const NdArray& inWeights) + { + return detail::discrete(generator_, inShape, inWeights); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/exponential.hpp b/runexamples/cpp/include/NumCpp/Random/exponential.hpp new file mode 100644 index 0000000..b04b391 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/exponential.hpp @@ -0,0 +1,125 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "exponential" distrubution +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param generator: instance of a random number generator + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(GeneratorType& generator, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + std::exponential_distribution dist(inScaleValue); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(GeneratorType& generator, const Shape& inShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inShape); + + std::exponential_distribution dist(inScaleValue); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype exponential(dtype inScaleValue = 1) + { + return detail::exponential(generator_, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "exponential" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.exponential.html#numpy.random.exponential + /// + /// @param inShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray exponential(const Shape& inShape, dtype inScaleValue = 1) + { + return detail::exponential(generator_, inShape, inScaleValue); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/extremeValue.hpp b/runexamples/cpp/include/NumCpp/Random/extremeValue.hpp new file mode 100644 index 0000000..5113c7f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/extremeValue.hpp @@ -0,0 +1,139 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "extreme value" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(GeneratorType& generator, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + std::extreme_value_distribution dist(inA, inB); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(GeneratorType& generator, const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::extreme_value_distribution dist(inA, inB); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "extreme value" distrubution. + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype extremeValue(dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "extreme value" distrubution. + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray extremeValue(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::extremeValue(generator_, inShape, inA, inB); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/f.hpp b/runexamples/cpp/include/NumCpp/Random/f.hpp new file mode 100644 index 0000000..c88e1aa --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/f.hpp @@ -0,0 +1,147 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "F" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param generator: instance of a random number generator + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(GeneratorType& generator, dtype inDofN, dtype inDofD) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDofN <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom should be greater than zero."); + } + + if (inDofD <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("denominator degrees of freedom should be greater than zero."); + } + + std::fisher_f_distribution dist(inDofN, inDofD); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(GeneratorType& generator, const Shape& inShape, dtype inDofN, dtype inDofD) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDofN <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("numerator degrees of freedom should be greater than zero."); + } + + if (inDofD <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("denominator degrees of freedom should be greater than zero."); + } + + NdArray returnArray(inShape); + + std::fisher_f_distribution dist(inDofN, inDofD); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + dtype f(dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inDofN, inDofD); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "F" distrubution. + /// + /// NumPy Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.f.html#numpy.random.f + /// + /// @param inShape + /// @param inDofN: Degrees of freedom in numerator. Should be greater than zero. + /// @param inDofD: Degrees of freedom in denominator. Should be greater than zero. + /// @return NdArray + /// + template + NdArray f(const Shape& inShape, dtype inDofN, dtype inDofD) + { + return detail::f(generator_, inShape, inDofN, inDofD); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/gamma.hpp b/runexamples/cpp/include/NumCpp/Random/gamma.hpp new file mode 100644 index 0000000..f98ee9a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/gamma.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "gamma" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param generator: instance of a random number generator + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(GeneratorType& generator, dtype inGammaShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inGammaShape <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input gamma shape should be greater than zero."); + } + + if (inScaleValue <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input scale should be greater than zero."); + } + + std::gamma_distribution dist(inGammaShape, inScaleValue); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(GeneratorType& generator, const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inGammaShape <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input gamma shape should be greater than zero."); + } + + if (inScaleValue <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input scale should be greater than zero."); + } + + NdArray returnArray(inShape); + + std::gamma_distribution dist(inGammaShape, inScaleValue); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + dtype gamma(dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inGammaShape, inScaleValue); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "gamma" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.gamma.html#numpy.random.gamma + /// + /// @param inShape + /// @param inGammaShape + /// @param inScaleValue (default 1) + /// @return NdArray + /// + template + NdArray gamma(const Shape& inShape, dtype inGammaShape, dtype inScaleValue = 1) + { + return detail::gamma(generator_, inShape, inGammaShape, inScaleValue); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/generator.hpp b/runexamples/cpp/include/NumCpp/Random/generator.hpp new file mode 100644 index 0000000..6dba1c4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/generator.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Seeds the random number generator +/// +#pragma once + +#include + +namespace nc::random +{ + /// generator function + static std::mt19937_64 generator_; + + //============================================================================ + // Method Description: + /// Seeds the random number generator + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html#numpy.random.seed + /// + /// @param inSeed + /// + inline void seed(int inSeed) + { + generator_.seed(inSeed); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/geometric.hpp b/runexamples/cpp/include/NumCpp/Random/geometric.hpp new file mode 100644 index 0000000..f4c0b64 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/geometric.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "geometric" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param generator: instance of a random number generator + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(GeneratorType& generator, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::geometric_distribution dist(inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(GeneratorType& generator, const Shape& inShape, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::geometric_distribution dist(inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + dtype geometric(double inP = 0.5) + { + return detail::geometric(generator_, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "geometric" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.geometric.html#numpy.random.geometric + /// + /// @param inShape + /// @param inP (probablity of success [0, 1]) + /// @return NdArray + /// + template + NdArray geometric(const Shape& inShape, double inP = 0.5) + { + return detail::geometric(generator_, inShape, inP); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/laplace.hpp b/runexamples/cpp/include/NumCpp/Random/laplace.hpp new file mode 100644 index 0000000..d23e4a0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/laplace.hpp @@ -0,0 +1,138 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "laplace" distrubution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/random/laplace_distribution.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param generator: instance of a random number generator + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(GeneratorType& generator, dtype inLoc = 0, dtype inScale = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + boost::random::laplace_distribution dist(inLoc, inScale); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(GeneratorType& generator, const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inShape); + + boost::random::laplace_distribution dist(inLoc, inScale); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + dtype laplace(dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inLoc, inScale); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "laplace" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.laplace.html#numpy.random.laplace + /// + /// @param inShape + /// @param inLoc: (The position, mu, of the distribution peak. Default is 0) + /// @param inScale: (float optional the exponential decay. Default is 1) + /// @return NdArray + /// + template + NdArray laplace(const Shape& inShape, dtype inLoc = 0, dtype inScale = 1) + { + return detail::laplace(generator_, inShape, inLoc, inScale); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Random/lognormal.hpp b/runexamples/cpp/include/NumCpp/Random/lognormal.hpp new file mode 100644 index 0000000..d223ff6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/lognormal.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "lognormal" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::lognormal_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::lognormal_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype lognormal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "lognormal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.lognormal.html#numpy.random.lognormal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray lognormal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::lognormal(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/negativeBinomial.hpp b/runexamples/cpp/include/NumCpp/Random/negativeBinomial.hpp new file mode 100644 index 0000000..25cbd98 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/negativeBinomial.hpp @@ -0,0 +1,151 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "negative Binomial" distribution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param generator: instance of a random number generator + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(GeneratorType& generator, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + std::negative_binomial_distribution dist(inN, inP); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(GeneratorType& generator, const Shape& inShape, dtype inN, double inP = 0.5) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inN < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input number of trials must be greater than or equal to zero."); + } + + if (inP < 0 || inP > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input probability of sucess must be of the range [0, 1]."); + } + + NdArray returnArray(inShape); + + std::negative_binomial_distribution dist(inN, inP); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + dtype negativeBinomial(dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inN, inP); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "negative Binomial" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.negative_binomial.html#numpy.random.negative_binomial + /// + /// @param inShape + /// @param inN: number of trials + /// @param inP: probablity of success [0, 1] + /// @return NdArray + /// + template + NdArray negativeBinomial(const Shape& inShape, dtype inN, double inP = 0.5) + { + return detail::negativeBinomial(generator_, inShape, inN, inP); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp b/runexamples/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp new file mode 100644 index 0000000..aad5b5b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/nonCentralChiSquared.hpp @@ -0,0 +1,161 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "non central chi squared" distrubution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/non_central_chi_squared_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param generator: instance of a random number generator + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(GeneratorType& generator, dtype inK = 1, dtype inLambda = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inK <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input k must be greater than zero."); + } + + if (inLambda <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input lambda must be greater than zero."); + } + + boost::random::non_central_chi_squared_distribution dist(inK, inLambda); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray + nonCentralChiSquared(GeneratorType& generator, const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inK <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input k must be greater than zero."); + } + + if (inLambda <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input lambda must be greater than zero."); + } + + NdArray returnArray(inShape); + + boost::random::non_central_chi_squared_distribution dist(inK, inLambda); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + dtype nonCentralChiSquared(dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inK, inLambda); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "non central chi squared" distrubution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.noncentral_chisquare.html#numpy.random.noncentral_chisquare + /// + /// @param inShape + /// @param inK (default 1) + /// @param inLambda (default 1) + /// @return NdArray + /// + template + NdArray nonCentralChiSquared(const Shape& inShape, dtype inK = 1, dtype inLambda = 1) + { + return detail::nonCentralChiSquared(generator_, inShape, inK, inLambda); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Random/normal.hpp b/runexamples/cpp/include/NumCpp/Random/normal.hpp new file mode 100644 index 0000000..1e60ae3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/normal.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "normal" distrubution. +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param generator: instance of a random number generator + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(GeneratorType& generator, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + std::normal_distribution dist(inMean, inSigma); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(GeneratorType& generator, const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inSigma <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::normal_distribution dist(inMean, inSigma); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + dtype normal(dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inMean, inSigma); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "normal" distrubution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal + /// + /// @param inShape + /// @param inMean: Mean value of the underlying normal distribution. Default is 0. + /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. + /// Default is 1. + /// @return NdArray + /// + template + NdArray normal(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) + { + return detail::normal(generator_, inShape, inMean, inSigma); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/permutation.hpp b/runexamples/cpp/include/NumCpp/Random/permutation.hpp new file mode 100644 index 0000000..793d689 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/permutation.hpp @@ -0,0 +1,111 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Randomly permute a sequence, or return a permuted range +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/arange.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param generator: instance of a random number generator + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(GeneratorType& generator, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray = arange(inValue); + std::shuffle(returnArray.begin(), returnArray.end(), generator); + return returnArray; + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(GeneratorType& generator, const NdArray& inArray) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + NdArray returnArray(inArray); + std::shuffle(returnArray.begin(), returnArray.end(), generator); + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inValue + /// @return NdArray + /// + template + NdArray permutation(dtype inValue) + { + return detail::permutation(generator_, inValue); + } + + //============================================================================ + // Method Description: + /// Randomly permute a sequence, or return a permuted range. + /// If x is an integer, randomly permute np.arange(x). + /// If x is an array, make a copy and shuffle the elements randomly. + /// + /// @param inArray + /// @return NdArray + /// + template + NdArray permutation(const NdArray& inArray) + { + return detail::permutation(generator_, inArray); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/poisson.hpp b/runexamples/cpp/include/NumCpp/Random/poisson.hpp new file mode 100644 index 0000000..0749eb5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/poisson.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "poisson" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param generator: instance of a random number generator + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(GeneratorType& generator, double inMean = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inMean <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input mean must be greater than zero."); + } + + std::poisson_distribution dist(inMean); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(GeneratorType& generator, const Shape& inShape, double inMean = 1) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inMean <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input mean must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::poisson_distribution dist(inMean); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inMean (default 1) + /// @return NdArray + /// + template + dtype poisson(double inMean = 1) + { + return detail::poisson(generator_, inMean); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "poisson" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.poisson.html#numpy.random.poisson + /// + /// @param inShape + /// @param inMean (default 1) + /// @return NdArray + /// + template + NdArray poisson(const Shape& inShape, double inMean = 1) + { + return detail::poisson(generator_, inShape, inMean); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/rand.hpp b/runexamples/cpp/include/NumCpp/Random/rand.hpp new file mode 100644 index 0000000..b74c95d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/rand.hpp @@ -0,0 +1,124 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Create an array of the given shape and populate it with +/// random samples from a uniform distribution over [0, 1). +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param generator: instance of a random number generator + /// @return NdArray + /// + template + dtype rand(GeneratorType& generator) + { + STATIC_ASSERT_FLOAT(dtype); + + std::uniform_real_distribution dist(static_cast(0.), + static_cast(1.) - DtypeInfo::epsilon()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray returnArray(inShape); + + std::uniform_real_distribution dist(static_cast(0.), + static_cast(1.) - DtypeInfo::epsilon()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @return NdArray + /// + template + dtype rand() + { + return detail::rand(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a uniform distribution over [0, 1). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.rand.html#numpy.random.rand + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray rand(const Shape& inShape) + { + return detail::rand(generator_, inShape); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/randFloat.hpp b/runexamples/cpp/include/NumCpp/Random/randFloat.hpp new file mode 100644 index 0000000..f3665f2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/randFloat.hpp @@ -0,0 +1,157 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Return random floats from low (inclusive) to high (exclusive), +/// with the given shape +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(GeneratorType& generator, dtype inLow, dtype inHigh = 0.) + { + STATIC_ASSERT_FLOAT(dtype); + + if (utils::essentiallyEqual(inLow, inHigh)) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + std::uniform_real_distribution dist(inLow, inHigh - DtypeInfo::epsilon()); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + STATIC_ASSERT_FLOAT(dtype); + + if (utils::essentiallyEqual(inLow, inHigh)) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + NdArray returnArray(inShape); + + std::uniform_real_distribution dist(inLow, inHigh - DtypeInfo::epsilon()); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return a single random float from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randFloat(dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random floats from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.ranf.html#numpy.random.ranf + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randFloat(const Shape& inShape, dtype inLow, dtype inHigh = 0.) + { + return detail::randFloat(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/randInt.hpp b/runexamples/cpp/include/NumCpp/Random/randInt.hpp new file mode 100644 index 0000000..5c2bbe4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/randInt.hpp @@ -0,0 +1,157 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Return random integers from low (inclusive) to high (exclusive), +/// with the given shape +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(GeneratorType& generator, dtype inLow, dtype inHigh = 0) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inLow == inHigh) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh) + { + std::swap(inLow, inHigh); + } + + std::uniform_int_distribution dist(inLow, inHigh - 1); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + STATIC_ASSERT_INTEGER(dtype); + + if (inLow == inHigh) + { + THROW_INVALID_ARGUMENT_ERROR("input low value must be less than the input high value."); + } + else if (inLow > inHigh - 1) + { + std::swap(inLow, inHigh); + } + + NdArray returnArray(inShape); + + std::uniform_int_distribution dist(inLow, inHigh - 1); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&dist, &generator](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Return random integer from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + dtype randInt(dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Return random integers from low (inclusive) to high (exclusive), + /// with the given shape. If no high value is input then the range will + /// go from [0, low). + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint + /// + /// @param inShape + /// @param inLow + /// @param inHigh default 0. + /// @return NdArray + /// + template + NdArray randInt(const Shape& inShape, dtype inLow, dtype inHigh = 0) + { + return detail::randInt(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/randN.hpp b/runexamples/cpp/include/NumCpp/Random/randN.hpp new file mode 100644 index 0000000..8f16b7c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/randN.hpp @@ -0,0 +1,121 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "standard normal" distribution. +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param generator: instance of a random number generator + /// @return dtype + /// + template + dtype randN(GeneratorType& generator) + { + STATIC_ASSERT_FLOAT(dtype); + + std::normal_distribution dist; + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_FLOAT(dtype); + + NdArray returnArray(inShape); + + std::normal_distribution dist; + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Returns a single random value sampled from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @return dtype + /// + template + dtype randN() + { + return detail::randN(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "standard normal" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html#numpy.random.randn + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray randN(const Shape& inShape) + { + return detail::randN(generator_, inShape); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/shuffle.hpp b/runexamples/cpp/include/NumCpp/Random/shuffle.hpp new file mode 100644 index 0000000..033723d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/shuffle.hpp @@ -0,0 +1,65 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// @version 1.1 +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Modify a sequence in-place by shuffling its contents. +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param generator: instance of a random number generator + /// @param inArray + /// + template + void shuffle(GeneratorType& generator, NdArray& inArray) + { + std::shuffle(inArray.begin(), inArray.end(), generator); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Modify a sequence in-place by shuffling its contents. + /// + /// @param inArray + /// + template + void shuffle(NdArray& inArray) + { + return detail::shuffle(generator_, inArray); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/standardNormal.hpp b/runexamples/cpp/include/NumCpp/Random/standardNormal.hpp new file mode 100644 index 0000000..d4377cd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/standardNormal.hpp @@ -0,0 +1,113 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "standard normal" distrubution +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/normal.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param generator: instance of a random number generator + /// @return NdArray + /// + template + dtype standardNormal(GeneratorType& generator) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return detail::normal(generator, 0, 1); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(GeneratorType& generator, const Shape& inShape) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return detail::normal(generator, inShape, 0, 1); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @return NdArray + /// + template + dtype standardNormal() + { + return detail::standardNormal(generator_); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from a "standard normal" distrubution with + /// mean = 0 and std = 1 + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_normal.html#numpy.random.standard_normal + /// + /// @param inShape + /// @return NdArray + /// + template + NdArray standardNormal(const Shape& inShape) + { + return detail::standardNormal(generator_, inShape); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/studentT.hpp b/runexamples/cpp/include/NumCpp/Random/studentT.hpp new file mode 100644 index 0000000..7a3ed4f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/studentT.hpp @@ -0,0 +1,136 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "student-T" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param generator: instance of a random number generator + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(GeneratorType& generator, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("degrees of freedom must be greater than zero."); + } + + std::student_t_distribution dist(inDof); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(GeneratorType& generator, const Shape& inShape, dtype inDof) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inDof <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("degrees of freedom must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::student_t_distribution dist(inDof); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inDof independent random variables + /// @return NdArray + /// + template + dtype studentT(dtype inDof) + { + return detail::studentT(generator_, inDof); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "student-T" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.standard_t.html#numpy.random.standard_t + /// + /// @param inShape + /// @param inDof independent random variables + /// @return NdArray + /// + template + NdArray studentT(const Shape& inShape, dtype inDof) + { + return detail::studentT(generator_, inShape, inDof); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/triangle.hpp b/runexamples/cpp/include/NumCpp/Random/triangle.hpp new file mode 100644 index 0000000..9a226f9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/triangle.hpp @@ -0,0 +1,190 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Create an array of the given shape and populate it with +/// random samples from the "triangle" distribution. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/triangle_distribution.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param generator: instance of a random number generator + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(GeneratorType& generator, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inA < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input A must be greater than or equal to zero."); + } + + if (inB < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input B must be greater than or equal to zero."); + } + + if (inC < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input C must be greater than or equal to zero."); + } + + const bool aLessB = inA <= inB; + const bool bLessC = inB <= inC; + if (!(aLessB && bLessC)) + { + THROW_INVALID_ARGUMENT_ERROR("inputs must be a <= b <= c."); + } + + boost::random::triangle_distribution dist(inA, inB, inC); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray + triangle(GeneratorType& generator, const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inA < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input A must be greater than or equal to zero."); + } + + if (inB < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input B must be greater than or equal to zero."); + } + + if (inC < 0) + { + THROW_INVALID_ARGUMENT_ERROR("input C must be greater than or equal to zero."); + } + + const bool aLessB = inA <= inB; + const bool bLessC = inB <= inC; + if (!(aLessB && bLessC)) + { + THROW_INVALID_ARGUMENT_ERROR("inputs must be a <= b <= c."); + } + + NdArray returnArray(inShape); + + boost::random::triangle_distribution dist(inA, inB, inC); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + dtype triangle(dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inA, inB, inC); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "triangle" distribution. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html#numpy.random.triangular + /// + /// @param inShape + /// @param inA + /// @param inB + /// @param inC + /// @return NdArray + /// + template + NdArray triangle(const Shape& inShape, dtype inA = 0, dtype inB = 0.5, dtype inC = 1) + { + return detail::triangle(generator_, inShape, inA, inB, inC); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Random/uniform.hpp b/runexamples/cpp/include/NumCpp/Random/uniform.hpp new file mode 100644 index 0000000..4904d6c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/uniform.hpp @@ -0,0 +1,126 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Draw samples from a uniform distribution. +/// +#pragma once + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Random/randFloat.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param generator: instance of a random number generator + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(GeneratorType& generator, dtype inLow, dtype inHigh) + { + STATIC_ASSERT_FLOAT(dtype); + + return detail::randFloat(generator, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(GeneratorType& generator, const Shape& inShape, dtype inLow, dtype inHigh) + { + STATIC_ASSERT_FLOAT(dtype); + + return detail::randFloat(generator, inShape, inLow, inHigh); + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Draw sample from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + dtype uniform(dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inLow, inHigh); + } + + //============================================================================ + // Method Description: + /// Draw samples from a uniform distribution. + /// + /// Samples are uniformly distributed over the half - + /// open interval[low, high) (includes low, but excludes high) + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html#numpy.random.uniform + /// + /// @param inShape + /// @param inLow + /// @param inHigh + /// @return NdArray + /// + template + NdArray uniform(const Shape& inShape, dtype inLow, dtype inHigh) + { + return detail::uniform(generator_, inShape, inLow, inHigh); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Random/uniformOnSphere.hpp b/runexamples/cpp/include/NumCpp/Random/uniformOnSphere.hpp new file mode 100644 index 0000000..140e3a0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/uniformOnSphere.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Such a distribution produces random numbers uniformly +/// distributed on the unit sphere of arbitrary dimension dim. +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/random/uniform_on_sphere.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param generator: instance of a random number generator + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(GeneratorType& generator, uint32 inNumPoints, uint32 inDims = 2) + { + STATIC_ASSERT_FLOAT(dtype); + + if (inNumPoints == 0) + { + return {}; + } + + boost::random::uniform_on_sphere dist(static_cast(inDims)); + + NdArray returnArray(inNumPoints, inDims); + for (uint32 row = 0; row < inNumPoints; ++row) + { + const auto& point = dist(generator); + std::copy(point.begin(), point.end(), returnArray.begin(row)); + } + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Such a distribution produces random numbers uniformly + /// distributed on the unit sphere of arbitrary dimension dim. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inNumPoints + /// @param inDims: dimension of the sphere (default 2) + /// @return NdArray + /// + template + NdArray uniformOnSphere(uint32 inNumPoints, uint32 inDims = 2) + { + return detail::uniformOnSphere(generator_, inNumPoints, inDims); + } +} // namespace nc::random + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Random/weibull.hpp b/runexamples/cpp/include/NumCpp/Random/weibull.hpp new file mode 100644 index 0000000..7066297 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Random/weibull.hpp @@ -0,0 +1,150 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// "weibull" distribution +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Shape.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Random/generator.hpp" + +namespace nc::random +{ + namespace detail + { + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param generator: instance of a random number generator + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(GeneratorType& generator, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + std::weibull_distribution dist(inA, inB); + return dist(generator); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param generator: instance of a random number generator + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(GeneratorType& generator, const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + if (inA <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input a must be greater than zero."); + } + + if (inB <= 0) + { + THROW_INVALID_ARGUMENT_ERROR("input b must be greater than zero."); + } + + NdArray returnArray(inShape); + + std::weibull_distribution dist(inA, inB); + + std::for_each(returnArray.begin(), + returnArray.end(), + [&generator, &dist](dtype& value) -> void { value = dist(generator); }); + + return returnArray; + } + } // namespace detail + + //============================================================================ + // Method Description: + /// Single random value sampled from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + dtype weibull(dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inA, inB); + } + + //============================================================================ + // Method Description: + /// Create an array of the given shape and populate it with + /// random samples from the "weibull" distribution. + /// + /// NumPy Reference: + /// https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.weibull.html#numpy.random.weibull + /// + /// @param inShape + /// @param inA (default 1) + /// @param inB (default 1) + /// @return NdArray + /// + template + NdArray weibull(const Shape& inShape, dtype inA = 1, dtype inB = 1) + { + return detail::weibull(generator_, inShape, inA, inB); + } +} // namespace nc::random diff --git a/runexamples/cpp/include/NumCpp/Roots.hpp b/runexamples/cpp/include/NumCpp/Roots.hpp new file mode 100644 index 0000000..6e669d0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots.hpp @@ -0,0 +1,34 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Roots/Bisection.hpp" +#include "NumCpp/Roots/Brent.hpp" +#include "NumCpp/Roots/Dekker.hpp" +#include "NumCpp/Roots/Newton.hpp" +#include "NumCpp/Roots/Secant.hpp" diff --git a/runexamples/cpp/include/NumCpp/Roots/Bisection.hpp b/runexamples/cpp/include/NumCpp/Roots/Bisection.hpp new file mode 100644 index 0000000..3323827 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Bisection.hpp @@ -0,0 +1,155 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Bisection root finding method + /// + class Bisection : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Bisection(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Bisection(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Bisection() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + checkAndFixAlgorithmCriteria(a, b); + + double x = 0.5 * (a + b); + double fx = f_(x); + + while (std::fabs(fx) >= epsilon_) + { + x = calculateX(x, a, b, fx); + fx = f_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Checks the bounds criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// + void checkAndFixAlgorithmCriteria(double &a, double &b) const noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (f_(a) < f_(b)) + { + std::swap(a, b); + } + } + + //============================================================================ + // Method Description: + /// Calculates the bisection point + /// + /// @param x: the evaluation point + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fx: the function evaluated at x + /// @return x + /// + static double calculateX(double x, double &a, double &b, double fx) noexcept + { + if (fx < 0) + { + b = x; + } + else + { + a = x; + } + + return 0.5 * (a + b); + } + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Roots/Brent.hpp b/runexamples/cpp/include/NumCpp/Roots/Brent.hpp new file mode 100644 index 0000000..ebcd6a4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Brent.hpp @@ -0,0 +1,280 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Brent root finding method + /// + class Brent : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Brent(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Brent(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Brent() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + double fa = f_(a); + double fb = f_(b); + + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + double lastB = a; // b_{k-1} + double lastFb = fa; + double s = DtypeInfo::max(); + double fs = DtypeInfo::max(); + double penultimateB = a; // b_{k-2} + + bool bisection = true; + while (std::fabs(fb) > epsilon_ && std::fabs(fs) > epsilon_ && std::fabs(b - a) > epsilon_) + { + if (useInverseQuadraticInterpolation(fa, fb, lastFb)) + { + s = calculateInverseQuadraticInterpolation(a, b, lastB, fa, fb, lastFb); + } + else + { + s = calculateSecant(a, b, fa, fb); + } + + if (useBisection(bisection, b, lastB, penultimateB, s)) + { + s = calculateBisection(a, b); + bisection = true; + } + else + { + bisection = false; + } + + fs = f_(s); + penultimateB = lastB; + lastB = b; + + if (fa * fs < 0) + { + b = s; + } + else + { + a = s; + } + + fa = f_(a); + lastFb = fb; + fb = f_(b); + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + incrementNumberOfIterations(); + } + + return fb < fs ? b : s; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Calculates the bisection point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return x + /// + static double calculateBisection(const double a, const double b) noexcept + { + return 0.5 * (a + b); + } + + //============================================================================ + // Method Description: + /// Calculates the secant point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @return the secant point + /// + static double calculateSecant(const double a, const double b, const double fa, const double fb) noexcept + { + // No need to check division by 0, in this case the method returns NAN which is taken care by + // useSecantMethod method + return b - fb * (b - a) / (fb - fa); + } + + //============================================================================ + // Method Description: + /// Calculates the inverse quadratic interpolation + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param lastB: the previous upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @param lastFb: the previous function evaluated at the upper bound + /// @return the inverse quadratic interpolation + /// + static double calculateInverseQuadraticInterpolation(const double a, + const double b, + const double lastB, + const double fa, + const double fb, + const double lastFb) noexcept + { + return a * fb * lastFb / ((fa - fb) * (fa - lastFb)) + b * fa * lastFb / ((fb - fa) * (fb - lastFb)) + + lastB * fa * fb / ((lastFb - fa) * (lastFb - fb)); + } + + //============================================================================ + // Method Description: + /// Uses the inverse quadratic interpolation + /// + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// @param lastFb: the previous function evaluated at the upper bound + /// @return bool + /// + static bool useInverseQuadraticInterpolation(const double fa, const double fb, const double lastFb) noexcept + { + return !utils::essentiallyEqual(fa, lastFb) && utils::essentiallyEqual(fb, lastFb); + } + + //============================================================================ + // Method Description: + /// Checks the algorithm criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evaluated at a + /// @param fb: the function evaluated at b + /// + static void checkAndFixAlgorithmCriteria(double &a, double &b, double &fa, double &fb) noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (std::fabs(fa) < std::fabs(fb)) + { + std::swap(a, b); + std::swap(fa, fb); + } + } + + //============================================================================ + // Method Description: + /// Uses the bisection + /// + /// @param bisection: the bisection point + /// @param b: the upper bound + /// @param lastB: the previous upper bound + /// @param penultimateB: + /// @param s: + /// @return bool + /// + [[nodiscard]] bool useBisection(const bool bisection, + const double b, + const double lastB, + const double penultimateB, + const double s) const noexcept + { + const double DELTA = epsilon_ + std::numeric_limits::min(); + + return (bisection && + std::fabs(s - b) >= + 0.5 * std::fabs(b - lastB)) || // Bisection was used in last step but |s-b|>=|b-lastB|/2 <- + // Interpolation step would be to rough, so still use bisection + (!bisection && std::fabs(s - b) >= + 0.5 * std::fabs(lastB - penultimateB)) || // Interpolation was used in last step + // but |s-b|>=|lastB-penultimateB|/2 <- + // Interpolation step would be to small + (bisection && + std::fabs(b - lastB) < DELTA) || // If last iteration was using bisection and difference between + // b and lastB is < delta use bisection for next iteration + (!bisection && std::fabs(lastB - penultimateB) < + DELTA); // If last iteration was using interpolation but difference between + // lastB ond penultimateB is < delta use biscetion for next iteration + } + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Roots/Dekker.hpp b/runexamples/cpp/include/NumCpp/Roots/Dekker.hpp new file mode 100644 index 0000000..f24a0ed --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Dekker.hpp @@ -0,0 +1,198 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Dekker root finding method + /// + class Dekker : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Dekker(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Dekker(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Dekker() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + double fa = f_(a); + double fb = f_(b); + + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + double lastB = a; + double lastFb = fa; + + while (std::fabs(fb) > epsilon_ && std::fabs(b - a) > epsilon_) + { + const double s = calculateSecant(b, fb, lastB, lastFb); + const double m = calculateBisection(a, b); + + lastB = b; + + b = useSecantMethod(b, s, m) ? s : m; + + lastFb = fb; + fb = f_(b); + + if (fa * fb > 0 && fb * lastFb < 0) + { + a = lastB; + } + + fa = f_(a); + checkAndFixAlgorithmCriteria(a, b, fa, fb); + + incrementNumberOfIterations(); + } + + return b; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Checks the bounds criteria + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @param fa: the function evalulated at the lower bound + /// @param fb: the function evalulated at the upper bound + /// + static void checkAndFixAlgorithmCriteria(double &a, double &b, double &fa, double &fb) noexcept + { + // Algorithm works in range [a,b] if criteria f(a)*f(b) < 0 and f(a) > f(b) is fulfilled + if (std::fabs(fa) < std::fabs(fb)) + { + std::swap(a, b); + std::swap(fa, fb); + } + } + + //============================================================================ + // Method Description: + /// Calculates secant + /// + /// @param b: the upper bound + /// @param fb: the function evalulated at the upper bound + /// @param lastB: the last upper bound + /// @param lastFb: the function evalulated at the last upper bound + /// @ return secant value + /// + static double calculateSecant(double b, double fb, double lastB, double lastFb) noexcept + { + // No need to check division by 0, in this case the method returns NAN which is taken care by + // useSecantMethod method + return b - fb * (b - lastB) / (fb - lastFb); + } + + //============================================================================ + // Method Description: + /// Calculate the bisection point + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return bisection point + /// + static double calculateBisection(double a, double b) noexcept + { + return 0.5 * (a + b); + } + + //============================================================================ + // Method Description: + /// Whether or not to use the secant method + /// + /// @param b: the upper bound + /// @param s: + /// @param m: + /// @ return bool + /// + static bool useSecantMethod(double b, double s, double m) noexcept + { + // Value s calculated by secant method has to be between m and b + return (b > m && s > m && s < b) || (b < m && s > b && s < m); + } + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Roots/Iteration.hpp b/runexamples/cpp/include/NumCpp/Roots/Iteration.hpp new file mode 100644 index 0000000..f0268e4 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Iteration.hpp @@ -0,0 +1,120 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// ABC for iteration classes to derive from + class Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// + explicit Iteration(double epsilon) noexcept : + epsilon_(epsilon) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// + Iteration(double epsilon, uint32 maxNumIterations) noexcept : + epsilon_(epsilon), + maxNumIterations_(maxNumIterations) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + virtual ~Iteration() noexcept = default; + + //============================================================================ + // Method Description: + /// Returns the number of iterations + /// + /// @return: number of iterations + /// + [[nodiscard]] uint32 numIterations() const noexcept + { + return numIterations_; + } + + protected: + //============================================================================ + // Method Description: + /// Resets the number of iterations + /// + void resetNumberOfIterations() noexcept + { + numIterations_ = 0; + } + + //============================================================================ + // Method Description: + /// Incraments the number of iterations + /// + /// @return the number of iterations prior to incramenting + /// + void incrementNumberOfIterations() + { + ++numIterations_; + if (numIterations_ > maxNumIterations_) + { + THROW_RUNTIME_ERROR( + "Maximum number of iterations has been reached; no root has been found within epsilon."); + } + } + + //====================================Attributes============================== + const double epsilon_; + uint32 maxNumIterations_{ 1000 }; + uint32 numIterations_{ 0 }; + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Roots/Newton.hpp b/runexamples/cpp/include/NumCpp/Roots/Newton.hpp new file mode 100644 index 0000000..b4ebdf3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Newton.hpp @@ -0,0 +1,137 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Newton root finding method + /// + class Newton : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// @param fPrime: the derivative of the function + /// + Newton(const double epsilon, std::function f, std::function fPrime) noexcept : + Iteration(epsilon), + f_(std::move(f)), + fPrime_(std::move(fPrime)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// @param fPrime: the derivative of the function + /// + Newton(const double epsilon, + const uint32 maxNumIterations, + std::function f, + std::function fPrime) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)), + fPrime_(std::move(fPrime)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Newton() noexcept override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param x: the starting point + /// @return root nearest the starting point + /// + double solve(double x) + { + resetNumberOfIterations(); + + double fx = f_(x); + double fxPrime = fPrime_(x); + + while (std::fabs(fx) >= epsilon_) + { + x = calculateX(x, fx, fxPrime); + + fx = f_(x); + fxPrime = fPrime_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + const std::function fPrime_; + + //============================================================================ + // Method Description: + /// Calculates x + /// + /// @param x: the current x value + /// @param fx: the function evaluated at the current x value + /// @param fxPrime: the derivate of the function evaluated at the current x value + /// @return x + /// + static double calculateX(double x, double fx, double fxPrime) noexcept + { + return x - fx / fxPrime; + } + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Roots/Secant.hpp b/runexamples/cpp/include/NumCpp/Roots/Secant.hpp new file mode 100644 index 0000000..41f43bc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Roots/Secant.hpp @@ -0,0 +1,143 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2019 Benjamin Mahr +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Finds the roots of the polynomial +/// +/// Code modified under MIT license from https://github.com/Ben1980/rootApproximation +/// as posted in +/// https://thoughts-on-coding.com/2019/06/06/numerical-methods-with-cpp-part-3-root-approximation-algorithms/ +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Roots/Iteration.hpp" + +namespace nc::roots +{ + //================================================================================ + // Class Description: + /// Secant root finding method + /// + class Secant : public Iteration + { + public: + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param f: the function + /// + Secant(const double epsilon, std::function f) noexcept : + Iteration(epsilon), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param epsilon: the epsilon value + /// @param maxNumIterations: the maximum number of iterations to perform + /// @param f: the function + /// + Secant(const double epsilon, const uint32 maxNumIterations, std::function f) noexcept : + Iteration(epsilon, maxNumIterations), + f_(std::move(f)) + { + } + + //============================================================================ + // Method Description: + /// Destructor + /// + ~Secant() override = default; + + //============================================================================ + // Method Description: + /// Solves for the root in the range [a, b] + /// + /// @param a: the lower bound + /// @param b: the upper bound + /// @return root between the bound + /// + double solve(double a, double b) + { + resetNumberOfIterations(); + + if (f_(a) > f_(b)) + { + std::swap(a, b); + } + + double x = b; + double lastX = a; + double fx = f_(b); + double lastFx = f_(a); + + while (std::fabs(fx) >= epsilon_) + { + const double x_tmp = calculateX(x, lastX, fx, lastFx); + + lastFx = fx; + lastX = x; + x = x_tmp; + + fx = f_(x); + + incrementNumberOfIterations(); + } + + return x; + } + + private: + //============================================================================ + const std::function f_; + + //============================================================================ + // Method Description: + /// Calculates x + /// + /// @param x: the current x value + /// @param lastX: the previous x value + /// @param fx: the function evaluated at the current x value + /// @param lastFx: the function evaluated at the previous x value + /// @return x + /// + static double calculateX(double x, double lastX, double fx, double lastFx) noexcept + { + const double functionDifference = fx - lastFx; + return x - fx * (x - lastX) / functionDifference; + } + }; +} // namespace nc::roots diff --git a/runexamples/cpp/include/NumCpp/Rotations.hpp b/runexamples/cpp/include/NumCpp/Rotations.hpp new file mode 100644 index 0000000..5bba0f0 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Rotations.hpp @@ -0,0 +1,33 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Module for dealing with rotations +/// +#pragma once + +#include "NumCpp/Rotations/DCM.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Rotations/rodriguesRotation.hpp" +#include "NumCpp/Rotations/wahbasProblem.hpp" diff --git a/runexamples/cpp/include/NumCpp/Rotations/DCM.hpp b/runexamples/cpp/include/NumCpp/Rotations/DCM.hpp new file mode 100644 index 0000000..0cabd3f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Rotations/DCM.hpp @@ -0,0 +1,192 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Factory methods for generating direction cosine matrices and vectors +/// +#pragma once + +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/round.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Rotations/Quaternion.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //================================================================================ + /// Factory methods for generating direction cosine matrices and vectors + class DCM + { + public: + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates according + /// to the input euler angles + /// + /// @param roll: euler roll angle in radians + /// @param pitch: euler pitch angle in radians + /// @param yaw: euler yaw angle in radians + /// @return NdArray + /// + static NdArray eulerAngles(double roll, double pitch, double yaw) + { + return Quaternion(roll, pitch, yaw).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates according + /// to the input euler angles + /// + /// @param angles: euler roll, pitch, angles + /// @return NdArray + /// + static NdArray eulerAngles(const NdArray& angles) + { + return Quaternion(angles).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the input axis by the input angle + /// + /// @param inAxis: euler axis cartesian vector with x,y,z components + /// @param inAngle: euler angle in radians + /// @return NdArray + /// + static NdArray eulerAxisAngle(const NdArray& inAxis, double inAngle) + { + return Quaternion(inAxis, inAngle).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the input axis by the input angle + /// + /// @param inAxis: euler axis cartesian vector with x,y,z components + /// @param inAngle: euler angle in radians + /// @return NdArray + /// + static NdArray eulerAxisAngle(const Vec3& inAxis, double inAngle) + { + return Quaternion(inAxis, inAngle).toDCM(); + } + + //============================================================================ + // Method Description: + /// returns whether the input array is a direction cosine + /// matrix + /// + /// @param inArray + /// @return bool + /// + static bool isValid(const NdArray& inArray) + { + const Shape inShape = inArray.shape(); + return inShape.rows == inShape.cols && + utils::essentiallyEqual(round(linalg::det(inArray), 2), 1.) && + utils::essentiallyEqual(round(linalg::det(inArray.transpose()), 2), 1.); + } + + //============================================================================ + // Method Description: + /// The euler roll angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler roll angle in radians + /// + static double roll(const NdArray& dcm) + { + return Quaternion(dcm).roll(); + } + + //============================================================================ + // Method Description: + /// The euler pitch angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler pitch angle in radians + /// + static double pitch(const NdArray& dcm) + { + return Quaternion(dcm).pitch(); + } + + //============================================================================ + // Method Description: + /// The euler yaw angle in radians + /// + /// @param dcm: a valid direction cosine matrix + /// @return euler yaw angle in radians + /// + static double yaw(const NdArray& dcm) + { + return Quaternion(dcm).yaw(); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray xRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 1., 0., 0. }, inAngle); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray yRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 0., 1., 0. }, inAngle); + } + + //============================================================================ + // Method Description: + /// returns a direction cosine matrix that rotates about + /// the x axis by the input angle + /// + /// @param inAngle (in radians) + /// @return NdArray + /// + static NdArray zRotation(double inAngle) + { + return DCM::eulerAxisAngle(Vec3{ 0., 0., 1. }, inAngle); + } + }; +} // namespace nc::rotations diff --git a/runexamples/cpp/include/NumCpp/Rotations/Quaternion.hpp b/runexamples/cpp/include/NumCpp/Rotations/Quaternion.hpp new file mode 100644 index 0000000..f365303 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Rotations/Quaternion.hpp @@ -0,0 +1,1028 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Holds a unit quaternion +/// +#pragma once + +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/argmax.hpp" +#include "NumCpp/Functions/clip.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/norm.hpp" +#include "NumCpp/Functions/square.hpp" +#include "NumCpp/Linalg/hat.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //================================================================================ + // Class Description: + /// Holds a unit quaternion + class Quaternion + { + public: + //============================================================================ + // Method Description: + /// Default Constructor + /// + Quaternion() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param roll: euler roll angle in radians + /// @param pitch: euler pitch angle in radians + /// @param yaw: euler yaw angle in radians + /// + Quaternion(double roll, double pitch, double yaw) noexcept + { + eulerToQuat(roll, pitch, yaw); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inI + /// @param inJ + /// @param inK + /// @param inS + /// + Quaternion(double inI, double inJ, double inK, double inS) noexcept : + components_{ inI, inJ, inK, inS } + { + normalize(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param components + /// + Quaternion(const std::array& components) noexcept : + components_{ components } + { + normalize(); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inArray: if size = 3 the roll, pitch, yaw euler angles + /// if size = 4 the i, j, k, s components + /// if shape = [3, 3] then direction cosine matrix + /// + Quaternion(const NdArray& inArray) : + components_{ 0., 0., 0., 0. } + { + if (inArray.size() == 3) + { + // euler angles + eulerToQuat(inArray[0], inArray[1], inArray[2]); + } + else if (inArray.size() == 4) + { + // quaternion i, j, k, s components + stl_algorithms::copy(inArray.cbegin(), inArray.cend(), components_.begin()); + normalize(); + } + else if (inArray.size() == 9) + { + // direction cosine matrix + dcmToQuat(inArray); + } + else + { + THROW_INVALID_ARGUMENT_ERROR("input array is not a valid size."); + } + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inAxis: Euler axis + /// @param inAngle: Euler angle in radians + /// + Quaternion(const Vec3& inAxis, double inAngle) noexcept + { + // normalize the input vector + Vec3 normAxis = inAxis.normalize(); + + const double halfAngle = inAngle / 2.; + const double sinHalfAngle = std::sin(halfAngle); + + components_[0] = normAxis.x * sinHalfAngle; + components_[1] = normAxis.y * sinHalfAngle; + components_[2] = normAxis.z * sinHalfAngle; + components_[3] = std::cos(halfAngle); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inAxis: Euler axis x,y,z vector components + /// @param inAngle: Euler angle in radians + /// + Quaternion(const NdArray& inAxis, double inAngle) : + Quaternion(Vec3(inAxis), inAngle) + { + } + + //============================================================================ + // Method Description: + /// the angle of rotation around the rotation axis that is described by the quaternion + /// + /// @return radians + /// + [[nodiscard]] double angleOfRotation() const noexcept + { + return 2. * std::acos(s()); + } + + //============================================================================ + // Method Description: + /// angular velocity vector between the two quaternions. The norm + /// of the array is the magnitude + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inTime (seperation time) + /// @return NdArray + /// + static NdArray angularVelocity(const Quaternion& inQuat1, const Quaternion& inQuat2, double inTime) + { + NdArray q0 = inQuat1.toNdArray(); + NdArray q1 = inQuat2.toNdArray(); + + NdArray qDot = q1 - q0; + qDot /= inTime; + + NdArray eyeTimesScalar(3); + eyeTimesScalar.zeros(); + eyeTimesScalar(0, 0) = inQuat2.s(); + eyeTimesScalar(1, 1) = inQuat2.s(); + eyeTimesScalar(2, 2) = inQuat2.s(); + + NdArray epsilonHat = linalg::hat(inQuat2.i(), inQuat2.j(), inQuat2.k()); + NdArray q(4, 3); + q.put(Slice(0, 3), Slice(0, 3), eyeTimesScalar + epsilonHat); + q(3, 0) = -inQuat2.i(); + q(3, 1) = -inQuat2.j(); + q(3, 2) = -inQuat2.k(); + + NdArray omega = q.transpose().dot(qDot.transpose()); + return omega *= 2.; + } + + //============================================================================ + // Method Description: + /// angular velocity vector between the two quaternions. The norm + /// of the array is the magnitude + /// + /// @param inQuat2 + /// @param inTime (seperation time) + /// @return NdArray + /// + [[nodiscard]] NdArray angularVelocity(const Quaternion& inQuat2, double inTime) const + { + return angularVelocity(*this, inQuat2, inTime); + } + + //============================================================================ + // Method Description: + /// the axis of rotation described by the quaternion + /// + /// @return Vec3 + /// + [[nodiscard]] Vec3 axisOfRotation() const noexcept + { + const auto halfAngle = angleOfRotation() / 2.; + const auto sinHalfAngle = std::sin(halfAngle); + auto axis = Vec3(i() / sinHalfAngle, j() / sinHalfAngle, k() / sinHalfAngle); + + // shouldn't be necessary, but let's be pedantic + return axis.normalize(); + } + + //============================================================================ + // Method Description: + /// quaternion conjugate + /// + /// @return Quaternion + /// + [[nodiscard]] Quaternion conjugate() const noexcept + { + return { -i(), -j(), -k(), s() }; + } + + //============================================================================ + // Method Description: + /// returns the i component + /// + /// @return double + /// + [[nodiscard]] double i() const noexcept + { + return components_[0]; + } + + //============================================================================ + // Method Description: + /// quaternion identity (0,0,0,1) + /// + /// @return Quaternion + /// + static Quaternion identity() noexcept + { + return {}; + } + + //============================================================================ + // Method Description: + /// quaternion inverse + /// + /// @return Quaterion + /// + [[nodiscard]] Quaternion inverse() const noexcept + { + /// for unit quaternions the inverse is equal to the conjugate + return conjugate(); + } + + //============================================================================ + // Method Description: + /// returns the j component + /// + /// @return double + /// + [[nodiscard]] double j() const noexcept + { + return components_[1]; + } + + //============================================================================ + // Method Description: + /// returns the k component + /// + /// @return double + /// + [[nodiscard]] double k() const noexcept + { + return components_[2]; + } + + //============================================================================ + // Method Description: + /// linearly interpolates between the two quaternions + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inPercent [0, 1] + /// @return Quaternion + /// + static Quaternion nlerp(const Quaternion& inQuat1, const Quaternion& inQuat2, double inPercent) + { + if (inPercent < 0. || inPercent > 1.) + { + THROW_INVALID_ARGUMENT_ERROR("input percent must be of the range [0,1]."); + } + + if (utils::essentiallyEqual(inPercent, 0.)) + { + return inQuat1; + } + if (utils::essentiallyEqual(inPercent, 1.)) + { + return inQuat2; + } + + const double oneMinus = 1. - inPercent; + std::array newComponents{}; + + stl_algorithms::transform(inQuat1.components_.begin(), + inQuat1.components_.end(), + inQuat2.components_.begin(), + newComponents.begin(), + [inPercent, oneMinus](double component1, double component2) -> double + { return oneMinus * component1 + inPercent * component2; }); + + return { newComponents }; + } + + //============================================================================ + // Method Description: + /// linearly interpolates between the two quaternions + /// + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + [[nodiscard]] Quaternion nlerp(const Quaternion& inQuat2, double inPercent) const + { + return nlerp(*this, inQuat2, inPercent); + } + + //============================================================================ + // Method Description: + /// The euler pitch angle in radians + /// + /// @return euler pitch angle in radians + /// + [[nodiscard]] double pitch() const noexcept + { + return std::asin(2 * (s() * j() - k() * i())); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the pitch axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion pitchRotation(double inAngle) noexcept + { + return { 0., inAngle, 0. }; + } + + //============================================================================ + // Method Description: + /// prints the Quaternion to the console + /// + void print() const + { + std::cout << *this; + } + + //============================================================================ + // Method Description: + /// The euler roll angle in radians + /// + /// @return euler roll angle in radians + /// + [[nodiscard]] double roll() const noexcept + { + return std::atan2(2. * (s() * i() + j() * k()), 1. - 2. * (utils::sqr(i()) + utils::sqr(j()))); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the roll axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion rollRotation(double inAngle) noexcept + { + return { inAngle, 0., 0. }; + } + + //============================================================================ + // Method Description: + /// rotate a vector using the quaternion + /// + /// @param inVector (cartesian vector with x,y,z components) + /// @return NdArray (cartesian vector with x,y,z components) + /// + [[nodiscard]] NdArray rotate(const NdArray& inVector) const + { + if (inVector.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input inVector must be a cartesion vector of length = 3."); + } + + return *this * inVector; + } + + //============================================================================ + // Method Description: + /// rotate a vector using the quaternion + /// + /// @param inVec3 + /// @return Vec3 + /// + [[nodiscard]] Vec3 rotate(const Vec3& inVec3) const + { + return *this * inVec3; + } + + //============================================================================ + // Method Description: + /// returns the s component + /// + /// @return double + /// + [[nodiscard]] double s() const noexcept + { + return components_[3]; + } + + //============================================================================ + // Method Description: + /// spherical linear interpolates between the two quaternions + /// + /// @param inQuat1 + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + static Quaternion slerp(const Quaternion& inQuat1, const Quaternion& inQuat2, double inPercent) + { + if (inPercent < 0 || inPercent > 1) + { + THROW_INVALID_ARGUMENT_ERROR("input percent must be of the range [0, 1]"); + } + + if (utils::essentiallyEqual(inPercent, 0.)) + { + return inQuat1; + } + if (utils::essentiallyEqual(inPercent, 1.)) + { + return inQuat2; + } + + double dotProduct = dot(inQuat1.toNdArray(), inQuat2.toNdArray()).item(); + + // If the dot product is negative, the quaternions + // have opposite handed-ness and slerp won't take + // the shorter path. Fix by reversing one quaternion. + Quaternion quat1Copy(inQuat1); + if (dotProduct < 0.) + { + quat1Copy *= -1.; + dotProduct *= -1.; + } + + constexpr double DOT_THRESHOLD = 0.9995; + if (dotProduct > DOT_THRESHOLD) + { + // If the inputs are too close for comfort, linearly interpolate + // and normalize the result. + return nlerp(inQuat1, inQuat2, inPercent); + } + + dotProduct = clip(dotProduct, -1., 1.); // Robustness: Stay within domain of acos() + const double theta0 = std::acos(dotProduct); // angle between input vectors + const double theta = theta0 * inPercent; // angle between v0 and result + + const double s0 = std::cos(theta) - + dotProduct * std::sin(theta) / std::sin(theta0); // == sin(theta_0 - theta) / sin(theta_0) + const double s1 = std::sin(theta) / std::sin(theta0); + + NdArray interpQuat = (quat1Copy.toNdArray() * s0) + (inQuat2.toNdArray() * s1); + return Quaternion(interpQuat); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// spherical linear interpolates between the two quaternions + /// + /// @param inQuat2 + /// @param inPercent (0, 1) + /// @return Quaternion + /// + [[nodiscard]] Quaternion slerp(const Quaternion& inQuat2, double inPercent) const + { + return slerp(*this, inQuat2, inPercent); + } + + //============================================================================ + // Method Description: + /// returns the quaternion as a string representation + /// + /// @return std::string + /// + [[nodiscard]] std::string str() const + { + std::string output = "[" + utils::num2str(i()) + ", " + utils::num2str(j()) + ", " + utils::num2str(k()) + + ", " + utils::num2str(s()) + "]\n"; + + return output; + } + + //============================================================================ + // Method Description: + /// returns the direction cosine matrix + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toDCM() const + { + NdArray dcm(3); + + const double q0 = i(); + const double q1 = j(); + const double q2 = k(); + const double q3 = s(); + + const double q0sqr = utils::sqr(q0); + const double q1sqr = utils::sqr(q1); + const double q2sqr = utils::sqr(q2); + const double q3sqr = utils::sqr(q3); + + dcm(0, 0) = q3sqr + q0sqr - q1sqr - q2sqr; + dcm(0, 1) = 2. * (q0 * q1 - q3 * q2); + dcm(0, 2) = 2. * (q0 * q2 + q3 * q1); + dcm(1, 0) = 2. * (q0 * q1 + q3 * q2); + dcm(1, 1) = q3sqr + q1sqr - q0sqr - q2sqr; + dcm(1, 2) = 2. * (q1 * q2 - q3 * q0); + dcm(2, 0) = 2. * (q0 * q2 - q3 * q1); + dcm(2, 1) = 2. * (q1 * q2 + q3 * q0); + dcm(2, 2) = q3sqr + q2sqr - q0sqr - q1sqr; + + return dcm; + } + + //============================================================================ + // Method Description: + /// returns the quaternion as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + auto componentsCopy = components_; + return NdArray(componentsCopy); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the x-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion xRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 1., 0., 0. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// The euler yaw angle in radians + /// + /// @return euler yaw angle in radians + /// + [[nodiscard]] double yaw() const noexcept + { + return std::atan2(2. * (s() * k() + i() * j()), 1. - 2. * (utils::sqr(j()) + utils::sqr(k()))); + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the yaw axis + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion yawRotation(double inAngle) noexcept + { + return { 0., 0., inAngle }; + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the y-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion yRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 0., 1., 0. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// returns a quaternion to rotate about the y-axis by the input angle + /// + /// @param inAngle (radians) + /// @return Quaternion + /// + static Quaternion zRotation(double inAngle) noexcept + { + const Vec3 eulerAxis = { 0., 0., 1. }; + return Quaternion(eulerAxis, inAngle); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// equality operator + /// + /// @param inRhs + /// @return bool + /// + bool operator==(const Quaternion& inRhs) const noexcept + { + const auto comparitor = [](double value1, double value2) noexcept -> bool + { return utils::essentiallyEqual(value1, value2); }; + + return stl_algorithms::equal(components_.begin(), components_.end(), inRhs.components_.begin(), comparitor); + } + + //============================================================================ + // Method Description: + /// equality operator + /// + /// @param inRhs + /// @return bool + /// + bool operator!=(const Quaternion& inRhs) const noexcept + { + return !(*this == inRhs); + } + + //============================================================================ + // Method Description: + /// addition assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator+=(const Quaternion& inRhs) noexcept + { + stl_algorithms::transform(components_.begin(), + components_.end(), + inRhs.components_.begin(), + components_.begin(), + std::plus()); // NOLINT(modernize-use-transparent-functors) + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// addition operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator+(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) += inRhs; + } + + //============================================================================ + // Method Description: + /// subtraction assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator-=(const Quaternion& inRhs) noexcept + { + stl_algorithms::transform(components_.begin(), + components_.end(), + inRhs.components_.begin(), + components_.begin(), + std::minus()); // NOLINT(modernize-use-transparent-functors) + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// subtraction operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator-(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) -= inRhs; + } + + //============================================================================ + // Method Description: + /// negative operator + /// + /// @return Quaternion + /// + Quaternion operator-() const noexcept + { + return Quaternion(*this) *= -1.; + } + + //============================================================================ + // Method Description: + /// multiplication assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator*=(const Quaternion& inRhs) noexcept + { + double q0 = inRhs.s() * i(); + q0 += inRhs.i() * s(); + q0 -= inRhs.j() * k(); + q0 += inRhs.k() * j(); + + double q1 = inRhs.s() * j(); + q1 += inRhs.i() * k(); + q1 += inRhs.j() * s(); + q1 -= inRhs.k() * i(); + + double q2 = inRhs.s() * k(); + q2 -= inRhs.i() * j(); + q2 += inRhs.j() * i(); + q2 += inRhs.k() * s(); + + double q3 = inRhs.s() * s(); + q3 -= inRhs.i() * i(); + q3 -= inRhs.j() * j(); + q3 -= inRhs.k() * k(); + + components_[0] = q0; + components_[1] = q1; + components_[2] = q2; + components_[3] = q3; + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// multiplication operator, only useful for multiplying + /// by negative 1, all others will be renormalized back out + /// + /// @param inScalar + /// @return Quaternion + /// + Quaternion& operator*=(double inScalar) noexcept + { + stl_algorithms::for_each(components_.begin(), + components_.end(), + [inScalar](double& component) { component *= inScalar; }); + + normalize(); + + return *this; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator*(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) *= inRhs; + } + + //============================================================================ + // Method Description: + /// multiplication operator, only useful for multiplying + /// by negative 1, all others will be renormalized back out + /// + /// @param inScalar + /// @return Quaternion + /// + Quaternion operator*(double inScalar) const noexcept + { + return Quaternion(*this) *= inScalar; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inVec + /// @return NdArray + /// + NdArray operator*(const NdArray& inVec) const + { + if (inVec.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input vector must be a cartesion vector of length = 3."); + } + + const auto p = Quaternion(inVec[0], inVec[1], inVec[2], 0.); + const auto pPrime = *this * p * this->inverse(); + + NdArray rotatedVec = { pPrime.i(), pPrime.j(), pPrime.k() }; + rotatedVec *= norm(inVec).item(); + return rotatedVec; + } + + //============================================================================ + // Method Description: + /// multiplication operator + /// + /// @param inVec3 + /// @return Vec3 + /// + Vec3 operator*(const Vec3& inVec3) const + { + return *this * inVec3.toNdArray(); + } + + //============================================================================ + // Method Description: + /// division assignment operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion& operator/=(const Quaternion& inRhs) noexcept + { + return *this *= inRhs.conjugate(); + } + + //============================================================================ + // Method Description: + /// division operator + /// + /// @param inRhs + /// @return Quaternion + /// + Quaternion operator/(const Quaternion& inRhs) const noexcept + { + return Quaternion(*this) /= inRhs; + } + + //============================================================================ + // Method Description: + /// IO operator for the Quaternion class + /// + /// @param inOStream + /// @param inQuat + /// @return std::ostream& + /// + friend std::ostream& operator<<(std::ostream& inOStream, const Quaternion& inQuat) + { + inOStream << inQuat.str(); + return inOStream; + } + + private: + //====================================Attributes============================== + std::array components_{ { 0., 0., 0., 1. } }; + + //============================================================================ + // Method Description: + /// renormalizes the quaternion + /// + void normalize() noexcept + { + double sumOfSquares = 0.; + std::for_each(components_.begin(), + components_.end(), + [&sumOfSquares](double component) noexcept -> void + { sumOfSquares += utils::sqr(component); }); + + const double norm = std::sqrt(sumOfSquares); + stl_algorithms::for_each(components_.begin(), + components_.end(), + [norm](double& component) noexcept -> void { component /= norm; }); + } + + //============================================================================ + // Method Description: + /// Converts the euler roll, pitch, yaw angles to quaternion components + /// + /// @ param roll: the euler roll angle in radians + /// @ param pitch: the euler pitch angle in radians + /// @ param yaw: the euler yaw angle in radians + /// + void eulerToQuat(double roll, double pitch, double yaw) noexcept + { + const auto halfPhi = roll / 2.; + const auto halfTheta = pitch / 2.; + const auto halfPsi = yaw / 2.; + + const auto sinHalfPhi = std::sin(halfPhi); + const auto cosHalfPhi = std::cos(halfPhi); + + const auto sinHalfTheta = std::sin(halfTheta); + const auto cosHalfTheta = std::cos(halfTheta); + + const auto sinHalfPsi = std::sin(halfPsi); + const auto cosHalfPsi = std::cos(halfPsi); + + components_[0] = sinHalfPhi * cosHalfTheta * cosHalfPsi; + components_[0] -= cosHalfPhi * sinHalfTheta * sinHalfPsi; + + components_[1] = cosHalfPhi * sinHalfTheta * cosHalfPsi; + components_[1] += sinHalfPhi * cosHalfTheta * sinHalfPsi; + + components_[2] = cosHalfPhi * cosHalfTheta * sinHalfPsi; + components_[2] -= sinHalfPhi * sinHalfTheta * cosHalfPsi; + + components_[3] = cosHalfPhi * cosHalfTheta * cosHalfPsi; + components_[3] += sinHalfPhi * sinHalfTheta * sinHalfPsi; + } + + //============================================================================ + // Method Description: + /// Converts the direction cosine matrix to quaternion components + /// + /// @ param dcm: the direction cosine matrix + /// + void dcmToQuat(const NdArray& dcm) + { + const Shape inShape = dcm.shape(); + if (!(inShape.rows == 3 && inShape.cols == 3)) + { + THROW_INVALID_ARGUMENT_ERROR("input direction cosine matrix must have shape = (3,3)."); + } + + NdArray checks(1, 4); + checks[0] = 1 + dcm(0, 0) + dcm(1, 1) + dcm(2, 2); + checks[1] = 1 + dcm(0, 0) - dcm(1, 1) - dcm(2, 2); + checks[2] = 1 - dcm(0, 0) + dcm(1, 1) - dcm(2, 2); + checks[3] = 1 - dcm(0, 0) - dcm(1, 1) + dcm(2, 2); + + const uint32 maxIdx = argmax(checks).item(); + + switch (maxIdx) + { + case 0: + { + components_[3] = 0.5 * std::sqrt(1 + dcm(0, 0) + dcm(1, 1) + dcm(2, 2)); + components_[0] = (dcm(2, 1) - dcm(1, 2)) / (4 * components_[3]); + components_[1] = (dcm(0, 2) - dcm(2, 0)) / (4 * components_[3]); + components_[2] = (dcm(1, 0) - dcm(0, 1)) / (4 * components_[3]); + + break; + } + case 1: + { + components_[0] = 0.5 * std::sqrt(1 + dcm(0, 0) - dcm(1, 1) - dcm(2, 2)); + components_[1] = (dcm(1, 0) + dcm(0, 1)) / (4 * components_[0]); + components_[2] = (dcm(2, 0) + dcm(0, 2)) / (4 * components_[0]); + components_[3] = (dcm(2, 1) - dcm(1, 2)) / (4 * components_[0]); + + break; + } + case 2: + { + components_[1] = 0.5 * std::sqrt(1 - dcm(0, 0) + dcm(1, 1) - dcm(2, 2)); + components_[0] = (dcm(1, 0) + dcm(0, 1)) / (4 * components_[1]); + components_[2] = (dcm(2, 1) + dcm(1, 2)) / (4 * components_[1]); + components_[3] = (dcm(0, 2) - dcm(2, 0)) / (4 * components_[1]); + + break; + } + case 3: + { + components_[2] = 0.5 * std::sqrt(1 - dcm(0, 0) - dcm(1, 1) + dcm(2, 2)); + components_[0] = (dcm(2, 0) + dcm(0, 2)) / (4 * components_[2]); + components_[1] = (dcm(2, 1) + dcm(1, 2)) / (4 * components_[2]); + components_[3] = (dcm(1, 0) - dcm(0, 1)) / (4 * components_[2]); + + break; + } + } + } + }; +} // namespace nc::rotations diff --git a/runexamples/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp b/runexamples/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp new file mode 100644 index 0000000..b6ab6dd --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Rotations/rodriguesRotation.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Performs Rodriques' rotation formula +/// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula +/// +#pragma once + +#include + +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Vector/Vec3.hpp" + +namespace nc::rotations +{ + //============================================================================ + // Method Description: + /// Performs Rodriques' rotation formula + /// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + /// + /// @param k: the axis to rotate around + /// @param theta: the angle in radians to rotate + /// @param v: the vector to rotate + /// + /// @return Vec3 + /// + inline Vec3 rodriguesRotation(const Vec3& k, double theta, const Vec3& v) noexcept + { + const auto kUnit = k.normalize(); + + const auto vCosTheta = v * std::cos(theta); + + auto kCrossV = kUnit.cross(v); + kCrossV *= std::sin(theta); + + const auto kDotV = kUnit.dot(v); + auto kkDotV = kUnit * kDotV; + kkDotV *= 1 - std::cos(theta); + + auto vec = vCosTheta + kCrossV; + vec += kkDotV; + + return vec; + } + + //============================================================================ + // Method Description: + /// Performs Rodriques' rotation formula + /// https://en.wikipedia.org/wiki/Rodrigues%27_rotation_formula + /// + /// @param k: the axis to rotate around + /// @param theta: the angle in radians to rotate + /// @param v: the vector to rotate + /// + /// @return NdArray + /// + template + NdArray rodriguesRotation(const NdArray& k, double theta, const NdArray& v) + { + return rodriguesRotation(Vec3(k), theta, Vec3(v)).toNdArray(); + } +} // namespace nc::rotations \ No newline at end of file diff --git a/runexamples/cpp/include/NumCpp/Rotations/wahbasProblem.hpp b/runexamples/cpp/include/NumCpp/Rotations/wahbasProblem.hpp new file mode 100644 index 0000000..4fcf74b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Rotations/wahbasProblem.hpp @@ -0,0 +1,130 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// In applied mathematics, Wahba's problem, first posed by Grace Wahba in 1965, seeks to +/// find a rotation matrix (special orthogonal matrix) between two coordinate systems from +/// a set of (weighted) vector observations. Solutions to Wahba's problem are often used in +/// satellite attitude determination utilising sensors such as magnetometers and multi-antenna +/// GPS receivers +/// https://en.wikipedia.org/wiki/Wahba%27s_problem +/// +#pragma once + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Functions/dot.hpp" +#include "NumCpp/Functions/eye.hpp" +#include "NumCpp/Functions/ones.hpp" +#include "NumCpp/Functions/zeros.hpp" +#include "NumCpp/Linalg/det.hpp" +#include "NumCpp/Linalg/svd.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::rotations +{ + //============================================================================ + // Method Description: + /// Finds a rotation matrix (special orthogonal matrix) between two coordinate + /// systems from a set of (weighted) vector observations. Solutions to Wahba's + /// problem are often used in satellite attitude determination utilising sensors + /// such as magnetometers and multi-antenna GPS receivers + /// https://en.wikipedia.org/wiki/Wahba%27s_problem + /// + /// @param wk: k-th 3-vector measurement in the reference frame (n x 3 matrix) + /// @param vk: corresponding k-th 3-vector measurement in the body frame (n x 3 matrix) + /// @param ak: set of weights for each observation (1 x n or n x 1 matrix) + /// + /// @return NdArray rotation matrix + /// + template + NdArray wahbasProblem(const NdArray& wk, const NdArray& vk, const NdArray& ak) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + const auto wkShape = wk.shape(); + if (wkShape.cols != 3) + { + THROW_INVALID_ARGUMENT_ERROR("wk matrix must be of shape [n, 3]"); + } + + const auto vkShape = vk.shape(); + if (vkShape.cols != 3) + { + THROW_INVALID_ARGUMENT_ERROR("vk matrix must be of shape [n, 3]"); + } + + if (wkShape.rows != vkShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("wk and vk matrices must have the same number of rows"); + } + + if (ak.size() != wkShape.rows) + { + THROW_INVALID_ARGUMENT_ERROR("ak matrix must have the same number of elements as wk and vk rows"); + } + + auto b = zeros(3, 3); + const auto cSlice = wk.cSlice(); + for (uint32 row = 0; row < wkShape.rows; ++row) + { + const auto wkVec = wk(row, cSlice); + const auto vkVec = vk(row, cSlice); + b += ak[row] * dot(wkVec.transpose(), vkVec); + } + + NdArray u; + NdArray s; + NdArray vt; + + linalg::svd(b, u, s, vt); + + auto m = eye(3, 3); + m(0, 0) = 1.; + m(1, 1) = 1.; + m(2, 2) = linalg::det(u) * linalg::det(vt.transpose()); + + return dot(u, dot(m, vt)); + } + + //============================================================================ + // Method Description: + /// Finds a rotation matrix (special orthogonal matrix) between two coordinate + /// systems from a set of (weighted) vector observations. Solutions to Wahba's + /// problem are often used in satellite attitude determination utilising sensors + /// such as magnetometers and multi-antenna GPS receivers + /// https://en.wikipedia.org/wiki/Wahba%27s_problem + /// + /// @param wk: k-th 3-vector measurement in the reference frame + /// @param vk: corresponding k-th 3-vector measurement in the body frame + /// + /// @return NdArray rotation matrix + /// + template + NdArray wahbasProblem(const NdArray& wk, const NdArray& vk) + { + const auto ak = ones({ 1, wk.shape().rows }); + return wahbasProblem(wk, vk, ak); + } +} // namespace nc::rotations diff --git a/runexamples/cpp/include/NumCpp/Special.hpp b/runexamples/cpp/include/NumCpp/Special.hpp new file mode 100644 index 0000000..c668411 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special.hpp @@ -0,0 +1,72 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Special/airy_ai.hpp" +#include "NumCpp/Special/airy_ai_prime.hpp" +#include "NumCpp/Special/airy_bi.hpp" +#include "NumCpp/Special/airy_bi_prime.hpp" +#include "NumCpp/Special/bernoulli.hpp" +#include "NumCpp/Special/bessel_in.hpp" +#include "NumCpp/Special/bessel_in_prime.hpp" +#include "NumCpp/Special/bessel_jn.hpp" +#include "NumCpp/Special/bessel_jn_prime.hpp" +#include "NumCpp/Special/bessel_kn.hpp" +#include "NumCpp/Special/bessel_kn_prime.hpp" +#include "NumCpp/Special/bessel_yn.hpp" +#include "NumCpp/Special/bessel_yn_prime.hpp" +#include "NumCpp/Special/beta.hpp" +#include "NumCpp/Special/cnr.hpp" +#include "NumCpp/Special/comp_ellint_1.hpp" +#include "NumCpp/Special/comp_ellint_2.hpp" +#include "NumCpp/Special/comp_ellint_3.hpp" +#include "NumCpp/Special/cyclic_hankel_1.hpp" +#include "NumCpp/Special/cyclic_hankel_2.hpp" +#include "NumCpp/Special/digamma.hpp" +#include "NumCpp/Special/ellint_1.hpp" +#include "NumCpp/Special/ellint_2.hpp" +#include "NumCpp/Special/ellint_3.hpp" +#include "NumCpp/Special/erf.hpp" +#include "NumCpp/Special/erf_inv.hpp" +#include "NumCpp/Special/erfc.hpp" +#include "NumCpp/Special/erfc_inv.hpp" +#include "NumCpp/Special/expint.hpp" +#include "NumCpp/Special/factorial.hpp" +#include "NumCpp/Special/gamma.hpp" +#include "NumCpp/Special/gamma1pm1.hpp" +#include "NumCpp/Special/log_gamma.hpp" +#include "NumCpp/Special/pnr.hpp" +#include "NumCpp/Special/polygamma.hpp" +#include "NumCpp/Special/prime.hpp" +#include "NumCpp/Special/riemann_zeta.hpp" +#include "NumCpp/Special/softmax.hpp" +#include "NumCpp/Special/spherical_bessel_jn.hpp" +#include "NumCpp/Special/spherical_bessel_yn.hpp" +#include "NumCpp/Special/spherical_hankel_1.hpp" +#include "NumCpp/Special/spherical_hankel_2.hpp" +#include "NumCpp/Special/trigamma.hpp" diff --git a/runexamples/cpp/include/NumCpp/Special/airy_ai.hpp b/runexamples/cpp/include/NumCpp/Special/airy_ai.hpp new file mode 100644 index 0000000..9c4be23 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/airy_ai.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_ai(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_ai(inValue); + } + + //============================================================================ + // Method Description: + /// The first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_ai(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_ai(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/airy_ai_prime.hpp b/runexamples/cpp/include/NumCpp/Special/airy_ai_prime.hpp new file mode 100644 index 0000000..95bb362 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/airy_ai_prime.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The derivative of the first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_ai_prime(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_ai_prime(inValue); + } + + //============================================================================ + // Method Description: + /// The derivative of the first linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_ai_prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_ai_prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/airy_bi.hpp b/runexamples/cpp/include/NumCpp/Special/airy_bi.hpp new file mode 100644 index 0000000..6efa8f9 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/airy_bi.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_bi(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_bi(inValue); + } + + //============================================================================ + // Method Description: + /// The second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_bi(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_bi(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/airy_bi_prime.hpp b/runexamples/cpp/include/NumCpp/Special/airy_bi_prime.hpp new file mode 100644 index 0000000..0787b78 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/airy_bi_prime.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/airy.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The derivative of the second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto airy_bi_prime(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::airy_bi_prime(inValue); + } + + //============================================================================ + // Method Description: + /// The derivative of the second linearly independent solution to the differential equation y'' - yz = 0. + /// http://mathworld.wolfram.com/AiryFunctions.html + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto airy_bi_prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return airy_bi_prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/bernoulli.hpp b/runexamples/cpp/include/NumCpp/Special/bernoulli.hpp new file mode 100644 index 0000000..9abb037 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bernoulli.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/bernoulli.hpp" + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Both return the nth Bernoulli number B2n. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n + /// @return double + /// + inline double bernoilli(uint32 n) + { + if (n == 1) + { + return 0.5; + } + if (n % 2 != 0) + { + return 0.; + } + + return boost::math::bernoulli_b2n(n / 2); + } + + //============================================================================ + // Method Description: + /// Both return the nth Bernoulli number B2n. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray bernoilli(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> double { return bernoilli(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_in.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_in.hpp new file mode 100644 index 0000000..b75b356 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_in.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_in(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_i(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_i(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_in(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_in(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_in_prime.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_in_prime.hpp new file mode 100644 index 0000000..eb7a99c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_in_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_in_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_i_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_in_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_in_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_jn.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_jn.hpp new file mode 100644 index 0000000..f23171f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_jn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_jn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_j(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_j(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_jn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_jn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_jn_prime.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_jn_prime.hpp new file mode 100644 index 0000000..b4db65f --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_jn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_jn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_j_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_jn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_jn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_kn.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_kn.hpp new file mode 100644 index 0000000..8b81fb7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_kn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_kn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_bessel_k(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_bessel_k(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_kn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_kn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_kn_prime.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_kn_prime.hpp new file mode 100644 index 0000000..248a980 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_kn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel_prime.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_kn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_bessel_k_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Modified Cylindrical Bessel function of the second kind + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_kn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_kn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_yn.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_yn.hpp new file mode 100644 index 0000000..e8ce29c --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_yn.hpp @@ -0,0 +1,94 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_yn(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::cyl_neumann(static_cast(inV), static_cast(inX)); +#else + return boost::math::cyl_neumann(static_cast(inV), static_cast(inX)); +#endif + } + + //============================================================================ + // Method Description: + /// Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_yn(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_yn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/bessel_yn_prime.hpp b/runexamples/cpp/include/NumCpp/Special/bessel_yn_prime.hpp new file mode 100644 index 0000000..41fe1f6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/bessel_yn_prime.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/bessel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto bessel_yn_prime(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_neumann_prime(inV, inX); + } + + //============================================================================ + // Method Description: + /// Derivcative of the Cylindrical Bessel function of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto bessel_yn_prime(dtype1 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype2 inX) -> auto{ return bessel_yn_prime(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/beta.hpp b/runexamples/cpp/include/NumCpp/Special/beta.hpp new file mode 100644 index 0000000..f9df749 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/beta.hpp @@ -0,0 +1,95 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/beta.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The beta function. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param a + /// @param b + /// @return calculated-result-type + /// + template + auto beta(dtype1 a, dtype2 b) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::beta(a, b); +#else + return boost::math::beta(a, b); +#endif + } + + //============================================================================ + // Method Description: + /// The beta function. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayA + /// @param inArrayB + /// @return NdArray + /// + template + auto beta(const NdArray& inArrayA, const NdArray& inArrayB) + { + NdArray returnArray(inArrayB.shape()); + + stl_algorithms::transform( + inArrayA.cbegin(), + inArrayA.cend(), + inArrayB.cbegin(), + returnArray.begin(), + [](dtype1 a, dtype2 b) -> auto{ return beta(a, b); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/cnr.hpp b/runexamples/cpp/include/NumCpp/Special/cnr.hpp new file mode 100644 index 0000000..5a1f7e6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/cnr.hpp @@ -0,0 +1,52 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/factorial.hpp" +#include "NumCpp/Special/pnr.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the number of combinations of n choose r. C(n, r) + /// + /// @param n: the total number of items + /// @param r: the number of items taken + /// @return double + /// + inline double cnr(uint32 n, uint32 r) + { + return pnr(n, r) / factorial(r); + } +} // namespace nc::special diff --git a/runexamples/cpp/include/NumCpp/Special/comp_ellint_1.hpp b/runexamples/cpp/include/NumCpp/Special/comp_ellint_1.hpp new file mode 100644 index 0000000..8b9802a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/comp_ellint_1.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_1.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the first kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @return calculated-result-type + /// + template + auto comp_ellint_1(dtype inK) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_1(inK); +#else + return boost::math::ellint_1(inK); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the first kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @return NdArray + /// + template + auto comp_ellint_1(const NdArray& inArrayK) + { + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + returnArray.begin(), + [](dtype inK) -> auto{ return comp_ellint_1(inK); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/comp_ellint_2.hpp b/runexamples/cpp/include/NumCpp/Special/comp_ellint_2.hpp new file mode 100644 index 0000000..cd28df5 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/comp_ellint_2.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_2.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the second kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @return calculated-result-type + /// + template + auto comp_ellint_2(dtype inK) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_2(inK); +#else + return boost::math::ellint_2(inK); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the second kind of k. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @return NdArray + /// + template + auto comp_ellint_2(const NdArray& inArrayK) + { + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + returnArray.begin(), + [](dtype inK) -> auto{ return comp_ellint_2(inK); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/comp_ellint_3.hpp b/runexamples/cpp/include/NumCpp/Special/comp_ellint_3.hpp new file mode 100644 index 0000000..8b649ec --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/comp_ellint_3.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_3.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the third kind of k and v. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inV: elliptic characteristic + /// @return calculated-result-type + /// + template + auto comp_ellint_3(dtype1 inK, dtype2 inV) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::comp_ellint_3(inK, inV); +#else + return boost::math::ellint_3(inK, inV); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the complete elliptic integral of the third kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: the order of the bessel function + /// @param inArrayV: elliptic characteristic + /// @return NdArray + /// + template + auto comp_ellint_3(const NdArray& inArrayK, const NdArray& inArrayV) + { + if (inArrayK.size() != inArrayV.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayk and inArrayV must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayV.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inV) -> auto{ return comp_ellint_3(inK, inV); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp b/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp new file mode 100644 index 0000000..03c4a3a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_1.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return std::complex + /// + template + auto cyclic_hankel_1(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_hankel_1(inV, inX); + } + + //============================================================================ + // Method Description: + /// Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input array + /// @return NdArray + /// + template + auto cyclic_hankel_1(dtype1 inV, const NdArray& inX) + { + NdArray returnArray(inX.shape()); + + stl_algorithms::transform( + inX.cbegin(), + inX.cend(), + returnArray.begin(), + [inV](dtype2 x) -> auto{ return cyclic_hankel_1(inV, x); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp b/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp new file mode 100644 index 0000000..5b39c59 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/cyclic_hankel_2.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return std::complex<> + /// + template + auto cyclic_hankel_2(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::cyl_hankel_2(inV, inX); + } + + //============================================================================ + // Method Description: + /// Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input array + /// @return NdArray + /// + template + auto cyclic_hankel_2(dtype1 inV, const NdArray& inX) + { + NdArray returnArray(inX.shape()); + + stl_algorithms::transform( + inX.cbegin(), + inX.cend(), + returnArray.begin(), + [inV](dtype2 x) -> auto{ return cyclic_hankel_2(inV, x); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/digamma.hpp b/runexamples/cpp/include/NumCpp/Special/digamma.hpp new file mode 100644 index 0000000..ceace13 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/digamma.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/digamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the digamma or psi function of inValue. Digamma is defined as the + /// logarithmic derivative of the gamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto digamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::digamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the digamma or psi function of values in inArray. Digamma is defined as the + /// logarithmic derivative of the gamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto digamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return digamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/ellint_1.hpp b/runexamples/cpp/include/NumCpp/Special/ellint_1.hpp new file mode 100644 index 0000000..ca26b59 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/ellint_1.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_1.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the first kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_1(dtype1 inK, dtype2 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_1(inK, inP); +#else + return boost::math::ellint_1(inK, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the first kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_1(const NdArray& inArrayK, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayP.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inP) -> auto{ return ellint_1(inK, inP); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/ellint_2.hpp b/runexamples/cpp/include/NumCpp/Special/ellint_2.hpp new file mode 100644 index 0000000..7c1a8c2 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/ellint_2.hpp @@ -0,0 +1,101 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_2.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_2(dtype1 inK, dtype2 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_2(inK, inP); +#else + return boost::math::ellint_2(inK, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: elliptic modulus or eccentricity + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_2(const NdArray& inArrayK, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + stl_algorithms::transform( + inArrayK.cbegin(), + inArrayK.cend(), + inArrayP.cbegin(), + returnArray.begin(), + [](dtype1 inK, dtype2 inP) -> auto{ return ellint_2(inK, inP); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/ellint_3.hpp b/runexamples/cpp/include/NumCpp/Special/ellint_3.hpp new file mode 100644 index 0000000..7958173 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/ellint_3.hpp @@ -0,0 +1,102 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/ellint_3.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k, v, and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inK: elliptic modulus or eccentricity + /// @param inV: elliptic characteristic + /// @param inP: Jacobi amplitude (measured in radians) + /// @return calculated-result-type + /// + template + auto ellint_3(dtype1 inK, dtype2 inV, dtype3 inP) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + STATIC_ASSERT_ARITHMETIC(dtype3); + +#ifdef __cpp_lib_math_special_functions + return std::ellint_3(inK, inV, inP); +#else + return boost::math::ellint_3(inK, inV, inP); +#endif + } + + //============================================================================ + // Method Description: + /// Computes the incomplete elliptic integral of the second kind of k, v, and p. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayK: the order of the bessel function + /// @param inArrayV: elliptic characteristic + /// @param inArrayP: Jacobi amplitude (measured in radians) + /// @return NdArray + /// + template + auto ellint_3(const NdArray& inArrayK, const NdArray& inArrayV, const NdArray& inArrayP) + { + if (inArrayK.size() != inArrayV.size() || inArrayK.size() != inArrayP.size()) + { + THROW_INVALID_ARGUMENT_ERROR("Shapes of inArrayK, inArrayV, and inArrayP must match."); + } + + NdArray returnArray(inArrayK.shape()); + + for (uint32 i = 0; i < inArrayK.size(); ++i) + { + returnArray[i] = ellint_3(inArrayK[i], inArrayV[i], inArrayP[i]); + } + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/erf.hpp b/runexamples/cpp/include/NumCpp/Special/erf.hpp new file mode 100644 index 0000000..6094169 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/erf.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Calculate the error function of all elements in the input array. + /// Integral (from [-x, x]) of np.exp(np.power(-t, 2)) dt, multiplied by 1/np.pi. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erf(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erf(inValue); + } + + //============================================================================ + // Method Description: + /// Calculate the error function of all elements in the input array. + /// Integral (from [-x, x]) of np.exp(np.power(-t, 2)) dt, multiplied by 1/np.pi. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erf(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erf(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/erf_inv.hpp b/runexamples/cpp/include/NumCpp/Special/erf_inv.hpp new file mode 100644 index 0000000..8ca9f88 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/erf_inv.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the inverse error function of z, that is a value x such that: + /// z = erf(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erf_inv(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erf_inv(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the inverse error function of z, that is a value x such that: + /// z = erf(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erf_inv(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erf_inv(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/erfc.hpp b/runexamples/cpp/include/NumCpp/Special/erfc.hpp new file mode 100644 index 0000000..9d78d57 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/erfc.hpp @@ -0,0 +1,80 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the complement of the error function of inValue. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erfc(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erfc(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the element-wise complement of the error + /// function of inValue. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erfc(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erfc(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/erfc_inv.hpp b/runexamples/cpp/include/NumCpp/Special/erfc_inv.hpp new file mode 100644 index 0000000..2137419 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/erfc_inv.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/erf.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the inverse complentary error function of z, that is a value x such that: + /// z = erfc(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto erfc_inv(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::erfc_inv(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the inverse complementary error function of z, that is a value x such that: + /// z = erfc(x). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto erfc_inv(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return erfc_inv(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/expint.hpp b/runexamples/cpp/include/NumCpp/Special/expint.hpp new file mode 100644 index 0000000..8a69e33 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/expint.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/expint.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Exponential integral Ei. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inX: value + /// @return calculated-result-type + /// + template + auto expint(dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::expint(inX); +#else + return boost::math::expint(inX); +#endif + } + + //============================================================================ + // Method Description: + /// Exponential integral Ei. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArrayX: value + /// @return NdArray + /// + template + auto expint(const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [](dtype inX) -> auto{ return expint(inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/factorial.hpp b/runexamples/cpp/include/NumCpp/Special/factorial.hpp new file mode 100644 index 0000000..70c1b8b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/factorial.hpp @@ -0,0 +1,87 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/math/special_functions/factorials.hpp" +#endif + +#include + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the factorial of the input value + /// + /// @param inValue + /// @return double + /// + inline double factorial(uint32 inValue) + { +#ifndef NUMCPP_NO_USE_BOOST + if (inValue <= boost::math::max_factorial::value) + { + return boost::math::factorial(inValue); + } + + return std::numeric_limits::infinity(); +#else + double result = 1.; + for (uint32 i = 2; i <= inValue; ++i) + { + result *= static_cast(i); + } + + return result; +#endif + } + + //============================================================================ + // Method Description: + /// Returns the factorial of the input value + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray factorial(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> double { return factorial(inValue); }); + + return returnArray; + } +} // namespace nc::special diff --git a/runexamples/cpp/include/NumCpp/Special/gamma.hpp b/runexamples/cpp/include/NumCpp/Special/gamma.hpp new file mode 100644 index 0000000..ef9fc96 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/gamma.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the "true gamma" of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto gamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::tgamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the "true gamma" of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto gamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return gamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/gamma1pm1.hpp b/runexamples/cpp/include/NumCpp/Special/gamma1pm1.hpp new file mode 100644 index 0000000..7b4748b --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/gamma1pm1.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the true gamma(dz + 1) - 1 of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto gamma1pm1(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::tgamma1pm1(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the true gamma(dz + 1) - 1 of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto gamma1pm1(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return gamma1pm1(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/log_gamma.hpp b/runexamples/cpp/include/NumCpp/Special/log_gamma.hpp new file mode 100644 index 0000000..d9830e3 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/log_gamma.hpp @@ -0,0 +1,79 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/gamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns natural log of the true gamma of value z. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto log_gamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::lgamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns natural log of the true gamma of values in array. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto log_gamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return log_gamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/pnr.hpp b/runexamples/cpp/include/NumCpp/Special/pnr.hpp new file mode 100644 index 0000000..2ee697e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/pnr.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Special/factorial.hpp" + +#ifndef NUMCPP_NO_USE_BOOST +#include "boost/math/special_functions/factorials.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the number of permutaions of n choose r. P(n, r) + /// + /// @param n: the total number of items + /// @param r: the number of items taken + /// @return double + /// + inline double pnr(uint32 n, uint32 r) + { + if (r > n) + { + return 0.; + } + else if (r == n) + { + return factorial(n); + } + + double combinations = 1.; + +#ifndef NUMCPP_NO_USE_BOOST + if (n <= boost::math::max_factorial::value) + { + const double nFactorial = factorial(n); + const double nMinusRFactoral = factorial(n - r); + + combinations = nFactorial / nMinusRFactoral; + } + else + { +#endif + const uint32 lower = n - r + 1; + combinations = static_cast(lower); + for (uint32 i = lower + 1; i <= n; ++i) + { + combinations *= static_cast(i); + } +#ifndef NUMCPP_NO_USE_BOOST + } +#endif + + return combinations; + } +} // namespace nc::special diff --git a/runexamples/cpp/include/NumCpp/Special/polygamma.hpp b/runexamples/cpp/include/NumCpp/Special/polygamma.hpp new file mode 100644 index 0000000..4d244aa --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/polygamma.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/polygamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the polygamma function of inValue. Polygamma is defined as the + /// n'th derivative of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth derivative + /// @param inValue + /// @return calculated-result-type + /// + template + auto polygamma(uint32 n, dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::polygamma(n, inValue); + } + + //============================================================================ + // Method Description: + /// Returns the polygamma function of the values in inArray. Polygamma is defined as the + /// n'th derivative of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth derivative + /// @param inArray + /// @return NdArray + /// + template + auto polygamma(uint32 n, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [n](dtype inValue) -> auto{ return polygamma(n, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/prime.hpp b/runexamples/cpp/include/NumCpp/Special/prime.hpp new file mode 100644 index 0000000..269a8ce --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/prime.hpp @@ -0,0 +1,85 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include + +#include "boost/math/special_functions/prime.hpp" + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The function prime provides fast table lookup to the first 10000 prime numbers + /// (starting from 2 as the zeroth prime: as 1 isn't terribly useful in practice). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param n: the nth prime number to return + /// @return uint32 + /// + inline uint32 prime(uint32 n) + { + if (n > boost::math::max_prime) + { + THROW_INVALID_ARGUMENT_ERROR("input n must be less than or equal to " + + std::to_string(boost::math::max_prime)); + } + + return boost::math::prime(n); + } + + //============================================================================ + // Method Description: + /// The function prime provides fast table lookup to the first 10000 prime numbers + /// (starting from 2 as the zeroth prime: as 1 isn't terribly useful in practice). + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + inline NdArray prime(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform(inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](uint32 inValue) -> uint32 { return prime(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/riemann_zeta.hpp b/runexamples/cpp/include/NumCpp/Special/riemann_zeta.hpp new file mode 100644 index 0000000..40cf19d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/riemann_zeta.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/zeta.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The Riemann Zeta function + /// https://en.wikipedia.org/wiki/Riemann_zeta_function + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto riemann_zeta(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::riemann_zeta(inValue); +#else + return boost::math::zeta(inValue); +#endif + } + + //============================================================================ + // Method Description: + /// The Riemann Zeta function + /// https://en.wikipedia.org/wiki/Riemann_zeta_function + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inArray + /// @return NdArray + /// + template + auto riemann_zeta(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return riemann_zeta(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/softmax.hpp b/runexamples/cpp/include/NumCpp/Special/softmax.hpp new file mode 100644 index 0000000..3f14896 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/softmax.hpp @@ -0,0 +1,99 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/Core/Types.hpp" +#include "NumCpp/Functions/exp.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// The softmax function transforms each element of a collection by computing + /// the exponential of each element divided by the sum of the exponentials of all + /// the elements. That is, if x is a one-dimensional numpy array: + /// softmax(x) = np.exp(x)/sum(np.exp(x)) + /// + /// @param inArray + /// @param inAxis (Optional, default NONE) + /// @return NdArray + /// + template + NdArray softmax(const NdArray& inArray, Axis inAxis = Axis::NONE) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + switch (inAxis) + { + case Axis::NONE: + { + auto returnArray = exp(inArray).template astype(); + returnArray /= static_cast(returnArray.sum().item()); + return returnArray; + } + case Axis::COL: + { + auto returnArray = exp(inArray).template astype(); + auto expSums = returnArray.sum(inAxis); + + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + const auto rowExpSum = static_cast(expSums[row]); + stl_algorithms::for_each(returnArray.begin(row), + returnArray.end(row), + [rowExpSum](double& value) { value /= rowExpSum; }); + } + + return returnArray; + } + case Axis::ROW: + { + auto returnArray = exp(inArray.transpose()).template astype(); + auto expSums = returnArray.sum(Axis::COL); + + for (uint32 row = 0; row < returnArray.shape().rows; ++row) + { + const auto rowExpSum = static_cast(expSums[row]); + stl_algorithms::for_each(returnArray.begin(row), + returnArray.end(row), + [rowExpSum](double& value) { value /= rowExpSum; }); + } + + return returnArray.transpose(); + } + default: + { + THROW_INVALID_ARGUMENT_ERROR("Unimplemented axis type."); + return {}; // get rid of compiler warning + } + } + } +} // namespace nc::special diff --git a/runexamples/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp b/runexamples/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp new file mode 100644 index 0000000..d0e07cb --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/spherical_bessel_jn.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_bessel_jn(uint32 inV, dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::sph_bessel(inV, inX); +#else + return boost::math::sph_bessel(inV, inX); +#endif + } + + //============================================================================ + // Method Description: + /// Spherical Bessel function of the first kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto spherical_bessel_jn(uint32 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype inX) -> auto{ return spherical_bessel_jn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp b/runexamples/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp new file mode 100644 index 0000000..50ffb26 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/spherical_bessel_yn.hpp @@ -0,0 +1,91 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#include + +#if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +#ifndef __cpp_lib_math_special_functions +#include "boost/math/special_functions/bessel.hpp" +#endif + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_bessel_yn(uint32 inV, dtype inX) + { + STATIC_ASSERT_ARITHMETIC(dtype); + +#ifdef __cpp_lib_math_special_functions + return std::sph_neumann(inV, inX); +#else + return boost::math::sph_neumann(inV, inX); +#endif + } + + //============================================================================ + // Method Description: + /// Spherical Bessel function of the second kind. + /// NOTE: Use of this function requires either using the Boost + /// includes or a C++17 compliant compiler. + /// + /// @param inV: the order of the bessel function + /// @param inArrayX: the input values + /// @return NdArray + /// + template + auto spherical_bessel_yn(uint32 inV, const NdArray& inArrayX) + { + NdArray returnArray(inArrayX.shape()); + + stl_algorithms::transform( + inArrayX.cbegin(), + inArrayX.cend(), + returnArray.begin(), + [inV](dtype inX) -> auto{ return spherical_bessel_yn(inV, inX); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #if defined(__cpp_lib_math_special_functions) || !defined(NUMCPP_NO_USE_BOOST) diff --git a/runexamples/cpp/include/NumCpp/Special/spherical_hankel_1.hpp b/runexamples/cpp/include/NumCpp/Special/spherical_hankel_1.hpp new file mode 100644 index 0000000..33d9293 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/spherical_hankel_1.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return calculated-result-type + /// + template + auto spherical_hankel_1(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::sph_hankel_1(inV, inX); + } + + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the first kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArray: the input values + /// @return NdArray + /// + template + auto spherical_hankel_1(dtype1 inV, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inV](dtype2 inValue) -> auto{ return spherical_hankel_1(inV, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/spherical_hankel_2.hpp b/runexamples/cpp/include/NumCpp/Special/spherical_hankel_2.hpp new file mode 100644 index 0000000..264d5ab --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/spherical_hankel_2.hpp @@ -0,0 +1,84 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include +#include + +#include "boost/math/special_functions/hankel.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inX: the input value + /// @return double + /// + template + std::complex spherical_hankel_2(dtype1 inV, dtype2 inX) + { + STATIC_ASSERT_ARITHMETIC(dtype1); + STATIC_ASSERT_ARITHMETIC(dtype2); + + return boost::math::sph_hankel_2(inV, inX); + } + + //============================================================================ + // Method Description: + /// Spherical Hankel funcion of the second kind. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inV: the order of the bessel function + /// @param inArray: the input value + /// @return NdArray + /// + template + auto spherical_hankel_2(dtype1 inV, const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [inV](dtype2 inValue) -> auto{ return spherical_hankel_2(inV, inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Special/trigamma.hpp b/runexamples/cpp/include/NumCpp/Special/trigamma.hpp new file mode 100644 index 0000000..f0a1636 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Special/trigamma.hpp @@ -0,0 +1,81 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Special Functions +/// +#pragma once + +#ifndef NUMCPP_NO_USE_BOOST + +#include "boost/math/special_functions/trigamma.hpp" + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/StlAlgorithms.hpp" +#include "NumCpp/NdArray.hpp" + +namespace nc::special +{ + //============================================================================ + // Method Description: + /// Returns the trigamma function of x. Trigamma is defined as the derivative + /// of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inValue + /// @return calculated-result-type + /// + template + auto trigamma(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return boost::math::trigamma(inValue); + } + + //============================================================================ + // Method Description: + /// Returns the trigamma function of x. Trigamma is defined as the derivative + /// of the digamma function. + /// NOTE: Use of this function requires using the Boost includes. + /// + /// @param inArray + /// @return NdArray + /// + template + auto trigamma(const NdArray& inArray) + { + NdArray returnArray(inArray.shape()); + + stl_algorithms::transform( + inArray.cbegin(), + inArray.cend(), + returnArray.begin(), + [](dtype inValue) -> auto{ return trigamma(inValue); }); + + return returnArray; + } +} // namespace nc::special + +#endif // #ifndef NUMCPP_NO_USE_BOOST diff --git a/runexamples/cpp/include/NumCpp/Utils.hpp b/runexamples/cpp/include/NumCpp/Utils.hpp new file mode 100644 index 0000000..d488069 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils.hpp @@ -0,0 +1,40 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Usefull utility type functions +/// +#pragma once + +#include "NumCpp/Utils/cube.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/gaussian.hpp" +#include "NumCpp/Utils/gaussian1d.hpp" +#include "NumCpp/Utils/interp.hpp" +#include "NumCpp/Utils/num2str.hpp" +#include "NumCpp/Utils/power.hpp" +#include "NumCpp/Utils/powerf.hpp" +#include "NumCpp/Utils/sqr.hpp" +#include "NumCpp/Utils/timeit.hpp" +#include "NumCpp/Utils/value2str.hpp" diff --git a/runexamples/cpp/include/NumCpp/Utils/cube.hpp b/runexamples/cpp/include/NumCpp/Utils/cube.hpp new file mode 100644 index 0000000..00d31ef --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/cube.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Cubes in input value +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Cubes in input value + /// + /// @param inValue + /// + /// @return cubed value + /// + template + constexpr dtype cube(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return inValue * inValue * inValue; + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/essentiallyEqual.hpp b/runexamples/cpp/include/NumCpp/Utils/essentiallyEqual.hpp new file mode 100644 index 0000000..20157f7 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/essentiallyEqual.hpp @@ -0,0 +1,83 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// tests that 2 floating point values are "essentially equal" +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// tests that 2 integer values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept + { + return inValue1 == inValue2; + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// @param inEpsilon + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2, dtype inEpsilon) noexcept + { + const auto absValue1 = std::abs(inValue1); + const auto absValue2 = std::abs(inValue2); + return std::abs(inValue1 - inValue2) <= ((absValue1 > absValue2 ? absValue2 : absValue1) * std::abs(inEpsilon)); + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(dtype inValue1, dtype inValue2) noexcept + { + return essentiallyEqual(inValue1, inValue2, DtypeInfo::epsilon()); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp b/runexamples/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp new file mode 100644 index 0000000..3c1ad47 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/essentiallyEqualComplex.hpp @@ -0,0 +1,86 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// tests that 2 floating point values are "essentially equal" +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/DtypeInfo.hpp" +#include "NumCpp/Core/Internal/StdComplexOperators.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// tests that 2 complex values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, const std::complex& inValue2) noexcept + { + return inValue1 == inValue2; + } + + //============================================================================ + /// tests that 2 complex values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// @param inEpsilon + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, + const std::complex& inValue2, + const std::complex& inEpsilon) noexcept + { + const auto absValue1 = std::abs(inValue1); + const auto absValue2 = std::abs(inValue2); + return std::abs(inValue1 - inValue2) <= ((absValue1 > absValue2 ? absValue2 : absValue1) * std::abs(inEpsilon)); + } + + //============================================================================ + /// tests that 2 floating point values are "essentially equal" + /// + /// @param inValue1 + /// @param inValue2 + /// + /// @return bool + /// + template::value, int> = 0> + bool essentiallyEqual(const std::complex& inValue1, const std::complex& inValue2) noexcept + { + return essentiallyEqual(inValue1, inValue2, DtypeInfo>::epsilon()); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/gaussian.hpp b/runexamples/cpp/include/NumCpp/Utils/gaussian.hpp new file mode 100644 index 0000000..53a3b56 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/gaussian.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// samples a 2D gaussian of mean zero and input STD sigma +/// +#pragma once + +#include + +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::utils +{ + //============================================================================ + // Method Description: + /// samples a 2D gaussian of mean zero and input STD sigma + /// + /// @param inX + /// @param inY + /// @param inSigma + /// + /// @return dtype + /// + inline double gaussian(double inX, double inY, double inSigma) noexcept + { + double exponent = sqr(inX) + sqr(inY); + exponent /= 2; + exponent /= sqr(inSigma); + return std::exp(-exponent); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/gaussian1d.hpp b/runexamples/cpp/include/NumCpp/Utils/gaussian1d.hpp new file mode 100644 index 0000000..543545a --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/gaussian1d.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// samples a 1D gaussian of input mean and sigma +/// +#pragma once + +#include + +#include "NumCpp/Utils/sqr.hpp" + +namespace nc::utils +{ + //============================================================================ + // Method Description: + /// samples a 1D gaussian of input mean and sigma + /// + /// @param inX + /// @param inMu + /// @param inSigma + /// + /// @return dtype + /// + inline double gaussian1d(double inX, double inMu, double inSigma) noexcept + { + double exponent = sqr(inX - inMu); + exponent /= 2; + exponent /= sqr(inSigma); + return std::exp(-exponent); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/interp.hpp b/runexamples/cpp/include/NumCpp/Utils/interp.hpp new file mode 100644 index 0000000..87ef689 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/interp.hpp @@ -0,0 +1,45 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Returns the linear interpolation between two points +/// +#pragma once + +namespace nc::utils +{ + //============================================================================ + /// Returns the linear interpolation between two points + /// + /// @param inValue1 + /// @param inValue2 + /// @param inPercent + /// + /// @return linear interpolated point + /// + constexpr double interp(double inValue1, double inValue2, double inPercent) noexcept + { + return inValue1 * (1. - inPercent) + inValue2 * inPercent; + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/num2str.hpp b/runexamples/cpp/include/NumCpp/Utils/num2str.hpp new file mode 100644 index 0000000..00f0ccc --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/num2str.hpp @@ -0,0 +1,50 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Converts the number into a string +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Converts the number into a string + /// + /// @param inNumber + /// + /// @return std::string + /// + template + std::string num2str(dtype inNumber) + { + STATIC_ASSERT_ARITHMETIC(dtype); + + return std::to_string(inNumber); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/power.hpp b/runexamples/cpp/include/NumCpp/Utils/power.hpp new file mode 100644 index 0000000..8d42955 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/power.hpp @@ -0,0 +1,62 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raises the input value to an integer power +/// +#pragma once + +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Raises the input value to an integer power + /// + /// @param inValue + /// @param inPower + /// + /// @return inValue raised to inPower + /// + template + dtype power(dtype inValue, uint8 inPower) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + if (inPower == 0) + { + return static_cast(1); + } + + dtype returnVal = inValue; + for (uint8 exponent = 1; exponent < inPower; ++exponent) + { + returnVal *= inValue; + } + return returnVal; + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/powerf.hpp b/runexamples/cpp/include/NumCpp/Utils/powerf.hpp new file mode 100644 index 0000000..73e36e6 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/powerf.hpp @@ -0,0 +1,53 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Raises the input value to a floating point power +/// +#pragma once + +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" +#include "NumCpp/Core/Internal/TypeTraits.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Raises the input value to a floating point power + /// + /// @param inValue + /// @param inPower + /// + /// @return inValue raised to inPower + /// + template + auto powerf(dtype1 inValue, const dtype2 inPower) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype1); + + return std::pow(inValue, inPower); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/sqr.hpp b/runexamples/cpp/include/NumCpp/Utils/sqr.hpp new file mode 100644 index 0000000..7d7bd04 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/sqr.hpp @@ -0,0 +1,48 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Squares in input value +/// +#pragma once + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Squares in input value + /// + /// @param inValue + /// + /// @return squared value + /// + template + constexpr dtype sqr(dtype inValue) noexcept + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + return inValue * inValue; + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/timeit.hpp b/runexamples/cpp/include/NumCpp/Utils/timeit.hpp new file mode 100644 index 0000000..fdcf31e --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/timeit.hpp @@ -0,0 +1,145 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Function profiling/timing +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Timer.hpp" +#include "NumCpp/Core/Types.hpp" + +namespace nc::utils +{ + namespace timeit_detail + { + /// @brief Result statistics of a timeit run + template + struct Result + { + TimeUnit min{}; + TimeUnit max{}; + TimeUnit mean{}; + }; + + template + std::ostream& operator<<(std::ostream& os, const Result result) + { + std::string unit{}; + if constexpr (std::is_same::value) + { + unit = " hours"; + } + else if constexpr (std::is_same::value) + { + unit = " minutes"; + } + else if constexpr (std::is_same::value) + { + unit = " seconds"; + } + else if constexpr (std::is_same::value) + { + unit = " milliseconds"; + } + else if constexpr (std::is_same::value) + { + unit = " microseconds"; + } + else if constexpr (std::is_same::value) + { + unit = " nanoseconds"; + } + else + { + unit = " time units of some sort"; + } + + os << "Timeit results:\n"; + os << "\tmin: " << result.min.count() << unit << "\n"; + os << "\tmax: " << result.max.count() << unit << "\n"; + os << "\tmean: " << result.mean.count() << unit << "\n"; + + return os; + } + } // namespace timeit_detail + + //============================================================================ + /// Timing of a function + /// + /// @param numIterations: number of iterations for the timing statistics + /// @param printResults: bool true to print the results + /// @param function: the function to time + /// @param args: the arguements that are forwarded to the function input + /// + /// @return timing statistics + /// + template + timeit_detail::Result + timeit(uint32 numIterations, bool printResults, Function function, Args&&... args) noexcept + { + auto result = timeit_detail::Result{}; + auto timer = Timer{}; + + for (uint32 i = 0; i < numIterations; ++i) + { + if (i == 0) + { + result.min = TimeUnit::max(); + } + + timer.tic(); + + using ResultType = std::invoke_result_t; + if constexpr (std::is_same_v) + { + function(std::forward(args)...); + } + else + { + // cppcheck-suppress redundantAssignment + [[maybe_unused]] const ResultType functionResult = function(std::forward(args)...); + } + + const auto elapsedTime = timer.toc(false); + + result.mean = result.mean + elapsedTime; + result.min = std::min(result.min, elapsedTime); + result.max = std::max(result.max, elapsedTime); + } + + result.mean = result.mean / numIterations; + + if (printResults) + { + std::cout << result; + } + + return result; + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Utils/value2str.hpp b/runexamples/cpp/include/NumCpp/Utils/value2str.hpp new file mode 100644 index 0000000..71a4d06 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Utils/value2str.hpp @@ -0,0 +1,54 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Converts the number into a string +/// +#pragma once + +#include +#include +#include + +#include "NumCpp/Core/Internal/StaticAsserts.hpp" + +namespace nc::utils +{ + //============================================================================ + /// Converts the value into a string + /// + /// @param inValue + /// + /// @return std::string + /// + template + std::string value2str(dtype inValue) + { + STATIC_ASSERT_ARITHMETIC_OR_COMPLEX(dtype); + + std::stringstream ss; + ss << inValue; + return ss.str(); + } +} // namespace nc::utils diff --git a/runexamples/cpp/include/NumCpp/Vector.hpp b/runexamples/cpp/include/NumCpp/Vector.hpp new file mode 100644 index 0000000..81ab863 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Vector.hpp @@ -0,0 +1,31 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple Vector classes +/// +#pragma once + +#include "NumCpp/Vector/Vec2.hpp" +#include "NumCpp/Vector/Vec3.hpp" diff --git a/runexamples/cpp/include/NumCpp/Vector/Vec2.hpp b/runexamples/cpp/include/NumCpp/Vector/Vec2.hpp new file mode 100644 index 0000000..29ea98d --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Vector/Vec2.hpp @@ -0,0 +1,560 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple 2D Vector class +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/interp.hpp" + +//==================================================================================== + +namespace nc +{ + //================================================================================ + // Class Description: + /// Holds a 2D vector + class Vec2 + { + public: + //====================================Attributes============================== + double x{ 0. }; + double y{ 0. }; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + constexpr Vec2() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inX: the x component + /// @param inY: the y component + /// + constexpr Vec2(double inX, double inY) noexcept : + x(inX), + y(inY) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + Vec2(const std::initializer_list& inList) + { + if (inList.size() != 2) + { + THROW_INVALID_ARGUMENT_ERROR("input initializer list must have a size = 2"); + } + + x = *inList.begin(); + y = *(inList.begin() + 1); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ndArray + /// + Vec2(const NdArray& ndArray) + { + if (ndArray.size() != 2) + { + THROW_INVALID_ARGUMENT_ERROR("input NdArray must have a size = 2"); + } + + x = ndArray[0]; + y = ndArray[1]; + } + + //============================================================================ + // Method Description: + /// Returns the angle between the two vectors + /// + /// @param otherVec + /// @return the angle in radians + /// + [[nodiscard]] double angle(const Vec2& otherVec) const noexcept + { + double dotProduct = dot(otherVec); + dotProduct /= norm(); + dotProduct /= otherVec.norm(); + + // clamp the value to the acos range just to be safe + dotProduct = std::max(std::min(dotProduct, 1.), -1.); + + return std::acos(dotProduct); + } + + //============================================================================ + // Method Description: + /// Returns a copy of the vector with its magnitude clamped + /// to maxLength + /// + /// @param maxLength + /// @return Vec2 + /// + [[nodiscard]] Vec2 clampMagnitude(double maxLength) const noexcept + { + const double magnitude = norm(); + if (magnitude <= maxLength) + { + return *this; + } + + Vec2 returnVec = Vec2(*this).normalize(); + returnVec *= maxLength; + return returnVec; + } + + //============================================================================ + // Method Description: + /// Returns the distance between the two vectors + /// + /// @param otherVec + /// @return the distance (equivalent to (a - b).norm() + /// + [[nodiscard]] double distance(const Vec2& otherVec) const noexcept + { + return (Vec2(*this) -= otherVec).norm(); + } + + //============================================================================ + // Method Description: + /// Returns the dot product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] double dot(const Vec2& otherVec) const noexcept + { + return x * otherVec.x + y * otherVec.y; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, -1] + /// + /// @return Vec2 + /// + static constexpr Vec2 down() noexcept + { + return Vec2(0., -1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [-1, 0] + /// + /// @return Vec2 + /// + static constexpr Vec2 left() noexcept + { + return Vec2(-1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Linearly interpolates between two vectors + /// + /// @param otherVec + /// @param t the amount to interpolate by (clamped from [0, 1]); + /// @return Vec2 + /// + [[nodiscard]] Vec2 lerp(const Vec2& otherVec, double t) const noexcept + { + t = std::max(std::min(t, 1.), 0.); + + Vec2 trajectory = otherVec; + trajectory -= *this; + const double xInterp = utils::interp(0., trajectory.x, t); + const double yInterp = utils::interp(0., trajectory.y, t); + + return Vec2(*this) += Vec2(xInterp, yInterp); + } + + //============================================================================ + // Method Description: + /// Returns the magnitude of the vector + /// + /// @return magnitude of the vector + /// + [[nodiscard]] double norm() const noexcept + { + return std::hypot(x, y); + } + + //============================================================================ + // Method Description: + /// Returns a new normalized Vec2 + /// + /// @return Vec2 + /// + [[nodiscard]] Vec2 normalize() const noexcept + { + return Vec2(*this) /= norm(); + } + + //============================================================================ + // Method Description: + /// Projects the vector onto the input vector + /// + /// @param otherVec + /// @return Vec2 + /// + [[nodiscard]] Vec2 project(const Vec2& otherVec) const noexcept + { + const double projectedMagnitude = norm() * std::cos(angle(otherVec)); + return otherVec.normalize() *= projectedMagnitude; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [1, 0] + /// + /// @return Vec2 + /// + static constexpr Vec2 right() noexcept + { + return Vec2(1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string toString() const + { + std::stringstream stream; + stream << "Vec2[" << x << ", " << y << "]"; + return stream.str(); + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + NdArray returnArray = { x, y }; + return returnArray.transpose(); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 1] + /// + /// @return Vec2 + /// + static constexpr Vec2 up() noexcept + { + return Vec2(0., 1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const Vec2& rhs) const noexcept + { + return utils::essentiallyEqual(x, rhs.x) && utils::essentiallyEqual(y, rhs.y); + } + + //============================================================================ + // Method Description: + /// Not Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const Vec2& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator+=(double scalar) noexcept + { + x += scalar; + y += scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param rhs + /// @return Vec2 + /// + Vec2& operator+=(const Vec2& rhs) noexcept + { + x += rhs.x; + y += rhs.y; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator-=(double scalar) noexcept + { + x -= scalar; + y -= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param rhs + /// @return Vec2 + /// + Vec2& operator-=(const Vec2& rhs) noexcept + { + x -= rhs.x; + y -= rhs.y; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator*=(double scalar) noexcept + { + x *= scalar; + y *= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param scalar + /// @return Vec2 + /// + Vec2& operator/=(double scalar) noexcept + { + x /= scalar; + y /= scalar; + return *this; + } + }; + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(double lhs, const Vec2& rhs) noexcept + { + return Vec2(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator+(const Vec2& lhs, const Vec2& rhs) noexcept + { + return Vec2(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Returns the negative vector + /// + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& vec) noexcept + { + return Vec2(-vec.x, -vec.y); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(double lhs, const Vec2& rhs) noexcept + { + return -Vec2(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator-(const Vec2& lhs, const Vec2& rhs) noexcept + { + return Vec2(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator*(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) *= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator*(double lhs, const Vec2& rhs) noexcept + { + return Vec2(rhs) *= lhs; + } + + //============================================================================ + // Method Description: + /// Vector mulitplication (dot product) + /// + /// @param lhs + /// @param rhs + /// @return dot product + /// + /// + inline double operator*(const Vec2& lhs, const Vec2& rhs) noexcept + { + return lhs.dot(rhs); + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param lhs + /// @param rhs + /// @return Vec2 + /// + inline Vec2 operator/(const Vec2& lhs, double rhs) noexcept + { + return Vec2(lhs) /= rhs; + } + + //============================================================================ + // Method Description: + /// stream output operator + /// + /// @param stream + /// @param vec + /// @return std::ostream + /// + inline std::ostream& operator<<(std::ostream& stream, const Vec2& vec) + { + stream << vec.toString() << std::endl; + return stream; + } +} // namespace nc diff --git a/runexamples/cpp/include/NumCpp/Vector/Vec3.hpp b/runexamples/cpp/include/NumCpp/Vector/Vec3.hpp new file mode 100644 index 0000000..200f903 --- /dev/null +++ b/runexamples/cpp/include/NumCpp/Vector/Vec3.hpp @@ -0,0 +1,612 @@ +/// @file +/// @author David Pilger +/// [GitHub Repository](https://github.com/dpilger26/NumCpp) +/// +/// License +/// Copyright 2018-2023 David Pilger +/// +/// Permission is hereby granted, free of charge, to any person obtaining a copy of this +/// software and associated documentation files(the "Software"), to deal in the Software +/// without restriction, including without limitation the rights to use, copy, modify, +/// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +/// permit persons to whom the Software is furnished to do so, subject to the following +/// conditions : +/// +/// The above copyright notice and this permission notice shall be included in all copies +/// or substantial portions of the Software. +/// +/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +/// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +/// PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE +/// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +/// DEALINGS IN THE SOFTWARE. +/// +/// Description +/// Simple 3D Vector class +/// +#pragma once + +#include +#include +#include +#include +#include + +#include "NumCpp/Core/Internal/Error.hpp" +#include "NumCpp/Functions/hypot.hpp" +#include "NumCpp/NdArray.hpp" +#include "NumCpp/Utils/essentiallyEqual.hpp" +#include "NumCpp/Utils/interp.hpp" + +//==================================================================================== + +namespace nc +{ + //================================================================================ + // Class Description: + /// Holds a 3D vector + class Vec3 + { + public: + //====================================Attributes============================== + double x{ 0. }; + double y{ 0. }; + double z{ 0. }; + + //============================================================================ + // Method Description: + /// Default Constructor + /// + constexpr Vec3() = default; + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inX: the x component + /// @param inY: the y component + /// @param inZ: the y component + /// + constexpr Vec3(double inX, double inY, double inZ) noexcept : + x(inX), + y(inY), + z(inZ) + { + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param inList + /// + Vec3(const std::initializer_list& inList) + { + if (inList.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input initializer list must have a size = 3"); + } + + x = *inList.begin(); + y = *(inList.begin() + 1); + z = *(inList.begin() + 2); + } + + //============================================================================ + // Method Description: + /// Constructor + /// + /// @param ndArray + /// + Vec3(const NdArray& ndArray) + { + if (ndArray.size() != 3) + { + THROW_INVALID_ARGUMENT_ERROR("input NdArray must have a size = 3"); + } + + x = ndArray[0]; + y = ndArray[1]; + z = ndArray[2]; + } + + //============================================================================ + // Method Description: + /// Returns the angle between the two vectors + /// + /// @param otherVec + /// @return the angle in radians + /// + [[nodiscard]] double angle(const Vec3& otherVec) const noexcept + { + double dotProduct = dot(otherVec); + dotProduct /= norm(); + dotProduct /= otherVec.norm(); + + // clamp the value to the acos range just to be safe + dotProduct = std::max(std::min(dotProduct, 1.), -1.); + + return std::acos(dotProduct); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 0, -1] + /// + /// @return Vec3 + /// + static constexpr Vec3 back() noexcept + { + return Vec3(0., 0., -1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns a copy of the vector with its magnitude clamped + /// to maxLength + /// + /// @param maxLength + /// @return Vec3 + /// + [[nodiscard]] Vec3 clampMagnitude(double maxLength) const noexcept + { + const double magnitude = norm(); + if (magnitude <= maxLength) + { + return *this; + } + + Vec3 returnVec = Vec3(*this).normalize(); + returnVec *= maxLength; + return returnVec; + } + + //============================================================================ + // Method Description: + /// Returns the cross product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] Vec3 cross(const Vec3& otherVec) const noexcept + { + const double crossX = y * otherVec.z - z * otherVec.y; + const double crossY = -(x * otherVec.z - z * otherVec.x); + const double crossZ = x * otherVec.y - y * otherVec.x; + + return Vec3(crossX, crossY, crossZ); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the distance between the two vectors + /// + /// @param otherVec + /// @return the distance (equivalent to (a - b).norm() + /// + [[nodiscard]] double distance(const Vec3& otherVec) const noexcept + { + return (Vec3(*this) -= otherVec).norm(); + } + + //============================================================================ + // Method Description: + /// Returns the dot product of the two vectors + /// + /// @param otherVec + /// @return the dot product + /// + [[nodiscard]] double dot(const Vec3& otherVec) const noexcept + { + return x * otherVec.x + y * otherVec.y + z * otherVec.z; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, -1, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 down() noexcept + { + return Vec3(0., -1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 0, 1] + /// + /// @return Vec3 + /// + static constexpr Vec3 forward() noexcept + { + return Vec3(0., 0., 1.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [-1, 0, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 left() noexcept + { + return Vec3(-1., 0., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Linearly interpolates between two vectors + /// + /// @param otherVec + /// @param t the amount to interpolate by (clamped from [0, 1]); + /// @return Vec3 + /// + [[nodiscard]] Vec3 lerp(const Vec3& otherVec, double t) const noexcept + { + t = std::max(std::min(t, 1.), 0.); + + Vec3 trajectory = otherVec; + trajectory -= *this; + const double xInterp = utils::interp(0., trajectory.x, t); + const double yInterp = utils::interp(0., trajectory.y, t); + const double zInterp = utils::interp(0., trajectory.z, t); + + return Vec3(*this) += Vec3(xInterp, yInterp, zInterp); + } + + //============================================================================ + // Method Description: + /// Returns the magnitude of the vector + /// + /// @return magnitude of the vector + /// + [[nodiscard]] double norm() const noexcept + { + return hypot(x, y, z); + } + + //============================================================================ + // Method Description: + /// Returns a new normalized Vec3 + /// + /// @return Vec3 + /// + [[nodiscard]] Vec3 normalize() const noexcept + { + return Vec3(*this) /= norm(); + } + + //============================================================================ + // Method Description: + /// Projects the vector onto the input vector + /// + /// @param otherVec + /// @return Vec3 + /// + [[nodiscard]] Vec3 project(const Vec3& otherVec) const noexcept + { + const double projectedMagnitude = norm() * std::cos(angle(otherVec)); + return otherVec.normalize() *= projectedMagnitude; + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [1, 0, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 right() noexcept + { + return Vec3(1., 0., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Returns the Vec3 as a string + /// + /// @return std::string + /// + [[nodiscard]] std::string toString() const + { + std::stringstream stream; + stream << "Vec3[" << x << ", " << y << ", " << z << "]"; + return stream.str(); + } + + //============================================================================ + // Method Description: + /// Returns the Vec2 as an NdArray + /// + /// @return NdArray + /// + [[nodiscard]] NdArray toNdArray() const + { + NdArray returnArray = { x, y, z }; + return returnArray.transpose(); + } + + //============================================================================ + // Method Description: + /// Returns the unit vector [0, 1, 0] + /// + /// @return Vec3 + /// + static constexpr Vec3 up() noexcept + { + return Vec3(0., 1., 0.); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator==(const Vec3& rhs) const noexcept + { + return utils::essentiallyEqual(x, rhs.x) && utils::essentiallyEqual(y, rhs.y) && + utils::essentiallyEqual(z, rhs.z); + } + + //============================================================================ + // Method Description: + /// Not Equality operator + /// + /// @param rhs + /// @return bool + /// + bool operator!=(const Vec3& rhs) const noexcept + { + return !(*this == rhs); + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator+=(double scalar) noexcept + { + x += scalar; + y += scalar; + z += scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param rhs + /// @return Vec3 + /// + Vec3& operator+=(const Vec3& rhs) noexcept + { + x += rhs.x; + y += rhs.y; + z += rhs.z; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator-=(double scalar) noexcept + { + x -= scalar; + y -= scalar; + z -= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param rhs + /// @return Vec3 + /// + Vec3& operator-=(const Vec3& rhs) noexcept + { + x -= rhs.x; + y -= rhs.y; + z -= rhs.z; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator*=(double scalar) noexcept + { + x *= scalar; + y *= scalar; + z *= scalar; + return *this; + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param scalar + /// @return Vec3 + /// + Vec3& operator/=(double scalar) noexcept + { + x /= scalar; + y /= scalar; + z /= scalar; + return *this; + } + }; + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Adds the scalar to the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(double lhs, const Vec3& rhs) noexcept + { + return Vec3(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Adds the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator+(const Vec3& lhs, const Vec3& rhs) noexcept + { + return Vec3(lhs) += rhs; + } + + //============================================================================ + // Method Description: + /// Returns the negative vector + /// + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& vec) noexcept + { + return Vec3(-vec.x, -vec.y, -vec.z); // NOLINT(modernize-return-braced-init-list) + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the scalar from the vector + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(double lhs, const Vec3& rhs) noexcept + { + return -Vec3(rhs) += lhs; + } + + //============================================================================ + // Method Description: + /// Subtracts the two vectors + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator-(const Vec3& lhs, const Vec3& rhs) noexcept + { + return Vec3(lhs) -= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator*(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) *= rhs; + } + + //============================================================================ + // Method Description: + /// Scalar mulitplication + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator*(double lhs, const Vec3& rhs) noexcept + { + return Vec3(rhs) *= lhs; + } + + //============================================================================ + // Method Description: + /// Vector mulitplication (dot product) + /// + /// @param lhs + /// @param rhs + /// @return dot product + /// + /// + inline double operator*(const Vec3& lhs, const Vec3& rhs) noexcept + { + return lhs.dot(rhs); + } + + //============================================================================ + // Method Description: + /// Scalar division + /// + /// @param lhs + /// @param rhs + /// @return Vec3 + /// + inline Vec3 operator/(const Vec3& lhs, double rhs) noexcept + { + return Vec3(lhs) /= rhs; + } + + //============================================================================ + // Method Description: + /// stream output operator + /// + /// @param stream + /// @param vec + /// @return std::ostream + /// + inline std::ostream& operator<<(std::ostream& stream, const Vec3& vec) + { + stream << vec.toString() << std::endl; + return stream; + } +} // namespace nc diff --git a/runexamples/cpp/onnx/GIT_COMMIT_ID b/runexamples/cpp/onnx/GIT_COMMIT_ID new file mode 100644 index 0000000..e402286 --- /dev/null +++ b/runexamples/cpp/onnx/GIT_COMMIT_ID @@ -0,0 +1 @@ +0c5b95fc86750526d09ee9e669a98506116c6bde diff --git a/runexamples/cpp/onnx/LICENSE b/runexamples/cpp/onnx/LICENSE new file mode 100644 index 0000000..48bc6bb --- /dev/null +++ b/runexamples/cpp/onnx/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/runexamples/cpp/onnx/Privacy.md b/runexamples/cpp/onnx/Privacy.md new file mode 100644 index 0000000..fcc8468 --- /dev/null +++ b/runexamples/cpp/onnx/Privacy.md @@ -0,0 +1,21 @@ +# Privacy + +## Data Collection +The software may collect information about you and your use of the software and send it to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may turn off the telemetry as described in the repository. There are also some features in the software that may enable you and Microsoft to collect data from users of your applications. If you use these features, you must comply with applicable law, including providing appropriate notices to users of your applications together with a copy of Microsoft's privacy statement. Our privacy statement is located at https://go.microsoft.com/fwlink/?LinkID=824704. You can learn more about data collection and use in the help documentation and our privacy statement. Your use of the software operates as your consent to these practices. + +*** + +### Private Builds +No data collection is performed when using your private builds built from source code. + +### Official Builds +ONNX Runtime does not maintain any independent telemetry collection mechanisms outside of what is provided by the platforms it supports. However, where applicable, ONNX Runtime will take advantage of platform-supported telemetry systems to collect trace events with the goal of improving product quality. + +Currently telemetry is only implemented for Windows builds and is turned **ON** by default in the official builds distributed in their respective package management repositories ([see here](../README.md#binaries)). This may be expanded to cover other platforms in the future. Data collection is implemented via 'Platform Telemetry' per vendor platform providers (see [telemetry.h](../onnxruntime/core/platform/telemetry.h)). + +#### Technical Details +The Windows provider uses the [TraceLogging](https://docs.microsoft.com/en-us/windows/win32/tracelogging/trace-logging-about) API for its implementation. This enables ONNX Runtime trace events to be collected by the operating system, and based on user consent, this data may be periodically sent to Microsoft servers following GDPR and privacy regulations for anonymity and data access controls. + +Windows ML and onnxruntime C APIs allow Trace Logging to be turned on/off (see [API pages](../README.md#api-documentation) for details). +For information on how to enable and disable telemetry, see [C API: Telemetry](./C_API.md#telemetry). +There are equivalent APIs in the C#, Python, and Java language bindings as well. diff --git a/runexamples/cpp/onnx/README.md b/runexamples/cpp/onnx/README.md new file mode 100644 index 0000000..22ef387 --- /dev/null +++ b/runexamples/cpp/onnx/README.md @@ -0,0 +1,61 @@ +

+ +**ONNX Runtime is a cross-platform inference and training machine-learning accelerator**. + +**ONNX Runtime inference** can enable faster customer experiences and lower costs, supporting models from deep learning frameworks such as PyTorch and TensorFlow/Keras as well as classical machine learning libraries such as scikit-learn, LightGBM, XGBoost, etc. ONNX Runtime is compatible with different hardware, drivers, and operating systems, and provides optimal performance by leveraging hardware accelerators where applicable alongside graph optimizations and transforms. [Learn more →](https://www.onnxruntime.ai/docs/#onnx-runtime-for-inferencing) + +**ONNX Runtime training** can accelerate the model training time on multi-node NVIDIA GPUs for transformer models with a one-line addition for existing PyTorch training scripts. [Learn more →](https://www.onnxruntime.ai/docs/#onnx-runtime-for-training) + +## Get Started & Resources + +* **General Information**: [onnxruntime.ai](https://onnxruntime.ai) + +* **Usage documention and tutorials**: [onnxruntime.ai/docs](https://onnxruntime.ai/docs) + +* **YouTube video tutorials**: [youtube.com/@ONNXRuntime](https://www.youtube.com/@ONNXRuntime) + +* [**Upcoming Release Roadmap**](https://github.com/microsoft/onnxruntime/wiki/Upcoming-Release-Roadmap) + +* **Companion sample repositories**: + - ONNX Runtime Inferencing: [microsoft/onnxruntime-inference-examples](https://github.com/microsoft/onnxruntime-inference-examples) + - ONNX Runtime Training: [microsoft/onnxruntime-training-examples](https://github.com/microsoft/onnxruntime-training-examples) + +## Builtin Pipeline Status + +|System|Inference|Training| +|---|---|---| +|Windows|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Windows%20CPU%20CI%20Pipeline?label=Windows+CPU)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=9)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Windows%20GPU%20CI%20Pipeline?label=Windows+GPU)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=10)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Windows%20GPU%20TensorRT%20CI%20Pipeline?label=Windows+GPU+TensorRT)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=47)|| +|Linux|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Linux%20CPU%20CI%20Pipeline?label=Linux+CPU)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=11)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Linux%20CPU%20Minimal%20Build%20E2E%20CI%20Pipeline?label=Linux+CPU+Minimal+Build)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=64)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Linux%20GPU%20CI%20Pipeline?label=Linux+GPU)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=12)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Linux%20GPU%20TensorRT%20CI%20Pipeline?label=Linux+GPU+TensorRT)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=45)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Linux%20OpenVINO%20CI%20Pipeline?label=Linux+OpenVINO)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=55)|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/orttraining-linux-ci-pipeline?label=Linux+CPU+Training)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=86)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/orttraining-linux-gpu-ci-pipeline?label=Linux+GPU+Training)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=84)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/orttraining/orttraining-ortmodule-distributed?label=Training+Distributed)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=148)| +|Mac|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/MacOS%20CI%20Pipeline?label=MacOS+CPU)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=13)|| +|Android|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/Android%20CI%20Pipeline?label=Android)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=53)|| +|iOS|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/iOS%20CI%20Pipeline?label=iOS)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=134)|| +|Web|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/ONNX%20Runtime%20Web%20CI%20Pipeline?label=Web)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=161)|| +|Other|[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/onnxruntime-binary-size-checks-ci-pipeline?repoName=microsoft%2Fonnxruntime&label=Binary+Size+Check)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=187&repoName=microsoft%2Fonnxruntime)
[![Build Status](https://dev.azure.com/onnxruntime/onnxruntime/_apis/build/status/onnxruntime-python-checks-ci-pipeline?label=Python+Checks)](https://dev.azure.com/onnxruntime/onnxruntime/_build/latest?definitionId=164)|| + +## Third-party Pipeline Status + +|System|Inference|Training| +|---|---|---| +|Linux|[![Build Status](https://github.com/Ascend/onnxruntime/actions/workflows/build-and-test.yaml/badge.svg)](https://github.com/Ascend/onnxruntime/actions/workflows/build-and-test.yaml)|| + +## Data/Telemetry + +Windows distributions of this project may collect usage data and send it to Microsoft to help improve our products and services. See the [privacy statement](docs/Privacy.md) for more details. + +## Contributions and Feedback + +We welcome contributions! Please see the [contribution guidelines](CONTRIBUTING.md). + +For feature requests or bug reports, please file a [GitHub Issue](https://github.com/Microsoft/onnxruntime/issues). + +For general discussion or questions, please use [GitHub Discussions](https://github.com/microsoft/onnxruntime/discussions). + +## Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. + +## License + +This project is licensed under the [MIT License](LICENSE). diff --git a/runexamples/cpp/onnx/ThirdPartyNotices.txt b/runexamples/cpp/onnx/ThirdPartyNotices.txt new file mode 100644 index 0000000..985eb64 --- /dev/null +++ b/runexamples/cpp/onnx/ThirdPartyNotices.txt @@ -0,0 +1,6266 @@ +THIRD PARTY SOFTWARE NOTICES AND INFORMATION + +Do Not Translate or Localize + +This software incorporates material from third parties. Microsoft makes certain +open source code available at http://3rdpartysource.microsoft.com, or you may +send a check or money order for US $5.00, including the product name, the open +source component name, and version number, to: + +Source Code Compliance Team +Microsoft Corporation +One Microsoft Way +Redmond, WA 98052 +USA + +Notwithstanding any other terms, you may reverse engineer this software to the +extent required to debug changes to any libraries licensed under the GNU Lesser +General Public License. + +_____ + +Intel Math Kernel Library (Intel MKL) + +Intel Simplified Software License (Version April 2018) + +Copyright (c) 2018 Intel Corporation. + +Use and Redistribution. You may use and redistribute the software (the “Software”), without modification, +provided the following conditions are met: + +* Redistributions must reproduce the above copyright notice and the following terms of use in the Software +and in the documentation and/or other materials provided with the distribution. + +* Neither the name of Intel nor the names of its suppliers may be used to endorse or promote products +derived from this Software without specific prior written permission. + +* No reverse engineering, decompilation, or disassembly of this Software is permitted. + +Limited patent license. Intel grants you a world-wide, royalty-free, non-exclusive license under patents it now +or hereafter owns or controls to make, have made, use, import, offer to sell and sell (“Utilize”) this Software, +but solely to the extent that any such patent is necessary to Utilize the Software alone. The patent license +shall not apply to any combinations which include this software. No hardware per se is licensed hereunder. + +Third party and other Intel programs. “Third Party Programs” are the files listed in the “third-party-programs.txt” +text file that is included with the Software and may include Intel programs under separate license terms. +Third Party Programs, even if included with the distribution of the Materials, are governed by +separate license terms and those license terms solely govern your use of those programs. + +DISCLAIMER. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. THIS SOFTWARE IS +NOT INTENDED FOR USE IN SYSTEMS OR APPLICATIONS WHERE FAILURE OF THE SOFTWARE +MAY CAUSE PERSONAL INJURY OR DEATH AND YOU AGREE THAT YOU ARE FULLY RESPONSIBLE FOR ANY +CLAIMS, COSTS, DAMAGES, EXPENSES, AND ATTORNEYS’ FEES ARISING OUT OF ANY SUCH USE, +EVEN IF ANY CLAIM ALLEGES THAT INTEL WAS NEGLIGENT REGARDING THE DESIGN OR MANUFACTURE OF +THE MATERIALS. + +LIMITATION OF LIABILITY. IN NO EVENT WILL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY +OF SUCH DAMAGE. YOU AGREE TO INDEMNIFY AND HOLD INTEL HARMLESS AGAINST ANY CLAIMS +AND EXPENSES RESULTING FROM YOUR USE OR UNAUTHORIZED USE OF THE SOFTWARE. + +No support. Intel may make changes to the Software, at any time without notice, and is not obligated to +support, update or provide training for the Software. + +Termination. Intel may terminate your right to use the Software in the event of your breach of this Agreement +and you fail to cure the breach within a reasonable period of time. + +Feedback. Should you provide Intel with comments, modifications, corrections, enhancements or other input +(“Feedback”) related to the Software Intel will be free to use, disclose, reproduce, license or otherwise +distribute or exploit the Feedback in its sole discretion without any obligations or restrictions of any kind, +including without limitation, intellectual property rights or licensing obligations. + +Compliance with laws. You agree to comply with all relevant laws and regulations governing your use, +transfer, import or export (or prohibition thereof) of the Software. + +Governing law. All disputes will be governed by the laws of the United States of America and the State of +Delaware without reference to conflict of law principles and subject to the exclusive jurisdiction of the state or +federal courts sitting in the State of Delaware, and each party agrees that it submits to the personal +jurisdiction and venue of those courts and waives any objections. The United Nations Convention on +Contracts for the International Sale of Goods (1980) is specifically excluded and will not apply to the +Software. + +*Other names and brands may be claimed as the property of others. + +_____ + +protocolbuffers/protobuf + +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. + +_____ + +madler/zlib + +The deflate format used by zlib was defined by Phil Katz. The deflate and +zlib specifications were written by L. Peter Deutsch. Thanks to all the +people who reported problems and suggested various improvements in zlib; they +are too numerous to cite here. + +Copyright notice: + + (C) 1995-2017 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. + +_____ + +pybind/pybind11 + +Copyright (c) 2016 Wenzel Jakob , All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Please also refer to the file CONTRIBUTING.md, which clarifies licensing of +external contributions to this project including patches, pull requests, etc. + +_____ + +onnx +Open Neural Network Exchange + +Copyright (c) Facebook, Inc. and Microsoft Corporation. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Eigen + +MPL v2.0 +Mozilla Public License Version 2.0 + + +================================== + +1. Definitions + +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions + +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities + +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination + +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. + +_____ + +intel/dnnl + +Copyright 2016-2018 Intel Corporation + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +sub-components: + +xbyak + +Copyright (c) 2007 MITSUNARI Shigeo. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. +Neither the name of the copyright owner nor the names of its contributors may +be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Microsoft GSL + +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +_____ + +Tensorflow + +Copyright 2018 The TensorFlow Authors. All rights reserved. + +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017, The TensorFlow Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Microsoft Cognitive Toolkit (CNTK) + +Copyright (c) Microsoft Corporation. All rights reserved. + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +NumPy License + +Copyright (c) 2005, NumPy Developers + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +Pytorch / Caffe2 + +From PyTorch: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +From Caffe2: + +Copyright (c) 2016-present, Facebook Inc. All rights reserved. + +All contributions by Facebook: +Copyright (c) 2016 Facebook Inc. + +All contributions by Google: +Copyright (c) 2015 Google Inc. +All rights reserved. + +All contributions by Yangqing Jia: +Copyright (c) 2015 Yangqing Jia +All rights reserved. + +All contributions from Caffe: +Copyright(c) 2013, 2014, 2015, the respective contributors +All rights reserved. + +All other contributions: +Copyright(c) 2015, 2016 the respective contributors +All rights reserved. + +Caffe2 uses a copyright model similar to Caffe: each contributor holds +copyright over their contributions to Caffe2. The project versioning records +all such contribution and copyright details. If a contributor wants to further +mark their specific copyright on a particular contribution, they should +indicate their copyright solely in the commit message of the change when it is +committed. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +_____ + +Caffe + +COPYRIGHT + +All contributions by the University of California: +Copyright (c) 2014-2017 The Regents of the University of California (Regents) +All rights reserved. + +All other contributions: +Copyright (c) 2014-2017, the respective contributors +All rights reserved. + +Caffe uses a shared copyright model: each contributor holds copyright over +their contributions to Caffe. The project versioning records all such +contribution and copyright details. If a contributor wants to further mark +their specific copyright on a particular contribution, they should indicate +their copyright solely in the commit message of the change when it is +committed. + +LICENSE + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +CONTRIBUTION AGREEMENT + +By contributing to the BVLC/caffe repository through pull-request, comment, +or otherwise, the contributor releases their content to the +license and copyright terms herein. + +_____ + +The LLVM Compiler Infrastructure + +============================================================================== +LLVM Release License +============================================================================== +University of Illinois/NCSA +Open Source License + +Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign. +All rights reserved. + +Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal with +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at + Urbana-Champaign, nor the names of its contributors may be used to + endorse or promote products derived from this Software without specific + prior written permission. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. + +============================================================================== +Copyrights and Licenses for Third Party Software Distributed with LLVM: +============================================================================== +The LLVM software contains code written by third parties. Such software will +have its own individual LICENSE.TXT file in the directory in which it appears. +This file will describe the copyrights, license, and restrictions which apply +to that code. + +The disclaimer of warranty in the University of Illinois Open Source License +applies to all code in the LLVM Distribution, and nothing in any of the +other licenses gives permission to use the names of the LLVM Team or the +University of Illinois to endorse or promote products derived from this +Software. + +The following pieces of software have additional or alternate copyrights, +licenses, and/or restrictions: + +Program Directory +------- --------- +Google Test llvm/utils/unittest/googletest +OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex} +pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT} +ARM contributions llvm/lib/Target/ARM/LICENSE.TXT +md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h + +_____ + +google/benchmark + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +CONTRIBUTORS + +# People who have agreed to one of the CLAs and can contribute patches. +# The AUTHORS file lists the copyright holders; this file +# lists people. For example, Google employees are listed here +# but not in AUTHORS, because Google holds the copyright. +# +# Names should be added to this file only after verifying that +# the individual or the individual's organization has agreed to +# the appropriate Contributor License Agreement, found here: +# +# https://developers.google.com/open-source/cla/individual +# https://developers.google.com/open-source/cla/corporate +# +# The agreement for individuals can be filled out on the web. +# +# When adding J Random Contributor's name to this file, +# either J's name or J's organization's name should be +# added to the AUTHORS file, depending on whether the +# individual or corporate CLA was used. +# +# Names should be added to this file as: +# Name +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Billy Robert O'Neal III +Chris Kennelly +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dominic Hamon +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +John Millikin +Jussi Knuuttila +Kai Wolf +Kishan Kumar +Kaito Udagawa +Lei Xu +Matt Clarkson +Maxim Vafin +Nick Hutchinson +Oleksandr Sochka +Pascal Leroy +Paul Redmond +Pierre Phaneuf +Radoslav Yovchev +Raul Marin +Ray Glover +Robert Guo +Roman Lebedev +Shuo Chen +Tobias Ulvgård +Tom Madams +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +AUTHORS + +# This is the official list of benchmark authors for copyright purposes. +# This file is distinct from the CONTRIBUTORS files. +# See the latter for an explanation. +# +# Names should be added to this file as: +# Name or Organization +# The email address is not required for organizations. +# +# Please keep the list sorted. + +Albert Pretorius +Arne Beer +Carto +Christopher Seymour +David Coeurjolly +Deniz Evrenci +Dirac Research +Dominik Czarnota +Eric Fiselier +Eugene Zhuk +Evgeny Safronov +Federico Ficarelli +Felix Homann +Google Inc. +International Business Machines Corporation +Ismael Jimenez Martinez +Jern-Kuan Leong +JianXiong Zhou +Joao Paulo Magalhaes +Jussi Knuuttila +Kaito Udagawa +Kishan Kumar +Lei Xu +Matt Clarkson +Maxim Vafin +MongoDB Inc. +Nick Hutchinson +Oleksandr Sochka +Paul Redmond +Radoslav Yovchev +Roman Lebedev +Shuo Chen +Steinar H. Gunderson +Stripe, Inc. +Yixuan Qiu +Yusuke Suzuki +Zbigniew Skowron + +_____ + +HalidelR + +Copyright (c) 2016 HalideIR contributors +Copyright (c) 2012-2014 MIT CSAIL, Google Inc., and other contributors +HalideIR is derived from the Halide project. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +Distributed Machine Learning Common Codebase + +Copyright (c) 2015 by Contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +_____ + +DLPack: Open In Memory Tensor Structure + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 by Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +HowardHinnant/date + +The source code in this project is released using the MIT License. There is no +global license for the project because each file is licensed individually with +different author names and/or dates. + +If you contribute to this project, please add your name to the license of each +file you modify. If you have already contributed to this project and forgot to +add your name to the license, please feel free to submit a new P/R to add your +name to the license in each file you modified. + +For convenience, here is a copy of the MIT license found in each file except +without author names or dates: + +The MIT License (MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +TVM Open Deep Learning Compiler Stack + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +CONTRIBUTORS + +TVM Contributors +================ +TVM adopts the Apache style model and governs by merit. We believe that it is important to create an inclusive community where everyone can use, +contribute to, and influence the direction of the project. We actively invite contributors who have earned the merit to be part of the development community. + +See the [community structure document](http://docs.tvm.ai/contribute/community.html) for the explanation of community structure and contribution guidelines. + +## Committers +- [Tianqi Chen](https://github.com/tqchen) (PMC) +- [Thierry Moreau](http://homes.cs.washington.edu/~moreau/) +- [Ziheng Jiang](https://github.com/ZihengJiang) +- [Haichen Shen](http://homes.cs.washington.edu/~haichen/) +- [Yizhi Liu](https://github.com/yzhliu) + +## Code Owners +- [Aditya Atluri](https://github.com/adityaatluri) ROCM +- [Leyuan Wang](https://github.com/Laurawly) TOPI +- [Yuwei Hu](https://github.com/Huyuwei) TOPI +- [Zhixun Tan](https://github.com/phisiart) OpenGL/WebGL backend +- [Nick Hynes](https://github.com/nhynes) SGX and secured computing +- [Lianmin Zheng](https://github.com/merrymercy) AutoTVM + +## Reviewers +- [Zhi Chen](https://github.com/zhiics) +- [Xiaoqiang Dan](https://github.com/xqdan) +- [Liangfu Chen](https://github.com/liangfu) +- [Masahiro Masuda](https://github.com/masahi) +- [Kazutaka Morita](https://github.com/kazum) +- [Tatsuya Nishiyama](https://github.com/nishi-t) +- [Pariksheet Pinjari](https://github.com/PariksheetPinjari909) +- [Jared Roesch](https://github.com/jroesch) +- [Siva](https://github.com/srkreddy1238) +- [Siju Samuel](https://github.com/siju-samuel) +- [Alex Weaver](https://github.com/alex-weaver) +- [Yao Wang](https://github.com/kevinthesun) +- [Jian Weng](https://github.com/were) +- [Eddie Yan](https://github.com/eqy) +- [Joshua Z. Zhang](https://github.com/zhreshold) + +## List of Contributors +- [Full List of Contributors](https://github.com/dmlc/tvm/graphs/contributors) + - To contributors: please add your name to the list. +- [Qiao Zhang](https://github.com/zhangqiaorjc) +- [Haolong Zhang](https://github.com/haolongzhangm) +- [Cody Hao Yu](https://github.com/comaniac) +- [Chris Nuernberger](https://github.com/cnuernber) + +_____ + +FreeBSD: getopt.c file + +Copyright (c) 1987, 1993, 1994 +The Regents of the University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +3. Neither the name of the University nor the names of its contributors +may be used to endorse or promote products derived from this software +without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +_____ + + +google/googletest + +Copyright 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +G3log : Asynchronous logger with Dynamic Sinks + +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to +_____ + +Scikit-learn + +Copyright (c) 2007–2018 The scikit-learn developers. +All rights reserved. + + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + a. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + b. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + c. Neither the name of the Scikit-learn Developers nor the names of + its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. + +_____ + +google/nsync + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +google/re2 + +Copyright (c) 2009 The RE2 Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +onnx/onnx-tensorrt + +MIT License + +Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +Copyright (c) 2018 Open Neural Network Exchange + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ +nvidia/cutlass + +Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +SPDX-License-Identifier: BSD-3-Clause + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ +Boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +_____ + +JDAI-CV/DNNLibrary + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2019] [JD.com Inc. JD AI] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +google/flatbuffers + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +google/glog + +Copyright (c) 2008, Google Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +A function gettimeofday in utilities.cc is based on + +http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd + +The license of this code is: + +Copyright (c) 2003-2008, Jouni Malinen and contributors +All Rights Reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the name(s) of the above-listed copyright holder(s) nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +abseil-cpp +https://github.com/abseil/abseil-cpp + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +microsoft/wil + +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE + +_____ + +nlohmann/json + +MIT License + +Copyright (c) 2013-2019 Niels Lohmann + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +dcleblanc/SafeInt + +MIT License + +Copyright (c) 2018 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ +Open MPI + +3-Clause BSD License + +Most files in this release are marked with the copyrights of the +organizations who have edited them. The copyrights below are in no +particular order and generally reflect members of the Open MPI core +team who have contributed code to this release. The copyrights for +code used under license from other parties are included in the +corresponding files. + +Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana + University Research and Technology + Corporation. All rights reserved. +Copyright (c) 2004-2017 The University of Tennessee and The University + of Tennessee Research Foundation. All rights + reserved. +Copyright (c) 2004-2010 High Performance Computing Center Stuttgart, + University of Stuttgart. All rights reserved. +Copyright (c) 2004-2008 The Regents of the University of California. + All rights reserved. +Copyright (c) 2006-2017 Los Alamos National Security, LLC. All rights + reserved. +Copyright (c) 2006-2017 Cisco Systems, Inc. All rights reserved. +Copyright (c) 2006-2010 Voltaire, Inc. All rights reserved. +Copyright (c) 2006-2017 Sandia National Laboratories. All rights reserved. +Copyright (c) 2006-2010 Sun Microsystems, Inc. All rights reserved. + Use is subject to license terms. +Copyright (c) 2006-2017 The University of Houston. All rights reserved. +Copyright (c) 2006-2009 Myricom, Inc. All rights reserved. +Copyright (c) 2007-2017 UT-Battelle, LLC. All rights reserved. +Copyright (c) 2007-2017 IBM Corporation. All rights reserved. +Copyright (c) 1998-2005 Forschungszentrum Juelich, Juelich Supercomputing + Centre, Federal Republic of Germany +Copyright (c) 2005-2008 ZIH, TU Dresden, Federal Republic of Germany +Copyright (c) 2007 Evergrid, Inc. All rights reserved. +Copyright (c) 2008 Chelsio, Inc. All rights reserved. +Copyright (c) 2008-2009 Institut National de Recherche en + Informatique. All rights reserved. +Copyright (c) 2007 Lawrence Livermore National Security, LLC. + All rights reserved. +Copyright (c) 2007-2017 Mellanox Technologies. All rights reserved. +Copyright (c) 2006-2010 QLogic Corporation. All rights reserved. +Copyright (c) 2008-2017 Oak Ridge National Labs. All rights reserved. +Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved. +Copyright (c) 2009-2015 Bull SAS. All rights reserved. +Copyright (c) 2010 ARM ltd. All rights reserved. +Copyright (c) 2016 ARM, Inc. All rights reserved. +Copyright (c) 2010-2011 Alex Brick . All rights reserved. +Copyright (c) 2012 The University of Wisconsin-La Crosse. All rights + reserved. +Copyright (c) 2013-2016 Intel, Inc. All rights reserved. +Copyright (c) 2011-2017 NVIDIA Corporation. All rights reserved. +Copyright (c) 2016 Broadcom Limited. All rights reserved. +Copyright (c) 2011-2017 Fujitsu Limited. All rights reserved. +Copyright (c) 2014-2015 Hewlett-Packard Development Company, LP. All + rights reserved. +Copyright (c) 2013-2017 Research Organization for Information Science (RIST). + All rights reserved. +Copyright (c) 2017-2018 Amazon.com, Inc. or its affiliates. All Rights + reserved. +Copyright (c) 2018 DataDirect Networks. All rights reserved. +Copyright (c) 2018-2019 Triad National Security, LLC. All rights reserved. + +$COPYRIGHT$ + +Additional copyrights may follow + +$HEADER$ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +- Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer listed + in this license in the documentation and/or other materials + provided with the distribution. + +- Neither the name of the copyright holders nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +The copyright holders provide no reassurances that the source code +provided does not infringe any patent, copyright, or any other +intellectual property rights of third parties. The copyright holders +disclaim any liability to any recipient for claims brought against +recipient by any third party for infringement of that parties +intellectual property rights. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +The Android Open Source Project + +Copyright (C) 2017 The Android Open Source Project +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +------ + +libprotobuf-mutator + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ----- + + openucx/ucx + https://github.com/openucx/ucx + + Copyright (c) 2014-2015 UT-Battelle, LLC. All rights reserved. + Copyright (C) 2014-2020 Mellanox Technologies Ltd. All rights reserved. + Copyright (C) 2014-2015 The University of Houston System. All rights reserved. + Copyright (C) 2015 The University of Tennessee and The University + of Tennessee Research Foundation. All rights reserved. + Copyright (C) 2016-2020 ARM Ltd. All rights reserved. + Copyright (c) 2016 Los Alamos National Security, LLC. All rights reserved. + Copyright (C) 2016-2020 Advanced Micro Devices, Inc. All rights reserved. + Copyright (C) 2019 UChicago Argonne, LLC. All rights reserved. + Copyright (c) 2018-2020 NVIDIA CORPORATION. All rights reserved. + Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved. + Copyright (C) 2016-2020 Stony Brook University. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + ----- + + From PyTorch: + + Copyright (c) 2016- Facebook, Inc (Adam Paszke) + Copyright (c) 2014- Facebook, Inc (Soumith Chintala) + Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) + Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) + Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) + Copyright (c) 2011-2013 NYU (Clement Farabet) + Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) + Copyright (c) 2006 Idiap Research Institute (Samy Bengio) + Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + + From Caffe2: + + Copyright (c) 2016-present, Facebook Inc. All rights reserved. + + All contributions by Facebook: + Copyright (c) 2016 Facebook Inc. + + All contributions by Google: + Copyright (c) 2015 Google Inc. + All rights reserved. + + All contributions by Yangqing Jia: + Copyright (c) 2015 Yangqing Jia + All rights reserved. + + All contributions from Caffe: + Copyright(c) 2013, 2014, 2015, the respective contributors + All rights reserved. + + All other contributions: + Copyright(c) 2015, 2016 the respective contributors + All rights reserved. + + Caffe2 uses a copyright model similar to Caffe: each contributor holds + copyright over their contributions to Caffe2. The project versioning records + all such contribution and copyright details. If a contributor wants to further + mark their specific copyright on a particular contribution, they should + indicate their copyright solely in the commit message of the change when it is + committed. + + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + +_____ + + mpi4py + https://github.com/mpi4py/mpi4py/ + + ======================= + LICENSE: MPI for Python + ======================= + + :Author: Lisandro Dalcin + :Contact: dalcinl@gmail.com + + + Copyright (c) 2019, Lisandro Dalcin. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +_____ +huggingface/transformers + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +_____ +msgpack/msgpack-python + +Copyright (C) 2008-2011 INADA Naoki + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +_____ +lanpa/tensorboardX + +MIT License + +Copyright (c) 2017 Tzu-Wei Huang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +_____ +tensorflow/tensorboard + +Copyright 2017 The TensorFlow Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017, The TensorFlow Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +_____ + +cerberus + +Cerberus is a lightweight and extensible data validation library for Python. + +ISC License + +Copyright (c) 2012-2016 Nicola Iarocci. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +MurmurHash3 + +MIT license + +https://github.com/aappleby/smhasher + +SMHasher is a test suite designed to test the distribution, collision, and +performance properties of non-cryptographic hash functions. +This is the home for the MurmurHash family of hash functions along with the +SMHasher test suite used to verify them. +SMHasher is released under the MIT license. +All MurmurHash versions are public domain software, and the author disclaims all copyright to their code. + +_____ + +gtest-ios-framework + +https://github.com/mestevens/gtest-ios-framework + +Copyright (c) 2013 Matthew Stevens + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +DLPack + +https://github.com/dmlc/dlpack + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 by Contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +emsdk + +MIT/Expat license + +https://github.com/emscripten-core/emsdk + +Copyright (c) 2018 Emscripten authors (see AUTHORS in Emscripten) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +---------------------------------------------------------------------------- + +This is the MIT/Expat Licence. For more information see: + +1. http://www.opensource.org/licenses/mit-license.php + +2. http://en.wikipedia.org/wiki/MIT_License + +_____ + +coremltools + +BSD-3-Clause License + +https://github.com/apple/coremltools + +Copyright (c) 2020, Apple Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +© 2021 GitHub, Inc. + +_____ + +react-native + +MIT License + +https://github.com/facebook/react-native + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +pytorch/cpuinfo + +BSD 2-Clause "Simplified" License + +https://github.com/pytorch/cpuinfo + +Copyright (c) 2019 Google LLC +Copyright (c) 2017-2018 Facebook Inc. +Copyright (C) 2012-2017 Georgia Institute of Technology +Copyright (C) 2010-2012 Marat Dukhan + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +SQLite Is Public Domain + +All of the code and documentation in SQLite has been dedicated to the public +domain by the authors. All code authors, and representatives of the companies +they work for, have signed affidavits dedicating their contributions to the +public domain and originals of those signed affidavits are stored in a firesafe +at the main offices of Hwaci. Anyone is free to copy, modify, publish, use, +compile, sell, or distribute the original SQLite code, either in source code +form or as a compiled binary, for any purpose, commercial or non-commercial, +and by any means. + +The previous paragraph applies to the deliverable code and documentation in +SQLite - those parts of the SQLite library that you actually bundle and ship +with a larger application. Some scripts used as part of the build process (for +example the "configure" scripts generated by autoconf) might fall under other +open-source licenses. Nothing from these build scripts ever reaches the final +deliverable SQLite library, however, and so the licenses associated with those +scripts should not be a factor in assessing your rights to copy and use the +SQLite library. + +All of the deliverable code in SQLite has been written from scratch. No code +has been taken from other projects or from the open internet. Every line of +code can be traced back to its original author, and all of those authors have +public domain dedications on file. So the SQLite code base is clean and is +uncontaminated with licensed code from other projects. + +_____ + +google/XNNPACK + +BSD License + +For XNNPACK software + +Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +Copyright 2019 Google LLC + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +google/sentencepiece, https://github.com/google/sentencepiece +(included when statically linked with onnxruntime-extensions) + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +dlfcn-win32/dlfcn-win32 is licensed under the MIT License + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +_____ + +The Python Imaging Library (PIL) is + + Copyright © 1997-2011 by Secret Labs AB + Copyright © 1995-2011 by Fredrik Lundh + +Pillow is the friendly PIL fork. It is + + Copyright © 2010-2023 by Alex Clark and contributors + +Like PIL, Pillow is licensed under the open source HPND License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + +_____ + +openssl/openssl, https://github.com/openssl/openssl + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + +_____ + +Tencent/rapidjson, https://github.com/Tencent/rapidjson + +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Open Source Software Licensed Under the JSON License: +-------------------------------------------------------------------- + +json.org +Copyright (c) 2002 JSON.org +All Rights Reserved. + +JSON_checker +Copyright (c) 2002 JSON.org +All Rights Reserved. + + +Terms of the JSON License: +--------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +_____ + +boostorg/boost, https://github.com/boostorg/boost + +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + +_____ + +libb64/libb64, https://github.com/libb64/libb64 + +Copyright-Only Dedication (based on United States law) or Public Domain Certification + +The person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below. + +A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain. + +Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. + +Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. + +_____ + +posix pthread library, https://sourceforge.net/projects/pthreads4w + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +_____ + +Triton Inference Server & Client, https://github.com/triton-inference-server + +Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of NVIDIA CORPORATION nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +_____ + +microsoft/mimalloc, https://github.com/microsoft/mimalloc + +MIT License + +Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +_____ + +TensorFlow.js + +https://github.com/tensorflow/tfjs + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +—— + +curl/curl + +https://github.com/curl + +COPYRIGHT AND PERMISSION NOTICE + +Copyright (C) Daniel Stenberg, , and many +contributors, see the THANKS file. + +All rights reserved. + +Permission to use, copy, modify, and distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright +notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall not +be used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization of the copyright holder. + +_____ + +Intel neural-compressor + +https://github.com/intel/neural-compressor + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + ============================================================================ + + Copyright 2016-2019 Intel Corporation + Copyright 2018 YANDEX LLC + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + This distribution includes third party software ("third party programs"). + This third party software, even if included with the distribution of + the Intel software, may be governed by separate license terms, including + without limitation, third party license terms, other Intel software license + terms, and open source software license terms. These separate license terms + govern your use of the third party programs as set forth in the + "THIRD-PARTY-PROGRAMS" file. + +_____ + +FlashAttention, https://github.com/Dao-AILab/flash-attention + +BSD 3-Clause License + +Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/runexamples/cpp/onnx/VERSION_NUMBER b/runexamples/cpp/onnx/VERSION_NUMBER new file mode 100644 index 0000000..4a02d2c --- /dev/null +++ b/runexamples/cpp/onnx/VERSION_NUMBER @@ -0,0 +1 @@ +1.16.2 diff --git a/runexamples/cpp/onnx/include/cpu_provider_factory.h b/runexamples/cpp/onnx/include/cpu_provider_factory.h new file mode 100644 index 0000000..2926786 --- /dev/null +++ b/runexamples/cpp/onnx/include/cpu_provider_factory.h @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#include "onnxruntime_c_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \param use_arena zero: false. non-zero: true. + */ +ORT_EXPORT +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena) +ORT_ALL_ARGS_NONNULL; + +#ifdef __cplusplus +} +#endif diff --git a/runexamples/cpp/onnx/include/onnxruntime_c_api.h b/runexamples/cpp/onnx/include/onnxruntime_c_api.h new file mode 100644 index 0000000..456a116 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_c_api.h @@ -0,0 +1,4550 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// See docs\c_cxx\README.md on generating the Doxygen documentation from this file + +/** \mainpage ONNX Runtime + * + * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models. + * + * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models. + * - \subpage c_cpp_api "Core C, C++ APIs" + * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training" + * + * \page c_cpp_api Core C, C++ APIs + *

C

+ * + * ::OrtApi - Click here to go to the structure with all C API functions. + * + *

C++

+ * + * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes + * + * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to + * automate memory management through standard C++ RAII principles. + * + * \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +#pragma once +#include +#include +#include + +/** \brief The API version defined in this header + * + * This value is used by some API functions to behave as this version of the header expects. + */ +#define ORT_API_VERSION 16 + +#ifdef __cplusplus +extern "C" { +#endif + +//! @} +// SAL2 Definitions +#ifndef _WIN32 +#define _In_ +#define _In_z_ +#define _In_opt_ +#define _In_opt_z_ +#define _Out_ +#define _Outptr_ +#define _Out_opt_ +#define _Inout_ +#define _Inout_opt_ +#define _Frees_ptr_opt_ +#define _Ret_maybenull_ +#define _Ret_notnull_ +#define _Check_return_ +#define _Outptr_result_maybenull_ +#define _In_reads_(X) +#define _Inout_updates_(X) +#define _Out_writes_(X) +#define _Inout_updates_all_(X) +#define _Out_writes_bytes_all_(X) +#define _Out_writes_all_(X) +#define _Success_(X) +#define _Outptr_result_buffer_maybenull_(X) +#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull)) +#else +#include +#define ORT_ALL_ARGS_NONNULL +#endif + +#ifdef _WIN32 +// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort. +// dllexport is not used, we use a .def file. +#ifdef ORT_DLL_IMPORT +#define ORT_EXPORT __declspec(dllimport) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL _stdcall +#define ORT_MUST_USE_RESULT +#define ORTCHAR_T wchar_t +#else +// To make symbols visible on macOS/iOS +#ifdef __APPLE__ +#define ORT_EXPORT __attribute__((visibility("default"))) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL +#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result)) +#define ORTCHAR_T char +#endif + +/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling. +/// All other strings are UTF-8 encoded, use char and std::string +#ifndef ORT_TSTR +#ifdef _WIN32 +#define ORT_TSTR(X) L##X +// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO. +#define ORT_TSTR_ON_MACRO(X) L"" X +#else +#define ORT_TSTR(X) X +#define ORT_TSTR_ON_MACRO(X) X +#endif +#endif + +// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro. +// Otherwise, ORT_FILE is equivalent to __FILE__. +#ifndef ORT_FILE +#define ORT_FILE_INTERNAL(x) ORT_TSTR(x) +#define ORT_FILE ORT_FILE_INTERNAL(__FILE__) +#endif + +// Any pointer marked with _In_ or _Out_, cannot be NULL. + +// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation +// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that. +// for ReleaseXXX(...) functions, they can accept NULL pointer. + +#ifdef __cplusplus +// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept. +// Such complex condition is needed because compilers set __cplusplus value differently. +#ifndef __has_feature +#define __has_feature(x) 0 +#endif +#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept))) +#define NO_EXCEPTION noexcept +#else +#define NO_EXCEPTION throw() +#endif +#else +#define NO_EXCEPTION +#endif + +// __VA_ARGS__ on Windows and Linux are different +#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_API_STATUS(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \ + NO_EXCEPTION ORT_MUST_USE_RESULT + +// XXX: Unfortunately, SAL annotations are known to not work with function pointers +#define ORT_API2_STATUS(NAME, ...) \ + _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT + +// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT +#define ORT_API_STATUS_IMPL(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input) + +#ifdef __DOXYGEN__ +#undef ORT_API_STATUS +#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_API2_STATUS +#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_CLASS_RELEASE +#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input) +#undef NO_EXCEPTION +#define NO_EXCEPTION +#endif +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +/** Copied from TensorProto::DataType + * Currently, Ort doesn't support complex64, complex128 + */ +typedef enum ONNXTensorElementDataType { + ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string + ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16, + ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision + // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ // Non-IEEE floating-point format based on IEEE754 single-precision +} ONNXTensorElementDataType; + +// Synced with onnx TypeProto oneof +typedef enum ONNXType { + ONNX_TYPE_UNKNOWN, + ONNX_TYPE_TENSOR, + ONNX_TYPE_SEQUENCE, + ONNX_TYPE_MAP, + ONNX_TYPE_OPAQUE, + ONNX_TYPE_SPARSETENSOR, + ONNX_TYPE_OPTIONAL +} ONNXType; + +// These types are synced with internal +// SparseFormatFlags +typedef enum OrtSparseFormat { + ORT_SPARSE_UNDEFINED = 0, + ORT_SPARSE_COO = 0x1, + ORT_SPARSE_CSRC = 0x2, + ORT_SPARSE_BLOCK_SPARSE = 0x4 +} OrtSparseFormat; + +// Enum allows to query sparse tensor indices +enum OrtSparseIndicesFormat { + ORT_SPARSE_COO_INDICES, + ORT_SPARSE_CSR_INNER_INDICES, + ORT_SPARSE_CSR_OUTER_INDICES, + ORT_SPARSE_BLOCK_SPARSE_INDICES +}; + +/** \brief Logging severity levels + * + * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show. + */ +typedef enum OrtLoggingLevel { + ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe). + ORT_LOGGING_LEVEL_INFO, ///< Informational messages. + ORT_LOGGING_LEVEL_WARNING, ///< Warning messages. + ORT_LOGGING_LEVEL_ERROR, ///< Error messages. + ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe). +} OrtLoggingLevel; + +typedef enum OrtErrorCode { + ORT_OK, + ORT_FAIL, + ORT_INVALID_ARGUMENT, + ORT_NO_SUCHFILE, + ORT_NO_MODEL, + ORT_ENGINE_ERROR, + ORT_RUNTIME_EXCEPTION, + ORT_INVALID_PROTOBUF, + ORT_MODEL_LOADED, + ORT_NOT_IMPLEMENTED, + ORT_INVALID_GRAPH, + ORT_EP_FAIL, +} OrtErrorCode; + +typedef enum OrtOpAttrType { + ORT_OP_ATTR_UNDEFINED = 0, + ORT_OP_ATTR_INT, + ORT_OP_ATTR_INTS, + ORT_OP_ATTR_FLOAT, + ORT_OP_ATTR_FLOATS, + ORT_OP_ATTR_STRING, + ORT_OP_ATTR_STRINGS, +} OrtOpAttrType; + +//! @} +#define ORT_RUNTIME_CLASS(X) \ + struct Ort##X; \ + typedef struct Ort##X Ort##X; + +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ +// The actual types defined have an Ort prefix +ORT_RUNTIME_CLASS(Env); +ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success +ORT_RUNTIME_CLASS(MemoryInfo); +ORT_RUNTIME_CLASS(IoBinding); +ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) +ORT_RUNTIME_CLASS(Value); +ORT_RUNTIME_CLASS(RunOptions); +ORT_RUNTIME_CLASS(TypeInfo); +ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo); +ORT_RUNTIME_CLASS(MapTypeInfo); +ORT_RUNTIME_CLASS(SequenceTypeInfo); +ORT_RUNTIME_CLASS(OptionalTypeInfo); +ORT_RUNTIME_CLASS(SessionOptions); +ORT_RUNTIME_CLASS(CustomOpDomain); +ORT_RUNTIME_CLASS(ModelMetadata); +ORT_RUNTIME_CLASS(ThreadPoolParams); +ORT_RUNTIME_CLASS(ThreadingOptions); +ORT_RUNTIME_CLASS(ArenaCfg); +ORT_RUNTIME_CLASS(PrepackedWeightsContainer); +ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2); +ORT_RUNTIME_CLASS(CUDAProviderOptionsV2); +ORT_RUNTIME_CLASS(CANNProviderOptions); +ORT_RUNTIME_CLASS(DnnlProviderOptions); +ORT_RUNTIME_CLASS(Op); +ORT_RUNTIME_CLASS(OpAttr); +ORT_RUNTIME_CLASS(Logger); + +#ifdef _WIN32 +typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr; +#else +typedef OrtStatus* OrtStatusPtr; +#endif + +/** \brief Memory allocation interface + * + * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators. + * + * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed. + */ +typedef struct OrtAllocator { + uint32_t version; ///< Must be initialized to ORT_API_VERSION + void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes + void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p); ///< Free a block of memory previously allocated with OrtAllocator::Alloc + const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_); ///< Return a pointer to an ::OrtMemoryInfo that describes this allocator +} OrtAllocator; + +typedef void(ORT_API_CALL* OrtLoggingFunction)( + void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location, + const char* message); + +/** \brief Graph optimization level + * + * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels + * for an in-depth understanding of the Graph Optimization Levels. + */ +typedef enum GraphOptimizationLevel { + ORT_DISABLE_ALL = 0, + ORT_ENABLE_BASIC = 1, + ORT_ENABLE_EXTENDED = 2, + ORT_ENABLE_ALL = 99 +} GraphOptimizationLevel; + +typedef enum ExecutionMode { + ORT_SEQUENTIAL = 0, + ORT_PARALLEL = 1, +} ExecutionMode; + +/** \brief Language projection identifiers + * /see OrtApi::SetLanguageProjection + */ +typedef enum OrtLanguageProjection { + ORT_PROJECTION_C = 0, + ORT_PROJECTION_CPLUSPLUS = 1, + ORT_PROJECTION_CSHARP = 2, + ORT_PROJECTION_PYTHON = 3, + ORT_PROJECTION_JAVA = 4, + ORT_PROJECTION_WINML = 5, + ORT_PROJECTION_NODEJS = 6, +} OrtLanguageProjection; + +struct OrtKernelInfo; +typedef struct OrtKernelInfo OrtKernelInfo; +struct OrtKernelContext; +typedef struct OrtKernelContext OrtKernelContext; +struct OrtCustomOp; +typedef struct OrtCustomOp OrtCustomOp; + +typedef enum OrtAllocatorType { + OrtInvalidAllocator = -1, + OrtDeviceAllocator = 0, + OrtArenaAllocator = 1 +} OrtAllocatorType; + +/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider. + */ +// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc +typedef enum OrtMemType { + OrtMemTypeCPUInput = -2, ///< Any CPU memory used by non-CPU execution provider + OrtMemTypeCPUOutput = -1, ///< CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeCPU = OrtMemTypeCPUOutput, ///< Temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeDefault = 0, ///< The default allocator for execution provider +} OrtMemType; + +/** \brief This mimics OrtDevice type constants so they can be returned in the API + */ +typedef enum OrtMemoryInfoDeviceType { + OrtMemoryInfoDeviceType_CPU = 0, + OrtMemoryInfoDeviceType_GPU = 1, + OrtMemoryInfoDeviceType_FPGA = 2 +} OrtMemoryInfoDeviceType; + +/** \brief Algorithm to use for cuDNN Convolution Op + */ +typedef enum OrtCudnnConvAlgoSearch { + OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx + OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7 + OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM +} OrtCudnnConvAlgoSearch; + +/** \brief CUDA Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA + */ +typedef struct OrtCUDAProviderOptions { +#ifdef __cplusplus + OrtCUDAProviderOptions() + : device_id{}, + cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief CUDA device Id + * Defaults to 0. + */ + int device_id; + + /** \brief CUDA Convolution algorithm search configuration. + * See enum OrtCudnnConvAlgoSearch for more details. + * Defaults to OrtCudnnConvAlgoSearchExhaustive. + */ + OrtCudnnConvAlgoSearch cudnn_conv_algo_search; + + /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief CUDA memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overriden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overriden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtCUDAProviderOptions; + +/** \brief ROCM Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM + */ +typedef struct OrtROCMProviderOptions { +#ifdef __cplusplus + OrtROCMProviderOptions() + : device_id{}, + miopen_conv_exhaustive_search{0}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief ROCM device Id + * Defaults to 0. + */ + int device_id; + + /** \brief ROCM MIOpen Convolution algorithm exaustive search option. + * Defaults to 0 (false). + */ + int miopen_conv_exhaustive_search; + + /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief ROCM memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overriden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overriden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtROCMProviderOptions; + +/** \brief TensorRT Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + */ +typedef struct OrtTensorRTProviderOptions { + int device_id; ///< CUDA device id (0 = default device) + int has_user_compute_stream; // indicator of user specified CUDA compute stream. + void* user_compute_stream; // user specified CUDA compute stream. + int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability + int trt_min_subgraph_size; // minimum size of TensorRT subgraphs + size_t trt_max_workspace_size; // maximum workspace size for TensorRT. + int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true + int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true + const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name. + int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true + int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true + int trt_dla_core; // DLA core number. Default 0 + int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true + int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true + const char* trt_engine_cache_path; // specify engine cache path + int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true + const char* trt_engine_decryption_lib_path; // specify engine decryption library path + int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true + // This is the legacy struct and don't add new fields here. + // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h + // For non-string field, need to create a new separate api to handle it. +} OrtTensorRTProviderOptions; + +/** \brief MIGraphX Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + */ +typedef struct OrtMIGraphXProviderOptions { + int device_id; // hip device id. + int migraphx_fp16_enable; // enable MIGraphX FP16 precision. Default 0 = false, nonzero = true + int migraphx_int8_enable; // enable MIGraphX INT8 precision. Default 0 = false, nonzero = true +} OrtMIGraphXProviderOptions; + +/** \brief OpenVINO Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO + */ +typedef struct OrtOpenVINOProviderOptions { +#ifdef __cplusplus + OrtOpenVINOProviderOptions() : device_type{}, + enable_vpu_fast_compile{}, + device_id{}, + num_of_threads{}, + cache_dir{}, + context{}, + enable_opencl_throttling{}, + enable_dynamic_shapes{} {} +#endif + /** \brief Device type string + * + * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16" + */ + const char* device_type; + unsigned char enable_vpu_fast_compile; ///< 0 = disabled, nonzero = enabled + const char* device_id; + size_t num_of_threads; ///< 0 = Use default number of threads + const char* cache_dir; // path is set to empty by default + void* context; + unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled + unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled +} OrtOpenVINOProviderOptions; + +struct OrtApi; +typedef struct OrtApi OrtApi; + +struct OrtTrainingApi; +typedef struct OrtTrainingApi OrtTrainingApi; + +/** \brief The helper interface to get the right version of OrtApi + * + * Get a pointer to this structure through ::OrtGetApiBase + */ +struct OrtApiBase { + /** \brief Get a pointer to the requested version of the ::OrtApi + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime + * older than the version created with this header file. + * + * One can call GetVersionString() to get the version of the Onnxruntime library for logging + * and error reporting purposes. + */ + const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; + + /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1") + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + */ + const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION; +}; + +typedef struct OrtApiBase OrtApiBase; + +/** \brief The Onnxruntime library's entry point to access the C API + * + * Call this to get the a pointer to an ::OrtApiBase + */ +ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION; + +/** \brief Thread work loop function + * + * Onnxruntime will provide the working loop on custom thread creation + * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn + */ +typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param); + +typedef const struct OrtCustomHandleType { + char __place_holder; +}* OrtCustomThreadHandle; + +/** \brief Ort custom thread creation function + * + * The function should return a thread handle to be used in onnxruntime thread pools + * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread + */ +typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param); + +/** \brief Custom thread join function + * + * Onnxruntime thread pool destructor will call the function to join a custom thread. + * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn + */ +typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle); + +typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api); + +/** \brief Callback function for RunAsync + * + * \param[in] user_data User specific data that passed back to the callback + * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr + * \param[out] num_outputs Number of outputs, on error, the value will be zero + * \param[out] status On error, status will provide details + */ +typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status); + +/** \brief The C API + * + * All C API functions are defined inside this structure as pointers to functions. + * Call OrtApiBase::GetApi to get a pointer to it + * + * \nosubgrouping + */ +struct OrtApi { + /// \name OrtStatus + /// @{ + + /** + * \brief Create an OrtStatus from a null terminated string + * + * \param[in] code + * \param[in] msg A null-terminated string. Its contents will be copied. + * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus + */ + OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get OrtErrorCode from OrtStatus + * + * \param[in] status + * \return OrtErrorCode that \p status was created with + */ + OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get error string from OrtStatus + * + * \param[in] status + * \return The error message inside the `status`. Do not free the returned value. + */ + const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Create an OrtEnv + * + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLogger, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, + OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Enable Telemetry + * + * \note Telemetry events are on by default since they are lightweight + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env); + /** \brief Disable Telemetry + * + * \see OrtApi::EnableTelemetryEvents + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create an OrtSession from a model file + * + * \param[in] env + * \param[in] model_path + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + // TODO: document the path separator convention? '/' vs '\' + // TODO: should specify the access characteristics of model_path. Is this read only during the + // execution of CreateSession, or does the OrtSession retain a handle to the file/directory + // and continue to access throughout the OrtSession lifetime? + // What sort of access is needed to model_path : read or read/write? + ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession from memory + * + * \param[in] env + * \param[in] model_data + * \param[in] model_data_length + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Run the model in an ::OrtSession + * + * Will not return until the model run has completed. Multiple threads might be used to run the model based on + * the options in the ::OrtSession and settings used when creating the ::OrtEnv + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] inputs Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be + * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers + * to them will be set into the `outputs` array. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** outputs); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Create an ::OrtSessionOptions object + * + * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these + * functions to enable them in the session:
+ * OrtSessionOptionsAppendExecutionProvider_CPU
+ * OrtSessionOptionsAppendExecutionProvider_CUDA
+ * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)
+ * The order they are called indicates the preference order as well. In other words call this method + * on your most preferred execution provider first followed by the less preferred ones. + * If none are called Ort will use its internal CPU execution provider. + * + * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options); + + /** \brief Set filepath to save optimized model after graph level transformations + * + * \param[in] options + * \param[in] optimized_model_filepath + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options, + _In_ const ORTCHAR_T* optimized_model_filepath); + + /** \brief Create a copy of an existing ::OrtSessionOptions + * + * \param[in] in_options OrtSessionOptions to copy + * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options, + _Outptr_ OrtSessionOptions** out_options); + + /** \brief Set execution mode + * + * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model + * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance. + * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details. + * + * \param[in] options + * \param[in] execution_mode + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode); + + /** \brief Enable profiling for a session + * + * \param[in] options + * \param[in] profile_file_prefix + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix); + + /** \brief Disable profiling for a session + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory pattern optimization + * + * The idea is if the input shapes are the same, we could trace the internal memory allocation + * and generate a memory pattern for future request. So next time we could just do one allocation + * with a big chunk for all the internal memory allocation. + * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode) + * + * \see OrtApi::DisableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory pattern optimization + * + * \see OrtApi::EnableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory arena on CPU + * + * Arena may pre-allocate memory for future usage. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory arena on CPU + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Set session log id + * + * \param[in] options + * \param[in] logid The log identifier. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid); + + /** \brief Set session log verbosity level + * + * Applies to session load, initialization, etc + * + * \param[in] options + * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level); + + /** \brief Set session log severity level + * + * \param[in] options + * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level); + + /** \brief Set the optimization level to apply when loading a graph + * + * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation + * \param[in,out] options The session options object + * \param[in] graph_optimization_level The optimization level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options, + GraphOptimizationLevel graph_optimization_level); + + /** \brief Sets the number of threads used to parallelize the execution within nodes + * + * When running a single node operation, ex. add, this sets the maximum number of threads to use. + * + * \note If built with OpenMP, this has no effect on the number of threads used. In this case + * use the OpenMP env variables to configure the number of intra op num threads. + * + * \param[in] options + * \param[in] intra_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads); + + /** \brief Sets the number of threads used to parallelize the execution of the graph + * + * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel. + * + * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1. + * + * \param[in] options + * \param[in] inter_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads); + + /// @} + /// \name OrtCustomOpDomain + /// @{ + + /** \brief Create a custom op domain + * + * \param[in] domain + * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out); + + /** \brief Add a custom op to a custom op domain + * + * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released + * + * \param[in] custom_op_domain + * \param[in] op + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add custom op domain to a session options + * + * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released + * + * \param[in] options + * \param[in] custom_op_domain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain); + + /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2. + * + * Registers custom ops from a shared library. + * + * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in + * session options are destroyed, or if an error occurs and it is non null. + * + * \param[in] options + * \param[in] library_path + * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Get input count for a session + * + * This number must also match the number of inputs passed to OrtApi::Run + * + * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of inputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get output count for a session + * + * This number must also match the number of outputs returned by OrtApi::Run + * + * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of outputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get overridable initializer count + * + * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName + * + * \param[in] session + * \param[in] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get input type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get output type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get overridable initializer type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get input name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get output name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get overridable initializer name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Create an OrtRunOptions + * + * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out); + + /** \brief Set per-run log verbosity level + * + * \see OrtApi::RunOptionsGetRunLogVerbosityLevel + * + * \param[in] options + * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level); + + /** \brief Set per-run log severity level + * + * \see OrtApi::RunOptionsGetRunLogSeverityLevel + * + * \param[in] options + * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level); + + /** \brief Set per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsGetRunTag + * + * \param[in] options + * \param[in] run_tag The run tag. + */ + ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag); + + /** \brief Get per-run log verbosity level + * + * \see OrtApi::RunOptionsSetRunLogVerbosityLevel + * + * \param[in] options + * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, + _Out_ int* log_verbosity_level); + + /** \brief Get per-run log severity level + * + * \see OrtApi::RunOptionsSetRunLogSeverityLevel + * + * \param[in] options + * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level); + + /** \brief Get per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsSetRunTag + * + * \param[in] options + * \param[out] run_tag The run tag. + * Do not free this value, it is owned by `options`. It will be invalidated if the run tag + * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed. + */ + ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag); + + /** \brief Set terminate flag + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options); + + /** \brief Clears the terminate flag + * + * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Create a tensor + * + * Create a tensor using a supplied ::OrtAllocator + * + * \param[in] allocator + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** \brief Create a tensor backed by a user supplied buffer + * + * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after. + * p_data is owned by caller. ReleaseValue won't release p_data. + * + * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param[in] p_data Pointer to the data buffer. + * \param[in] p_data_len The number of bytes in the data buffer. + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type The data type. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type, + _Outptr_ OrtValue** out); + + /** \brief Return if an ::OrtValue is a tensor type + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Get a pointer to the raw data inside a tensor + * + * Used to read/write/modify the internal tensor data directly. + * \note The returned pointer is valid until the \p value is destroyed. + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Filled in with a pointer to the internal storage + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out); + + /** \brief Set all strings at once in a string tensor + * + * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s An array of strings. Each string in this array must be null terminated. + * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len); + + /** \brief Get total byte length for all strings in a string tensor + * + * Typically used with OrtApi::GetStringTensorContent + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[out] len Total byte length of all strings (does not include trailing nulls) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len); + + /** \brief Get all strings from a string tensor + * + * An example of the results:
+ * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }
+ * \p s must have a size of 11 bytes
+ * \p offsets must have 4 elements
+ * After the call, these values will be filled in:
+ * \p s will contain "Thisisatest"
+ * \p offsets will contain { 0, 4, 6, 7 }
+ * The length of the last string is just s_len - offsets[last] + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated. + * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength) + * \param[out] offsets Array of start offsets into the strings written to \p s + * \param[in] offsets_len Number of elements in offsets + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s, + size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out Do not free this value, it will be valid until type_info is freed. + * If type_info does not represent tensor, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out); + + /** \brief Get ::ONNXType from ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + + /** \brief Create an ::OrtTensorTypeAndShapeInfo object + * + * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Set element type in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] type + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type); + + /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_values Array with `dim_count` elements. Can contain negative values. + * \param[in] dim_count Number of elements in `dim_values` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count); + + /** \brief Get element type in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::SetTensorElementType + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::GetDimensions + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo + * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, + size_t dim_values_length); + + /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names + * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length); + + /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo + * + * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other). + * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1. + * + * Examples:
+ * [] = 1
+ * [1,3,4] = 12
+ * [2,0,4] = 0
+ * [-1,3,4] = -1
+ * + * \param[in] info + * \param[out] out Number of elements + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get type and shape information from a tensor ::OrtValue + * + * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure + * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Get type information of an OrtValue + * + * \param[in] value + * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out); + + /** \brief Get ONNXType of an ::OrtValue + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtMemoryInfo + /// @{ + + /** \brief Create an ::OrtMemoryInfo + * + * \param[in] name + * \param[in] type + * \param[in] id + * \param[in] mem_type + * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id, + enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out); + + /** \brief Create an ::OrtMemoryInfo for CPU memory + * + * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0. + * + * \param[in] type + * \param[in] mem_type + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type, + _Outptr_ OrtMemoryInfo** out); + + /** \brief Compare ::OrtMemoryInfo objects for equality + * + * Compares all settings of each ::OrtMemoryInfo for equality + * + * \param[in] info1 + * \param[in] info2 + * \param[out] out Set to 0 if equal, -1 if not equal + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out); + + /** \brief Get name from ::OrtMemoryInfo + * + * \param[in] ptr + * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out); + + /** \brief Get the id from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out); + + /** \brief Get the ::OrtMemType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out); + + /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out); + + /// @} + /// \name OrtAllocator + /// @{ + + /// \brief Calls OrtAllocator::Alloc function + ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out); + /// \brief Calls OrtAllocator::Free function + ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p); + /// \brief Calls OrtAllocator::Info function + ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out); + + /** \brief Get the default allocator + * + * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator. + * + * \param[out] out Returned value should NOT be freed + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Override session symbolic dimensions + * + * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable + * optimizations that can take advantage of fixed values (such as memory planning, etc) + * + * \param[in] options + * \param[in] dim_denotation + * \param[in] dim_value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation, + _In_ int64_t dim_value); + + /// @} + /// \name OrtValue + /// @{ + + /* Internal information (not seen in Doxygen) + * + * APIs to support non-tensor types - map and sequence. + * Currently only the following types are supported + * Note: the following types should be kept in sync with data_types.h + * Map types + * ========= + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * + * Sequence types + * ============== + * std::vector + * std::vector + * std::vector + * std::vector + * std::vector> + * std::vector + */ + + /** \brief Get non tensor data from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values + * separately. Use index=0 to retrieve keys and index=1 to retrieve values. + * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element + * of the sequence. + * + * \param[in] value + * \param[in] index See above for usage based on `value` type + * \param[in] allocator Allocator used to allocate ::OrtValue + * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** out); + + /** \brief Get non tensor value count from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE + * the number of elements in the sequence will be returned + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out); + + /** \brief Create a map or sequence ::OrtValue + * + * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s + * representing keys and values.
+ * + * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the + * sequence. 'in' should be an array of N ::OrtValue%s. + * + * \param[in] in See above for details + * \param[in] num_values + * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values, + enum ONNXType value_type, _Outptr_ OrtValue** out); + + /** \brief Create an opaque (custom user defined type) ::OrtValue + * + * Constructs an ::OrtValue that contains a value of non-standard type created for + * experiments or while awaiting standardization. ::OrtValue in this case would contain + * an internal representation of the Opaque type. Opaque types are distinguished from + * each other by two strings 1) domain and 2) type name. The combination of the two + * must be unique, so the type representation is properly identified internally. The combination + * must be properly registered from within ORT at both compile/run time or by another API. + * + * To construct the ::OrtValue pass domain and type names, also a pointer to a data container + * the type of which must be known to both ORT and the client program. That data container may or may + * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for + * verification purposes. + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] data_container User pointer Data to populate ::OrtValue + * \param[in] data_container_size Size in bytes of what `data_container` points to + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name, + _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out); + + /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue + * + * Copies internal data from an opaque value into a user provided buffer + * + * \see OrtApi::CreateOpaqueValue + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] in The opaque ::OrtValue + * \param[out] data_container Buffer to copy data into + * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in, + _Out_ void* data_container, size_t data_container_size); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get a float stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out); + + /** \brief Fetch a 64-bit int stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out); + + /** \brief Fetch a string stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the string + * attribute, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string attribute's size, + * the value of `size` is set to the true size of the string attribute, the provided memory + * is filled with the attribute's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string attribute's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string attribute + * and a failure status is returned.) + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * \param[in,out] size See above comments for details + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out, + _Inout_ size_t* size); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, get the input count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get the output count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get an input of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index, + _Out_ const OrtValue** out); + + /** \brief Used for custom operators, get an output of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index, + _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtEnv + /// @{ + ORT_CLASS_RELEASE(Env); + /// @} + /// \name OrtStatus + /// @{ + ORT_CLASS_RELEASE(Status); + /// @} + /// \name OrtMemoryInfo + /// @{ + ORT_CLASS_RELEASE(MemoryInfo); + /// @} + /// \name OrtSession + /// @{ + ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) + /// @} + /// \name OrtValue + /// @{ + ORT_CLASS_RELEASE(Value); + /// @} + /// \name OrtRunOptions + /// @{ + ORT_CLASS_RELEASE(RunOptions); + /// @} + /// \name OrtTypeInfo + /// @{ + ORT_CLASS_RELEASE(TypeInfo); + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + ORT_CLASS_RELEASE(TensorTypeAndShapeInfo); + /// @} + /// \name OrtSessionOptions + /// @{ + ORT_CLASS_RELEASE(SessionOptions); + /// @} + /// \name OrtCustomOpDomain + /// @{ + ORT_CLASS_RELEASE(CustomOpDomain); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get denotation from type information + * + * Augments ::OrtTypeInfo to return denotations on the type. + * + * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor. + * + * \param[in] type_info + * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free. + * \param[out] len Length in bytes of the string returned in `denotation` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation, + _Out_ size_t* len); + + /** \brief Get detailed map information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map. + * The OrtMapTypeInfo has additional information about the map's key type and value type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[out] type_info + * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info + * does not contain a map, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtMapTypeInfo** out); + + /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo + * + * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence. + * The ::OrtSequenceTypeInfo has additional information about the sequence's element type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] type_info + * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info + * doesn not contain a sequence, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + + /** \brief Get key type from an ::OrtMapTypeInfo + * + * Key types are restricted to being scalar types. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] map_type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get the value type from an ::OrtMapTypeInfo + * + * \param[in] map_type_info + * \param[out] type_info + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + + /** \brief Get element type from an ::OrtSequenceTypeInfo + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] sequence_type_info + * \param[out] type_info + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info, + _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + ORT_CLASS_RELEASE(MapTypeInfo); + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + ORT_CLASS_RELEASE(SequenceTypeInfo); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief End profiling and return filename of the profile data + * + * Profiling is turned on through OrtApi::EnableProfiling + * + * \param[in] session + * \param[in] allocator + * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out); + + /** \brief Get ::OrtModelMetadata from an ::OrtSession + * + * \param[in] session + * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** \brief Get `producer name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `graph name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `domain` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator, + _Outptr_ char** value); + + /** \brief Get `description` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[in] key Null terminated string + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * `value` will be set to nullptr if the given key is not found in the custom metadata map. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value); + + /** \brief Get version number from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[out] value Set to the version number + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value); + + ORT_CLASS_RELEASE(ModelMetadata); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * Create an environment with global threadpools that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid, + _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Use global thread pool on a session + * + * Disable using per session thread pool and use the shared global threadpool. + * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Create an ::OrtThreadingOptions + * + * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out); + + ORT_CLASS_RELEASE(ThreadingOptions); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`. + * The strings and the pointer array must be freed using `allocator` + * `keys` will be set to nullptr if the custom metadata map is empty. + * \param[out] num_keys Set to the number of elements in the `keys` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * + * Override symbolic dimensions (by specific name strings) with actual values + * if known at session initialization time to enable optimizations that can + * take advantage of fixed values (such as memory planning, etc) + * + */ + ORT_API2_STATUS(AddFreeDimensionOverrideByName, + _Inout_ OrtSessionOptions* options, _In_ const char* dim_name, + _In_ int64_t dim_value); + + /// @} + /// \name Misc + /// @{ + + /** \brief Get the names of all available providers + * + * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies. + * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options. + * + * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the + * array itself must be freed using OrtApi::ReleaseAvailableProviders + * \param[out] provider_length Set to the number of entries in the `out_ptr` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length); + + /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail + * so you can rely on it in a noexcept code. + * + * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders. + * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr, + _In_ int providers_length); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get the length of a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] index Index of the string in the tensor + * \param[out] out Set to number of bytes of the string element + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out); + + /** \brief Get a single string from a string tensor + * + * \param[in] value A string tensor + * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength. + * \param[in] index Index of the string in the tensor + * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s); + + /** \brief Set a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] s A null terminated UTF-8 encoded string + * \param[in] index Index of the string in the tensor to set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Set a session configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value. + * + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo + * + * \param[in] session + * \param[in] mem_info valid ::OrtMemoryInfo instance + * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info, + _Outptr_ OrtAllocator** out); + + /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator + */ + ORT_CLASS_RELEASE(Allocator); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Run a model using Io Bindings for the inputs & outputs + * + * \see OrtApi::Run + * + * \param[in] session + * \param[in] run_options + * \param[in] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr); + + /** \brief Create an ::OrtIoBinding instance + * + * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names. + * Thus if you want to use a raw on device buffer as input or output you can avoid + * extra copy during runtime. + * + * \param[in] session + * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out); + + /// @} + /// \name OrtIoBinding + /// @{ + + /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding + */ + ORT_CLASS_RELEASE(IoBinding); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding input + * + * When using OrtApi::RunWithBinding this value is used for the named input + * + * \param[in] binding_ptr + * \param[in] name Name for the model input + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding output + * + * When using OrtApi::RunWithBinding this value is used for the named output + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the model output name + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtIoBinding output to a device + * + * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo. + * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using + * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of + * memory within ::OrtValue ahead of time. + * + * \see OrtApi::RunWithBinding + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the device name + * \param[in] mem_info_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr); + + /** \brief Get the names of an ::OrtIoBinding's outputs + * + * Returns the names of the outputs in the order they were bound. This is useful after running the model + * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if + * the order of outputs and their names is not known. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths. + * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter. + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer` + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned, + * no memory allocation is performed and buffer and lengths are set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count); + + /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding + * + * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding + * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput + * or OrtApi::BindOutputToDevice. + * + * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed. + * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after + * all the ::OrtValue%s contained therein are individually released. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate output array + * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs. + * \param[out] output_count Set to number of ::OrtValue%s returned + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count); + + /** \brief Clears any previously set Inputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Clears any previously set Outputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Direct memory access to a specified tensor element + * + * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved + * + * This function only works for numeric type tensors (No strings, etc). + * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd. + * + * \param[in] value + * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape + * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape. + * \param[out] out Set to a pointer to the element specified + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an allocator and register it with the ::OrtEnv + * + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env ::OrtEnv instance + * \param[in] mem_info + * \param[in] arena_cfg Pass nullptr for defaults + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info, + _In_ const OrtArenaCfg* arena_cfg); + + /** \brief Set language projection + * + * Set the language projection for collecting telemetry data when Env is created. + * + * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also. + * + * \param[in] ort_env + * \param[in] projection + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Return the time that profiling was started + * + * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns + * + * \param[in] session + * \param[out] out nanoseconds of profiling's start time + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set global intra-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] intra_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads); + + /** \brief Set global inter-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] inter_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads); + + /** \brief Set global spin control options + * + * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Allow spinning of thread pools when their queues are empty. This will set the value for both + * inter_op and intra_op threadpools. + * + * \param[in] tp_options + * \param[in] allow_spinning Valid values are 0 or 1.
+ * 0 = It won't spin (recommended if CPU usage is high)
+ * 1 = Threadpool will spin to wait for queue to become non-empty + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add a pre-allocated initializer to a session + * + * If a model contains an initializer with a name that is same as the name passed to this call, + * ORT will use this initializer instance instead of deserializing one from the model file. This + * is useful when you want to share the same initializer across sessions. + * + * \param[in] options + * \param[in] name Null terminated string of the initializer name + * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be + * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object + * to which it is added. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name, + _In_ const OrtValue* val); + + /// @} + /// \name OrtEnv + /// @{ + + /** + * Create a custom environment with global threadpools and logger that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level, + _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA provider to session options + * + * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options); + + /** \brief Append ROCM execution provider to the session options + * + * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] rocm_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM, + _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options); + + /** \brief Append OpenVINO execution provider to the session options + * + * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. + * + * \param[in] options + * \param[in] provider_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO, + _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set threading flush-to-zero and denormal-as-zero + * + * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool. + * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy. + * + * \param[in] tp_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \deprecated Use OrtApi::CreateArenaCfgV2 + * + * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior + * + * \param[in] max_mem Use 0 to allow ORT to choose the default + * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default + * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default + * \param[in] out A pointer to an OrtArenaCfg instance + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, + int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out); + + ORT_CLASS_RELEASE(ArenaCfg); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * Use this to obtain the description of the graph present in the model + * (doc_string field of the GraphProto message within the ModelProto message). + * If it doesn't exist, an empty string will be returned. + * + * \param[in] model_metadata An instance of ::OrtModelMetadata + * \param[in] allocator Allocator used to allocate the string that will be returned back + * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT provider to session options + * + * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options); + + /// @} + /// \name Misc + /// @{ + + /** \brief Set current GPU device ID + * + * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less + * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is + * required to restrict execution to a single GPU. + * + * \param[in] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id); + + /** \brief Get current GPU device ID + * + * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm). + * + * \see OrtApi::SetCurrentGpuDeviceId + * + * \param[out] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out, _Inout_ size_t* size); + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out, _Inout_ size_t* size); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \brief Create an ::OrtArenaCfg + * + * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior. + * + * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the + * following parameters mean and how to choose these values.): + * "max_mem": Maximum memory that can be allocated by the arena based allocator. + * Use 0 for ORT to pick the best value. Default is 0. + * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested. + * Use -1 to allow ORT to choose the default. + * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * Ultimately, the first allocation size is determined by the allocation memory request. + * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after + * crossing which the current chunk is chunked into 2. + * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * "max_power_of_two_extend_bytes": The maximum enxtend size if arena strategy is `kNextPowerOfTwo`. + * It is not an allocation limit, it is only a limit for extention when requested byte is less than the limit. + * When requested bytes is more than the limit, allocator will still return as requested. + * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes. + * Ultimately, the allocation size is determined by the allocation memory request. + * Further allocation sizes are governed by the arena extend strategy. + * + * \param[in] arena_config_keys Keys to configure the arena + * \param[in] arena_config_values Values to configure the arena + * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values` + * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys, + _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys, + _Outptr_ OrtArenaCfg** out); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Set a single run configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value + * + * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtPrepackedWeightsContainer + /// @{ + + /** \brief Create an ::OrtPrepackedWeightsContainer + * + * This container will hold pre-packed buffers of shared initializers for sharing between sessions + * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers + * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container + * to sessions that you would like to share pre-packed buffers of shared initializers at session + * creation time. + * + * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out); + + /** \brief Release OrtPrepackedWeightsContainer instance + * + * \note instance must not be released until the sessions using it are released + */ + ORT_CLASS_RELEASE(PrepackedWeightsContainer); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create session with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSession except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env OrtEnv instance instance + * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise) + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /** \brief Create session from memory with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env + * \param[in] model_data Array of bytes holding the model + * \param[in] model_data_length Number of bytes in `model_data_model` + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT execution provider to the session options + * + * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an + * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2 + * which must be created with OrtApi::CreateTensorRTProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions + * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions. + * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options); + + /// @} + /// \name OrtTensorRTProviderOptionsV2 + /// @{ + + /** \brief Create an OrtTensorRTProviderOptionsV2 + * + * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out); + + /** \brief Set options in a TensorRT Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2 + * and value should be its related range. + * + * For example, key="trt_max_workspace_size" and value="2147483648" + * + * \param[in] tensorrt_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized TensorRT provider options string. + * + * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......" + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtTensorRTProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + */ + void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Enable custom operators + * + * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Register a custom allocator + * + * Enables sharing between multiple sessions that use the same env instance. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except + * instead of ORT creating an allocator based on provided info, in this case + * ORT uses the user-provided custom allocator. + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env + * \param[in] allocator User provided allocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator); + + /** \brief Unregister a custom allocator + * + * It is an error if you provide an ::OrtMemoryInfo not corresponding to any + * registered allocators for sharing. + * + * \param[in] env + * \param[in] mem_info + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env, + _In_ const OrtMemoryInfo* mem_info); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise + * + * \param[in] value existing ::OrtValue + * \param[out] out unless an error occurs, contains 1 iff the value contains an instance + * of sparse tensor or 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Create an ::OrtValue with a sparse tensor that is empty. + * + * Use FillSparseTensor() functions to populate sparse tensor with non-zero values and + * format specific indices data. + * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value + * if any was allocated. + * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed + * by FillSparseTensor() APIs. The lifespan of the allocator instance must eclipse the lifespan + * this sparse tensor instance as the same allocator will be used to free memory. + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape, + size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values pointer to an array of values. For strings, pass const char**. + * \param[in] indices_data pointer to a location of COO indices + * \param[in] indices_num number of COO indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_data, size_t indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values - pointer to an array of values. For strings, pass const char**. + * \param[in] inner_indices_data pointer to a location of CSR inner indices + * \param[in] inner_indices_num number of CSR inner indices + * \param[in] outer_indices_data pointer to a location of CSR outer indices + * \param[in] outer_indices_num number of CSR outer indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* inner_indices_data, size_t inner_indices_num, + _In_ const int64_t* outer_indices_data, size_t outer_indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape + * \param[in] values_shape_len + * \param[in] values structure with values information + * \param[in] indices_shape_data pointer to a location of indices shape + * \param[in] indices_shape_len length of the block sparse indices shape + * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_shape_data, size_t indices_shape_len, + _In_ const int32_t* indices_data); + + /** + * Create an ::OrtValue with a sparse tensor. This is the first step. + * Next, use UseIndices() functions to supply sparse tensor with + * format specific indices data and set its sparse format to a specific enum value. + * This will not perform memory allocations. It will + * use supplied user buffer which should outlive the created sparse tensor. + * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer. + * This function can not be used to map strings from the user allocated memory. Strings must always be copied + * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data + * using appropriate Make*() function. + * + * \param[in] info memory info where sparse values reside. + * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero + * values, pass nullptr + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values, + * pass {0} shape. + * \param[in] values_shape_len number of values shape dimensions + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + _In_ const int64_t* dense_shape, size_t dense_shape_len, + _In_ const int64_t* values_shape, size_t values_shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This assigns Coo format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of + * indices_data buffer should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or + * be twice as number of nnz values for a 2-D indices {nnz, 2} + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num); + + /** + * The assigns CSR format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of + * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue. + * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or + * equal to rows + 1 of the dense shape. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num, + _Inout_ int64_t* outer_data, size_t outer_num); + + /** + * The assigns BlockSparse format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of + * indices_data buffer must eclipse the lifespan of this ::OrtValue. + * + * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors + * \param[in] indices_shape_len length of the indices shape + * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data); + + /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor. + * + * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor + * \param[out] out pointer to out parameter + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out); + + /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor. + * + * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor + * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*(). + * + * \param[in] ort_value an instance of ::OrtValue containing sparse tensor + * \param[out] out returns a pointer to values data. Do not attempt to free this ptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out); + + /** \brief Returns data type, shape for the type of indices specified by indices_format. + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse + * tensor does not contain. + * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns indices data for the type of the indices specified by indices_format + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain. + * \param[out] num_indices Pointer to where the number of indices entries is returned + * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices); + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None) + * Use this API to find if the optional type OrtValue is None or not. + * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue. + * For example, if you get an OrtValue that corresponds to Optional(tensor) and + * if HasValue() returns true, use it as tensor and so on. + + * \param[in] value Input OrtValue. + * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel + * \see ::OrtCustomOp + * \param[in] context OrtKernelContext instance + * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel. + * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to + * some other EP), then a nullptr is returned as the output param. + * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session. + * Only use it for custom kernel launching. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out); + + /// @} + /// \name GetTensorMemoryInfo + /// @{ + /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor + * \param[in] value ::OrtValue containing tensor. + * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info); + + /// @} + /// \name GetExecutionProviderApi + /// @{ + /** \brief Get a pointer to the requested version of the Execution Provider specific + * API extensions to the OrtApi + * \param[in] provider_name The name of the execution provider name. Currently only the following + * values are supported: "DML". + * \param[in] version Must be ::ORT_API_VERSION. + * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure. + * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML". + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api); + + /// @} + + /// \name SessionOptions + /// @{ + /** \brief Set custom thread creation function + * + * \param[in] options Session options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set creation options for custom thread + * + * \param[in] options Session options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function + * + * \param[in] options Session options + * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /// \name OrtThreadingOptions + /// @{ + /** \brief Set custom thread creation function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set custom thread creation options for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr); + + /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr); + + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA execution provider to the session options + * + * If CUDA is not available (due to a non CUDA enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an + * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2 + * which must be created with OrtApi::CreateCUDAProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions + * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions. + * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options); + + /// @} + /// \name OrtCUDAProviderOptionsV2 + /// @{ + + /** \brief Create an OrtCUDAProviderOptionsV2 + * + * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out); + + /** \brief Set options in a CUDA Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2 + * and value should be its related range. + * + * For example, key="device_id" and value="0" + * + * \param[in] cuda_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized CUDA provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtCUDAProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.11. + */ + void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input); + + /// @} + + /** \brief Append MIGraphX provider to session options + * + * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] migraphx_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX, + _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options); + + /** \brief Replace initialized Tensors with external data with the data provided in initializers. + * + * The function will find the initialized TensorProtos with external data in the graph with the provided names and + * replace them with the provided tensors. The API verifies that the TensorProto being replaced + * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement + * will occur before any of the optimizations take place. The data will be copied into the graph + * since TensorProto can't refer to the user provided buffers. + * + * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed + * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated + * and the SessionOptions instance that refers to them can be destroyed. + * + * \param[in] options + * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names. + * \param[in] initializers Array of ::OrtValue type + * \param[in] initializers_num Number of elements in the initializer_names and initializers + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.12. + */ + ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options, + _In_reads_(input_len) const char* const* initializer_names, + _In_reads_(input_len) const OrtValue* const* initializers, size_t initializers_num); + + /** \brief: Create attribute of onnxruntime operator + * + * \param[in] name Name of the attribute + * \param[in] data Data content of the attribute + * \param[in] len Number of bytes stored in data + * \param[in] type Data type + * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOpAttr, + _In_ const char* name, + _In_ const void* data, + _In_ int len, + _In_ OrtOpAttrType type, + _Outptr_ OrtOpAttr** op_attr); + + /* \brief: Release op attribute + * + * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(OpAttr); + + /** \brief: Create onnxruntime native operator + * + * \param[in] info Kernel info + * \param[in] op_name Operator name + * \param[in] domain Operator domain + * \param[in] version Operator opset version + * \param[in] type_constraint_names Name of the type contraints, such as "T" or "T1" + * \param[in] type_constraint_values Type of each contraints + * \param[in] type_constraint_count Number of contraints + * \param[in] attr_values Attributes used to initialize the operator + * \param[in] attr_count Number of the attributes + * \param[in] input_count Number of inputs + * \param[in] output_count Number of outputs + * \param[out] ort_op Operator that has been created + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOp, + _In_ const OrtKernelInfo* info, + _In_z_ const char* op_name, + _In_z_ const char* domain, + int version, + _In_reads_(type_constraint_count) const char** type_constraint_names, + _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values, + int type_constraint_count, + _In_reads_(attr_count) const OrtOpAttr* const* attr_values, + int attr_count, + int input_count, + int output_count, + _Outptr_ OrtOp** ort_op); + + /** \brief: Invoke the operator created by OrtApi::CreateOp + * The inputs must follow the order as specified in onnx specification + * + * \param[in] context Kernel context + * \param[in] ort_op Operator that has been created + * \param[in] input_values Array of inputs + * \param[in] input_count Number of inputs + * \param[in] output_values Array of outputs + * \param[in] output_count Number of outputs + * + * \since Version 1.12. + */ + ORT_API2_STATUS(InvokeOp, + _In_ const OrtKernelContext* context, + _In_ const OrtOp* ort_op, + _In_ const OrtValue* const* input_values, + _In_ int input_count, + _Inout_ OrtValue* const* output_values, + _In_ int output_count); + + /* \brief: Release an onnxruntime operator + * + * \param[in] Op Operator created by OrtApi::CreateOp + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(Op); + + /** \brief: Append execution provider to the session options. + * \param[in] options + * \param[in] provider_name - provider to add. + * \param[in] provider_options_keys - keys to configure the provider options + * \param[in] provider_options_values - values to configure the provider options + * \param[in] num_keys - number of keys passed in + * + * Currently supported providers: + * QNN + * SNPE + * XNNPACK + * + * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_ function + * that should be used to add it. + * + * QNN supported keys: + * "backend_path": file path to QNN backend library. + * "qnn_context_cache_enable": 1 to enable QNN graph creation from cached QNN context file. If it's enabled: QNN EP will + * load from cached QNN context binary if it exist. It will generate a context binary file if it's not exist + * "qnn_context_cache_path": explicitly provide the QNN context cache file. Default to model_file.onnx.bin if not provided. + * "profiling_level": QNN profiling level, options: "off", "basic", "detailed". Default to off. + * "rpc_control_latency": QNN RPC control latency. + * "htp_performance_mode": QNN performance mode, options: "burst", "balanced", "default", "high_performance", + * "high_power_saver", "low_balanced", "low_power_saver", "power_saver", "sustained_high_performance". Default to "default". + * + * SNPE supported keys: + * "runtime": SNPE runtime engine, options: "CPU", "CPU_FLOAT32", "GPU", "GPU_FLOAT32_16_HYBRID", "GPU_FLOAT16", + * "DSP", "DSP_FIXED8_TF", "AIP_FIXED_TF", "AIP_FIXED8_TF". + * Mapping to SNPE Runtime_t definition: CPU, CPU_FLOAT32 => zdl::DlSystem::Runtime_t::CPU; + * GPU, GPU_FLOAT32_16_HYBRID => zdl::DlSystem::Runtime_t::GPU; + * GPU_FLOAT16 => zdl::DlSystem::Runtime_t::GPU_FLOAT16; + * DSP, DSP_FIXED8_TF => zdl::DlSystem::Runtime_t::DSP. + * AIP_FIXED_TF, AIP_FIXED8_TF => zdl::DlSystem::Runtime_t::AIP_FIXED_TF. + * "priority": execution priority, options: "low", "normal". + * "buffer_type": ITensor or user buffers, options: "ITENSOR", user buffer with different types - "TF8", "TF16", "UINT8", "FLOAT". + * "ITENSOR" -- default, ITensor which is float only. + * "TF8" -- quantized model required, "FLOAT" -- for both quantized or non-quantized model + * "enable_init_cache": enable SNPE init caching feature, set to 1 to enabled it. Disabled by default. + * If SNPE is not available (due to a non Snpe enabled build or its dependencies not being installed), this function will fail. + * + * XNNPACK supported keys: + * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider. + * default value is 0, which means to use the session thread-pool size. + * + * \since Version 1.12. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options, + _In_ const char* provider_name, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /* \brief: Get a copy of kernel info + * + * \param[in] info Kernel info + * \param[out] info_copy Copy of kernel info + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CopyKernelInfo, + _In_ const OrtKernelInfo* info, + _Outptr_ OrtKernelInfo** info_copy); + + /* \brief: Release kernel info + * + * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(KernelInfo); + + /// \name Ort Training + /// @{ + /** \brief Gets the Training C Api struct + * + * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable + * training with onnxruntime. + * \note A NULL pointer will be returned and no error message will be printed if the training api + * is not supported with this build. A NULL pointer will be returned and an error message will be + * printed if the provided version is unsupported, for example when using a runtime older than the + * version created with this header file. + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtTrainingApi struct for the version requested. + * + * \since Version 1.13 + */ + const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION; + + /// @} + + /** \brief Append CANN provider to session options + * + * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cann_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN, + _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options); + + /** \brief Create an OrtCANNProviderOptions + * + * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out); + + /** \brief Set options in a CANN Execution Provider. + * + * \param[in] cann_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized CANN provider options string. + * + * \param[in] cann_options OrtCANNProviderOptions instance + * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator() + * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate + * continuous buffers for output strings and lengths. + * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'. + * The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options, + _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an OrtCANNProviderOptions + * + * \param[in] the pointer of OrtCANNProviderOptions which will been deleted + * + * \since Version 1.13. + */ + void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input); + + /* \brief Get OrtDevice type from MemoryInfo + * + * \since Version 1.14 + */ + void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out); + + /* \brief Update the OrtEnv instance with custom log severity level + * + * \param[in] ort_env The OrtEnv instance being used + * \param[in] log_severity_level The log severity level. + * + * \since Version 1.14. + */ + ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level); + + /* \brief Set affinities for intra op threads + * + * Affinity string follows format: + * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id + * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. + * e.g. 1,2,3;4,5 + * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. + * To ease the configuration, an "interval" is also allowed: + * e.g. 1-8;8-16;17-24 + * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. + * Note: + * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, + * ort does not set affinity on the main thread which is started and managed by the calling app; + * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, + * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. + * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. + * + * \since Version 1.14 + */ + ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string); + + /** \brief Register custom ops from a shared library. + * + * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * + * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the + * library handle is released. If no OrtSession is created, then the library handle is released when the provided + * OrtSessionOptions is released. + * + * \param[in] options The session options. + * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library + * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information + * on the format of library names and search paths. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name); + + /** \brief Register custom ops by calling a RegisterCustomOpsFn function. + * + * Searches for registration_func_name and if found calls it. + * + * The library containing the function must either be linked against or previously loaded by the executable. + * + * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2. + * + * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load + * the library from a path. e.g. mobile platforms where the library must be linked into the app. + * + * The registration function must have the signature of RegisterCustomOpsFn: + * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api); + * + * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration + * function should be implemented. + * + * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the + * registration function. + * \param[in] registration_func_name Name of registration function to use. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options, + _In_ const char* registration_func_name); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the number of inputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the number of outputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the name of a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an input's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the name of a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an output's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's + * name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the type information for a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an input during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get the type information for a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an output during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] name UTF-8 null-terminated string representing the attribute's name. + * \param[in] allocator Allocator used to allocate the internal tensor state. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue, + * which will also free internal tensor state allocated with the provided allocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name, + _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtSessionOptions + /// Custom operator APIs + /// @{ + + /** \brief Checks if the given session configuration entry exists. + * + * The config_key formats are defined in onnxruntime_session_options_config_keys.h + * + * Can be used in a custom operator library to check for session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The ::OrtSessionOptions instance. + * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key. + * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ int* out); + + /** \brief Get a session configuration value. + * + * Returns a failure status if the configuration key does not exist. + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * If `config_value` is nullptr, the value of `size` is set to the true size of the string + * value (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string value's size, + * the value of `size` is set to the true size of the string value, the provided memory + * is filled with the value's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string value's size and `config_value` + * is not nullptr, the value of `size` is set to the true size of the string value + * and a failure status is returned. + * + * Can be used in a custom operator library to get session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The session options. + * \param[in] config_key A null-terminated UTF-8 string representation of the config key. + * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored. + * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size); + + /// @} + + /** \brief Append dnnl provider to session options + * + * If oneDNN is not available, this function will return failure. + * + * \param[in] options + * \param[in] dnnl_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl, + _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options); + + /** \brief Create an OrtDnnlProviderOptions + * + * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out); + + /** \brief Set options in a oneDNN Execution Provider. + * + * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions + * and value should be its related range. + * + * For example, key="use_arena" and value="1" + * + * \param[in] dnnl_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized oneDNN provider options string. + * + * For example, "use_arena=1;......" + * + * \param dnnl_options - OrtDnnlProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtDnnlProviderOptions + * + * \since Version 1.15. + */ + void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the graph node name from ::OrtKernelInfo. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_ char* out, _Inout_ size_t* size); + + /** \brief Get the session logger from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log + * messages. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Get the runtime logger from ::OrtKernelContext. + * + * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log + * messages during inference. + * + * \param[in] context An instance of ::OrtKernelContext. + * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtLogger + /// Custom operator APIs. + /// @{ + + /** \brief Logs a message at the given severity level using the provided ::OrtLogger. + * + * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level + * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity + * level. + * + * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger. + * + * \param[in] logger The ::OrtLogger instance. + * \param[in] log_severity_level The message's severity level. + * \param[in] message The message to log. + * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level, + _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number, + _In_z_ const char* func_name); + + /** \brief Get the logging severity level of the ::OrtLogger. + * + * Can be used in a custom operator to get the logging serverity level of the ::OrtLogger associated with + * the ::OrtKernelInfo. + * + * \param[in] logger The ::OrtLogger instance. + * \param[out] out Pointer to variable assigned with the logging severity level on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out); + + /// @} + + /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] index The node index. + * \param[out] is_constant Is it a constant node input or not. + * \param[out] out The OrtValue tensor value. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out); + + /** \brief Get Optional Type information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional. + * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by ::OrtOptionalTypeInfo. + * + * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied + * in place of the optional type when creating the actual ::OrtValue). + * + * \param[in] type_info + * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value, + * it is owned by OrtTypeInfo instance. When the type_info does not represent + * optional type, nullptr is returned in out. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out); + + /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo. + * + * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type. + * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by the returned ::OrtTypeInfo. + * + * \param[in] optional_type_info + * \param[out] out A pointer to the ::OrtTypeInfo for what the optional value could be. + * it is owned by OrtOptionalTypeInfo instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info, + _Outptr_ OrtTypeInfo** out); + + /** \brief Set a single string in a string tensor + * Do not zero terminate the string data. + * + * \param[in] value A string tensor + * \param[in] index - flat index of the element + * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator) + * \param[inout] buffer - address of return value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer); + + /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object + * + * \param[in] context OrtKernelContext instance + * \param[in] mem_info OrtMemoryInfo instance + * \param[out] out A pointer to OrtAllocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out); + + /** \brief Returns a null terminated string of the build info including git info and cxx flags + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + * + * \since Version 1.15. + */ + const char*(ORT_API_CALL* GetBuildInfoString)(void); + + /// \name OrtROCMProviderOptions + /// @{ + + /** \brief Create an OrtROCMProviderOptions + * + * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out); + + /** \brief Set options in a ROCm Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html + * to know the available keys and values. Key should be in null terminated string format of the member of + * ::OrtROCMProviderOptions and value should be its related range. + * + * For example, key="device_id" and value="0" + * + * \param[in] rocm_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized ROCm provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param rocm_options - OrtROCMProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtROCMProviderOptions + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.16. + */ + void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input); + + /** \brief Create an allocator with specific type and register it with the ::OrtEnv + * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * \param[in] env OrtEnv instance + * \param[in] provider_type ExecutionProvider type + * \param[in] mem_info OrtMemoryInfo instance + * \param[in] arena_cfg Arena configuration + * \param[in] provider_options_keys key of the provider options map + * \param[in] provider_options_values value of the provider options map + * \param[in] num_keys Length of the provider options map + */ + ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type, _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg, + _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys); + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] output OrtValue* array of size output_names_len. + * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue. + * Later, the output array will be passed to run_async_callback with all null(s) filled with valid + * OrtValue pointer(s) allocated by onnxruntime. + * NOTE: it is customer's duty to finally release the output array and each of its member, + * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer. + * \param[in] run_async_callback Callback function on model run completion + * \param[in] user_data User data that pass back to run_async_callback + */ + ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* input, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** output, + _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data); + + /** + * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value); + + /** + * Get TensorRT EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value); + + /** + * Get CUDA EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Get a EP resoure. + * E.g. a cuda stream or a cublas handle + * + * \param context - Kernel context + * \param resouce_version - Version of the resource + * \param resource_id - Type of resource + * \param resource - A pointer to returned resource + * + * \since Version 1.16. + */ + ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resouce_version, _In_ int resource_id, _Outptr_ void** resource); +}; + +/* + * Steps to use a custom op: + * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops + * 2 Create an OrtCustomOp structure for each op and add them to the domain + * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options + */ + +// Specifies some characteristics of inputs/outputs of custom ops: +// Specify if the inputs/outputs are one of: +// 1) Non-optional (input/output must be present in the node) +// 2) Optional (input/output may be absent in the node) +// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands. +// Only the last input or output of a custom op may be marked as variadic. +// The homogeneity of the variadic input or output determines whether all operands must be of the same +// tensor element type. +typedef enum OrtCustomOpInputOutputCharacteristic { + INPUT_OUTPUT_REQUIRED = 0, + INPUT_OUTPUT_OPTIONAL, + INPUT_OUTPUT_VARIADIC, +} OrtCustomOpInputOutputCharacteristic; + +/* + * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by + * the implementor of the custom op. + */ +struct OrtCustomOp { + uint32_t version; // Must be initialized to ORT_API_VERSION + + // This callback creates the kernel, which is a user defined + // parameter that is passed to the Kernel* callbacks below. It is + // recommended to use CreateKernelV2 which allows for a safe error + // propagation by returning an OrtStatusPtr. + void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info); + + // Returns the name of the op + const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op); + + // Returns the type of the execution provider, return nullptr to use CPU execution provider + const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op); + + // Returns the count and types of the input & output tensors + ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op); + ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op); + + // Perform a computation step. It is recommended to use + // KernelComputeV2 which allows for a safe error propagation by + // returning an OrtStatusPtr. + void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context); + void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel); + + // Returns the characteristics of the input & output tensors + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the memory type of the input tensors. This API allows the custom op + // to place the inputs on specific devices. By default, it returns + // OrtMemTypeDefault, which means the input is placed on the default device for + // the execution provider. If the inputs need to be with different memory tyeps, + // this function can be overridden to return the specific memory types. + OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the minimum number of input arguments expected for the variadic input. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Returns the minimum number of output values expected for the variadic output. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Create the kernel state which is passed to each compute call. + OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info, + _Out_ void** kernel); + + // Perform the computation step. + OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context); +}; + +/* + * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists + * + * \param device_id CUDA device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the ROCm provider to the session, please use + * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the ROCm provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the MIGraphX provider to the session, please use + * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the MIGraphX provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the oneDNN provider to the session, please use + * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * oneDNN support and the oneDNN provider shared library exists + * + * \param use_arena zero: false. non-zero: true. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena); + +#ifdef __cplusplus +} +#endif +/// @} diff --git a/runexamples/cpp/onnx/include/onnxruntime_cxx_api.h b/runexamples/cpp/onnx/include/onnxruntime_cxx_api.h new file mode 100644 index 0000000..47356c3 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_cxx_api.h @@ -0,0 +1,2266 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Summary: The Ort C++ API is a header only wrapper around the Ort C API. +// +// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors +// and automatically releasing resources in the destructors. The primary purpose of C++ API is exception safety so +// all the resources follow RAII and do not leak memory. +// +// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers. +// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};). However, you can't use them +// until you assign an instance that actually holds an underlying object. +// +// For Ort objects only move assignment between objects is allowed, there are no copy constructors. +// Some objects have explicit 'Clone' methods for this purpose. +// +// ConstXXXX types are copyable since they do not own the underlying C object, so you can pass them to functions as arguments +// by value or by reference. ConstXXXX types are restricted to const only interfaces. +// +// UnownedXXXX are similar to ConstXXXX but also allow non-const interfaces. +// +// The lifetime of the corresponding owning object must eclipse the lifetimes of the ConstXXXX/UnownedXXXX types. They exists so you do not +// have to fallback to C types and the API with the usual pitfalls. In general, do not use C API from your C++ code. + +#pragma once +#include "onnxruntime_c_api.h" +#include "onnxruntime_float16.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ORT_NO_EXCEPTIONS +#include +#endif + +/** \brief All C++ Onnxruntime APIs are defined inside this namespace + * + */ +namespace Ort { + +/** \brief All C++ methods that can fail will throw an exception of this type + * + * If ORT_NO_EXCEPTIONS is defined, then any error will result in a call to abort() + */ +struct Exception : std::exception { + Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {} + + OrtErrorCode GetOrtErrorCode() const { return code_; } + const char* what() const noexcept override { return message_.c_str(); } + + private: + std::string message_; + OrtErrorCode code_; +}; + +#ifdef ORT_NO_EXCEPTIONS +// The #ifndef is for the very special case where the user of this library wants to define their own way of handling errors. +// NOTE: This header expects control flow to not continue after calling ORT_CXX_API_THROW +#ifndef ORT_CXX_API_THROW +#define ORT_CXX_API_THROW(string, code) \ + do { \ + std::cerr << Ort::Exception(string, code) \ + .what() \ + << std::endl; \ + abort(); \ + } while (false) +#endif +#else +#define ORT_CXX_API_THROW(string, code) \ + throw Ort::Exception(string, code) +#endif + +// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, +// it's in a template so that we can define a global variable in a header and make +// it transparent to the users of the API. +template +struct Global { + static const OrtApi* api_; +}; + +// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it. +template +#ifdef ORT_API_MANUAL_INIT +const OrtApi* Global::api_{}; +inline void InitApi() noexcept { Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); } + +// Used by custom operator libraries that are not linked to onnxruntime. Sets the global API object, which is +// required by C++ APIs. +// +// Example mycustomop.cc: +// +// #define ORT_API_MANUAL_INIT +// #include +// #undef ORT_API_MANUAL_INIT +// +// OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api_base) { +// Ort::InitApi(api_base->GetApi(ORT_API_VERSION)); +// // ... +// } +// +inline void InitApi(const OrtApi* api) noexcept { Global::api_ = api; } +#else +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +// "Global initializer calls a non-constexpr function." Therefore you can't use ORT APIs in the other global initializers. +// Please define ORT_API_MANUAL_INIT if it conerns you. +#pragma warning(disable : 26426) +#endif +const OrtApi* Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif +#endif + +/// This returns a reference to the OrtApi interface in use +inline const OrtApi& GetApi() noexcept { return *Global::api_; } + +/// +/// This function returns the onnxruntime version string +/// +/// version string major.minor.rev +std::string GetVersionString(); + +/// +/// This function returns the onnxruntime build information: including git branch, +/// git commit id, build type(Debug/Release/RelWithDebInfo) and cmake cpp flags. +/// +/// string +std::string GetBuildInfoString(); + +/// +/// This is a C++ wrapper for OrtApi::GetAvailableProviders() and +/// returns a vector of strings representing the available execution providers. +/// +/// vector of strings +std::vector GetAvailableProviders(); + +/** \brief IEEE 754 half-precision floating point data type + * + * \details This struct is used for converting float to float16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector fp16_values; + * fp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(fp16_values), + * [](float value) { return Ort::Float16_t(value); }); + * + * \endcode + */ +struct Float16_t : onnxruntime_float16::Float16Impl { + private: + /// + /// Constructor from a 16-bit representation of a float16 value + /// No conversion is done here. + /// + /// 16-bit representation + constexpr explicit Float16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::Float16Impl; + + /// + /// Default constructor + /// + Float16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of float16. + /// + /// uint16_t bit representation of float16 + /// new instance of Float16_t + constexpr static Float16_t FromBits(uint16_t v) noexcept { return Float16_t(v); } + + /// + /// __ctor from float. Float is converted into float16 16-bit representation. + /// + /// float value + explicit Float16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts Float16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + using Base::operator==; + using Base::operator!=; + using Base::operator<; +}; + +static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief bfloat16 (Brain Floating Point) data type + * + * \details This struct is used for converting float to bfloat16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector bfp16_values; + * bfp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(bfp16_values), + * [](float value) { return Ort::BFloat16_t(value); }); + * + * \endcode + */ +struct BFloat16_t : onnxruntime_float16::BFloat16Impl { + private: + /// + /// Constructor from a uint16_t representation of bfloat16 + /// used in FromBits() to escape overload resolution issue with + /// constructor from float. + /// No conversion is done. + /// + /// 16-bit bfloat16 value + constexpr explicit BFloat16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::BFloat16Impl; + + BFloat16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of bfloat16. + /// + /// uint16_t bit representation of bfloat16 + /// new instance of BFloat16_t + static constexpr BFloat16_t FromBits(uint16_t v) noexcept { return BFloat16_t(v); } + + /// + /// __ctor from float. Float is converted into bfloat16 16-bit representation. + /// + /// float value + explicit BFloat16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts BFloat16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + // We do not have an inherited impl for the below operators + // as the internal class implements them a little differently + bool operator==(const BFloat16_t& rhs) const noexcept; + bool operator!=(const BFloat16_t& rhs) const noexcept { return !(*this == rhs); } + bool operator<(const BFloat16_t& rhs) const noexcept; +}; + +static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief float8e4m3fn (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FN_t { + uint8_t value; + constexpr Float8E4M3FN_t() noexcept : value(0) {} + constexpr Float8E4M3FN_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FN_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FN_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FN_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e4m3fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FNUZ_t { + uint8_t value; + constexpr Float8E4M3FNUZ_t() noexcept : value(0) {} + constexpr Float8E4M3FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2 (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2_t { + uint8_t value; + constexpr Float8E5M2_t() noexcept : value(0) {} + constexpr Float8E5M2_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2FNUZ_t { + uint8_t value; + constexpr Float8E5M2FNUZ_t() noexcept : value(0) {} + constexpr Float8E5M2FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +namespace detail { +// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type +// This can't be done in the C API since C doesn't have function overloading. +#define ORT_DEFINE_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); } + +ORT_DEFINE_RELEASE(Allocator); +ORT_DEFINE_RELEASE(MemoryInfo); +ORT_DEFINE_RELEASE(CustomOpDomain); +ORT_DEFINE_RELEASE(ThreadingOptions); +ORT_DEFINE_RELEASE(Env); +ORT_DEFINE_RELEASE(RunOptions); +ORT_DEFINE_RELEASE(Session); +ORT_DEFINE_RELEASE(SessionOptions); +ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo); +ORT_DEFINE_RELEASE(SequenceTypeInfo); +ORT_DEFINE_RELEASE(MapTypeInfo); +ORT_DEFINE_RELEASE(TypeInfo); +ORT_DEFINE_RELEASE(Value); +ORT_DEFINE_RELEASE(ModelMetadata); +ORT_DEFINE_RELEASE(IoBinding); +ORT_DEFINE_RELEASE(ArenaCfg); +ORT_DEFINE_RELEASE(Status); +ORT_DEFINE_RELEASE(OpAttr); +ORT_DEFINE_RELEASE(Op); +ORT_DEFINE_RELEASE(KernelInfo); + +#undef ORT_DEFINE_RELEASE + +/** \brief This is a tagging template type. Use it with Base to indicate that the C++ interface object + * has no ownership of the underlying C object. + */ +template +struct Unowned { + using Type = T; +}; + +/** \brief Used internally by the C++ API. C++ wrapper types inherit from this. + * This is a zero cost abstraction to wrap the C API objects and delete them on destruction. + * + * All of the C++ classes + * a) serve as containers for pointers to objects that are created by the underlying C API. + * Their size is just a pointer size, no need to dynamically allocate them. Use them by value. + * b) Each of struct XXXX, XXX instances function as smart pointers to the underlying C API objects. + * they would release objects owned automatically when going out of scope, they are move-only. + * c) ConstXXXX and UnownedXXX structs function as non-owning, copyable containers for the above pointers. + * ConstXXXX allow calling const interfaces only. They give access to objects that are owned by somebody else + * such as Onnxruntime or instances of XXXX classes. + * d) serve convenient interfaces that return C++ objects and further enhance exception and type safety so they can be used + * in C++ code. + * + */ + +/// +/// This is a non-const pointer holder that is move-only. Disposes of the pointer on destruction. +/// +template +struct Base { + using contained_type = T; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + ~Base() { OrtRelease(p_); } + + Base(const Base&) = delete; + Base& operator=(const Base&) = delete; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + OrtRelease(p_); + p_ = v.release(); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + /// \brief Relinquishes ownership of the contained C object pointer + /// The underlying object is not destroyed + contained_type* release() { + T* p = p_; + p_ = nullptr; + return p; + } + + protected: + contained_type* p_{}; +}; + +// Undefined. For const types use Base> +template +struct Base; + +/// +/// Covers unowned pointers owned by either the ORT +/// or some other instance of CPP wrappers. +/// Used for ConstXXX and UnownedXXXX types that are copyable. +/// Also convenient to wrap raw OrtXX pointers . +/// +/// +template +struct Base> { + using contained_type = typename Unowned::Type; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + + ~Base() = default; + + Base(const Base&) = default; + Base& operator=(const Base&) = default; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + p_ = nullptr; + std::swap(p_, v.p_); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + protected: + contained_type* p_{}; +}; + +// Light functor to release memory with OrtAllocator +struct AllocatedFree { + OrtAllocator* allocator_; + explicit AllocatedFree(OrtAllocator* allocator) + : allocator_(allocator) {} + void operator()(void* ptr) const { + if (ptr) allocator_->Free(allocator_, ptr); + } +}; + +} // namespace detail + +struct AllocatorWithDefaultOptions; +struct Env; +struct TypeInfo; +struct Value; +struct ModelMetadata; + +/** \brief unique_ptr typedef used to own strings allocated by OrtAllocators + * and release them at the end of the scope. The lifespan of the given allocator + * must eclipse the lifespan of AllocatedStringPtr instance + */ +using AllocatedStringPtr = std::unique_ptr; + +/** \brief The Status that holds ownership of OrtStatus received from C API + * Use it to safely destroy OrtStatus* returned from the C API. Use appropriate + * constructors to construct an instance of a Status object from exceptions. + */ +struct Status : detail::Base { + explicit Status(std::nullptr_t) noexcept {} ///< Create an empty object, must be assigned a valid one to be used + explicit Status(OrtStatus* status) noexcept; ///< Takes ownership of OrtStatus instance returned from the C API. + explicit Status(const Exception&) noexcept; ///< Creates status instance out of exception + explicit Status(const std::exception&) noexcept; ///< Creates status instance out of exception + Status(const char* message, OrtErrorCode code) noexcept; ///< Creates status instance out of null-terminated string message. + std::string GetErrorMessage() const; + OrtErrorCode GetErrorCode() const; + bool IsOK() const noexcept; ///< Returns true if instance represents an OK (non-error) status. +}; + +/** \brief The ThreadingOptions + * + * The ThreadingOptions used for set global threadpools' options of The Env. + */ +struct ThreadingOptions : detail::Base { + /// \brief Wraps OrtApi::CreateThreadingOptions + ThreadingOptions(); + + /// \brief Wraps OrtApi::SetGlobalIntraOpNumThreads + ThreadingOptions& SetGlobalIntraOpNumThreads(int intra_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalInterOpNumThreads + ThreadingOptions& SetGlobalInterOpNumThreads(int inter_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalSpinControl + ThreadingOptions& SetGlobalSpinControl(int allow_spinning); + + /// \brief Wraps OrtApi::SetGlobalDenormalAsZero + ThreadingOptions& SetGlobalDenormalAsZero(); + + /// \brief Wraps OrtApi::SetGlobalCustomCreateThreadFn + ThreadingOptions& SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /// \brief Wraps OrtApi::SetGlobalCustomThreadCreationOptions + ThreadingOptions& SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options); + + /// \brief Wraps OrtApi::SetGlobalCustomJoinThreadFn + ThreadingOptions& SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); +}; + +/** \brief The Env (Environment) + * + * The Env holds the logging state used by all other objects. + * Note: One Env must be created before using any other Onnxruntime functionality + */ +struct Env : detail::Base { + explicit Env(std::nullptr_t) {} ///< Create an empty Env object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateEnv + Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLogger + Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param); + + /// \brief Wraps OrtApi::CreateEnvWithGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLoggerAndGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief C Interop Helper + explicit Env(OrtEnv* p) : Base{p} {} + + Env& EnableTelemetryEvents(); ///< Wraps OrtApi::EnableTelemetryEvents + Env& DisableTelemetryEvents(); ///< Wraps OrtApi::DisableTelemetryEvents + + Env& UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level); ///< Wraps OrtApi::UpdateEnvWithCustomLogLevel + + Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocator + + Env& CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocatorV2 +}; + +/** \brief Custom Op Domain + * + */ +struct CustomOpDomain : detail::Base { + explicit CustomOpDomain(std::nullptr_t) {} ///< Create an empty CustomOpDomain object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateCustomOpDomain + explicit CustomOpDomain(const char* domain); + + // This does not take ownership of the op, simply registers it. + void Add(const OrtCustomOp* op); ///< Wraps CustomOpDomain_Add +}; + +/** \brief RunOptions + * + */ +struct RunOptions : detail::Base { + explicit RunOptions(std::nullptr_t) {} ///< Create an empty RunOptions object, must be assigned a valid one to be used + RunOptions(); ///< Wraps OrtApi::CreateRunOptions + + RunOptions& SetRunLogVerbosityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogVerbosityLevel + int GetRunLogVerbosityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogVerbosityLevel + + RunOptions& SetRunLogSeverityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogSeverityLevel + int GetRunLogSeverityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogSeverityLevel + + RunOptions& SetRunTag(const char* run_tag); ///< wraps OrtApi::RunOptionsSetRunTag + const char* GetRunTag() const; ///< Wraps OrtApi::RunOptionsGetRunTag + + RunOptions& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddRunConfigEntry + + /** \brief Terminates all currently executing Session::Run calls that were made using this RunOptions instance + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error + * Wraps OrtApi::RunOptionsSetTerminate + */ + RunOptions& SetTerminate(); + + /** \brief Clears the terminate flag so this RunOptions instance can be used in a new Session::Run call without it instantly terminating + * + * Wraps OrtApi::RunOptionsUnsetTerminate + */ + RunOptions& UnsetTerminate(); +}; + +namespace detail { +// Utility function that returns a SessionOption config entry key for a specific custom operator. +// Ex: custom_op.[custom_op_name].[config] +std::string MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config); +} // namespace detail + +/// +/// Class that represents session configuration entries for one or more custom operators. +/// +/// Example: +/// Ort::CustomOpConfigs op_configs; +/// op_configs.AddConfig("my_custom_op", "device_type", "CPU"); +/// +/// Passed to Ort::SessionOptions::RegisterCustomOpsLibrary. +/// +struct CustomOpConfigs { + CustomOpConfigs() = default; + ~CustomOpConfigs() = default; + CustomOpConfigs(const CustomOpConfigs&) = default; + CustomOpConfigs& operator=(const CustomOpConfigs&) = default; + CustomOpConfigs(CustomOpConfigs&& o) = default; + CustomOpConfigs& operator=(CustomOpConfigs&& o) = default; + + /** \brief Adds a session configuration entry/value for a specific custom operator. + * + * \param custom_op_name The name of the custom operator for which to add a configuration entry. + * Must match the name returned by the CustomOp's GetName() method. + * \param config_key The name of the configuration entry. + * \param config_value The value of the configuration entry. + * \return A reference to this object to enable call chaining. + */ + CustomOpConfigs& AddConfig(const char* custom_op_name, const char* config_key, const char* config_value); + + /** \brief Returns a flattened map of custom operator configuration entries and their values. + * + * The keys has been flattened to include both the custom operator name and the configuration entry key name. + * For example, a prior call to AddConfig("my_op", "key", "value") corresponds to the flattened key/value pair + * {"my_op.key", "value"}. + * + * \return An unordered map of flattened configurations. + */ + const std::unordered_map& GetFlattenedConfigs() const; + + private: + std::unordered_map flat_configs_; +}; + +/** \brief Options object used when creating a new Session object + * + * Wraps ::OrtSessionOptions object and methods + */ + +struct SessionOptions; + +namespace detail { +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionOptionsImpl : Base { + using B = Base; + using B::B; + + SessionOptions Clone() const; ///< Creates and returns a copy of this SessionOptions object. Wraps OrtApi::CloneSessionOptions + + std::string GetConfigEntry(const char* config_key) const; ///< Wraps OrtApi::GetSessionConfigEntry + bool HasConfigEntry(const char* config_key) const; ///< Wraps OrtApi::HasSessionConfigEntry + std::string GetConfigEntryOrDefault(const char* config_key, const std::string& def); +}; + +template +struct SessionOptionsImpl : ConstSessionOptionsImpl { + using B = ConstSessionOptionsImpl; + using B::B; + + SessionOptionsImpl& SetIntraOpNumThreads(int intra_op_num_threads); ///< Wraps OrtApi::SetIntraOpNumThreads + SessionOptionsImpl& SetInterOpNumThreads(int inter_op_num_threads); ///< Wraps OrtApi::SetInterOpNumThreads + SessionOptionsImpl& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level); ///< Wraps OrtApi::SetSessionGraphOptimizationLevel + + SessionOptionsImpl& EnableCpuMemArena(); ///< Wraps OrtApi::EnableCpuMemArena + SessionOptionsImpl& DisableCpuMemArena(); ///< Wraps OrtApi::DisableCpuMemArena + + SessionOptionsImpl& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file); ///< Wraps OrtApi::SetOptimizedModelFilePath + + SessionOptionsImpl& EnableProfiling(const ORTCHAR_T* profile_file_prefix); ///< Wraps OrtApi::EnableProfiling + SessionOptionsImpl& DisableProfiling(); ///< Wraps OrtApi::DisableProfiling + + SessionOptionsImpl& EnableOrtCustomOps(); ///< Wraps OrtApi::EnableOrtCustomOps + + SessionOptionsImpl& EnableMemPattern(); ///< Wraps OrtApi::EnableMemPattern + SessionOptionsImpl& DisableMemPattern(); ///< Wraps OrtApi::DisableMemPattern + + SessionOptionsImpl& SetExecutionMode(ExecutionMode execution_mode); ///< Wraps OrtApi::SetSessionExecutionMode + + SessionOptionsImpl& SetLogId(const char* logid); ///< Wraps OrtApi::SetSessionLogId + SessionOptionsImpl& SetLogSeverityLevel(int level); ///< Wraps OrtApi::SetSessionLogSeverityLevel + + SessionOptionsImpl& Add(OrtCustomOpDomain* custom_op_domain); ///< Wraps OrtApi::AddCustomOpDomain + + SessionOptionsImpl& DisablePerSessionThreads(); ///< Wraps OrtApi::DisablePerSessionThreads + + SessionOptionsImpl& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddSessionConfigEntry + + SessionOptionsImpl& AddInitializer(const char* name, const OrtValue* ort_val); ///< Wraps OrtApi::AddInitializer + SessionOptionsImpl& AddExternalInitializers(const std::vector& names, const std::vector& ort_values); ///< Wraps OrtApi::AddExternalInitializers + + SessionOptionsImpl& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA + SessionOptionsImpl& AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA_V2 + SessionOptionsImpl& AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_ROCM + SessionOptionsImpl& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO + SessionOptionsImpl& AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CANN + SessionOptionsImpl& AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options); + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_Dnnl + SessionOptionsImpl& AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options); + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider. Currently supports QNN, SNPE and XNNPACK. + SessionOptionsImpl& AppendExecutionProvider(const std::string& provider_name, + const std::unordered_map& provider_options = {}); + + SessionOptionsImpl& SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomCreateThreadFn + SessionOptionsImpl& SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options); ///< Wraps OrtApi::SessionOptionsSetCustomThreadCreationOptions + SessionOptionsImpl& SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomJoinThreadFn + + ///< Registers the custom operator from the specified shared library via OrtApi::RegisterCustomOpsLibrary_V2. + ///< The custom operator configurations are optional. If provided, custom operator configs are set via + ///< OrtApi::AddSessionConfigEntry. + SessionOptionsImpl& RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, const CustomOpConfigs& custom_op_configs = {}); + + SessionOptionsImpl& RegisterCustomOpsUsingFunction(const char* function_name); ///< Wraps OrtApi::RegisterCustomOpsUsingFunction +}; +} // namespace detail + +using UnownedSessionOptions = detail::SessionOptionsImpl>; +using ConstSessionOptions = detail::ConstSessionOptionsImpl>; + +/** \brief Wrapper around ::OrtSessionOptions + * + */ +struct SessionOptions : detail::SessionOptionsImpl { + explicit SessionOptions(std::nullptr_t) {} ///< Create an empty SessionOptions object, must be assigned a valid one to be used + SessionOptions(); ///< Wraps OrtApi::CreateSessionOptions + explicit SessionOptions(OrtSessionOptions* p) : SessionOptionsImpl{p} {} ///< Used for interop with the C API + UnownedSessionOptions GetUnowned() const { return UnownedSessionOptions{this->p_}; } + ConstSessionOptions GetConst() const { return ConstSessionOptions{this->p_}; } +}; + +/** \brief Wrapper around ::OrtModelMetadata + * + */ +struct ModelMetadata : detail::Base { + explicit ModelMetadata(std::nullptr_t) {} ///< Create an empty ModelMetadata object, must be assigned a valid one to be used + explicit ModelMetadata(OrtModelMetadata* p) : Base{p} {} ///< Used for interop with the C API + + /** \brief Returns a copy of the producer name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetProducerNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetProducerName + + /** \brief Returns a copy of the graph name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphName + + /** \brief Returns a copy of the domain name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDomainAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDomain + + /** \brief Returns a copy of the description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDescription + + /** \brief Returns a copy of the graph description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphDescription + + /** \brief Returns a vector of copies of the custom metadata keys. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance std::vector of smart pointers that would deallocate the buffers when out of scope. + * The OrtAllocator instance must be valid at the point of memory release. + */ + std::vector GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetCustomMetadataMapKeys + + /** \brief Looks up a value by a key in the Custom Metadata map + * + * \param key zero terminated string key to lookup + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * maybe nullptr if key is not found. + * + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataLookupCustomMetadataMap + + int64_t GetVersion() const; ///< Wraps OrtApi::ModelMetadataGetVersion +}; + +struct IoBinding; + +namespace detail { + +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionImpl : Base { + using B = Base; + using B::B; + + size_t GetInputCount() const; ///< Returns the number of model inputs + size_t GetOutputCount() const; ///< Returns the number of model outputs + size_t GetOverridableInitializerCount() const; ///< Returns the number of inputs that have defaults that can be overridden + + /** \brief Returns a copy of input name at the specified index. + * + * \param index must less than the value returned by GetInputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetInputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of output name at then specified index. + * + * \param index must less than the value returned by GetOutputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of the overridable initializer name at then specified index. + * + * \param index must less than the value returned by GetOverridableInitializerCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const; ///< Wraps OrtApi::SessionGetOverridableInitializerName + + uint64_t GetProfilingStartTimeNs() const; ///< Wraps OrtApi::SessionGetProfilingStartTimeNs + ModelMetadata GetModelMetadata() const; ///< Wraps OrtApi::SessionGetModelMetadata + + TypeInfo GetInputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetInputTypeInfo + TypeInfo GetOutputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOutputTypeInfo + TypeInfo GetOverridableInitializerTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOverridableInitializerTypeInfo +}; + +template +struct SessionImpl : ConstSessionImpl { + using B = ConstSessionImpl; + using B::B; + + /** \brief Run the model returning results in an Ort allocated vector. + * + * Wraps OrtApi::Run + * + * The caller provides a list of inputs and a list of the desired outputs to return. + * + * See the output logs for more information on warnings/errors that occur while processing the model. + * Common errors are.. (TODO) + * + * \param[in] run_options + * \param[in] input_names Array of null terminated strings of length input_count that is the list of input names + * \param[in] input_values Array of Value objects of length input_count that is the list of input values + * \param[in] input_count Number of inputs (the size of the input_names & input_values arrays) + * \param[in] output_names Array of C style strings of length output_count that is the list of output names + * \param[in] output_count Number of outputs (the size of the output_names array) + * \return A std::vector of Value objects that directly maps to the output_names array (eg. output_name[0] is the first entry of the returned vector) + */ + std::vector Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count); + + /** \brief Run the model returning results in user provided outputs + * Same as Run(const RunOptions&, const char* const*, const Value*, size_t,const char* const*, size_t) + */ + void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count); + + void Run(const RunOptions& run_options, const IoBinding&); ///< Wraps OrtApi::RunWithBinding + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * Wraps OrtApi::RunAsync + * + * \param[in] run_options + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input_values Array of Value objects of length input_count + * \param[in] input_count Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[out] output_values Array of provided Values to be filled with outputs. + * On calling RunAsync, output_values[i] could either be initialized by a null pointer or a preallocated OrtValue*. + * Later, on invoking the callback, each output_values[i] of null will be filled with an OrtValue* allocated by onnxruntime. + * Then, an OrtValue** pointer will be casted from output_values, and pass to the callback. + * NOTE: it is customer's duty to finally release output_values and each of its member, + * regardless of whether the member (Ort::Value) is allocated by onnxruntime or preallocated by the customer. + * \param[in] output_count Number of elements in the output_names and outputs array + * \param[in] callback Callback function on model run completion + * \param[in] user_data User data that pass back to the callback + */ + void RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data); + + /** \brief End profiling and return a copy of the profiling file name. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr EndProfilingAllocated(OrtAllocator* allocator); ///< Wraps OrtApi::SessionEndProfiling +}; + +} // namespace detail + +using ConstSession = detail::ConstSessionImpl>; +using UnownedSession = detail::SessionImpl>; + +/** \brief Wrapper around ::OrtSession + * + */ +struct Session : detail::SessionImpl { + explicit Session(std::nullptr_t) {} ///< Create an empty Session object, must be assigned a valid one to be used + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); ///< Wraps OrtApi::CreateSession + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); ///< Wraps OrtApi::CreateSessionWithPrepackedWeightsContainer + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options); ///< Wraps OrtApi::CreateSessionFromArray + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); ///< Wraps OrtApi::CreateSessionFromArrayWithPrepackedWeightsContainer + + ConstSession GetConst() const { return ConstSession{this->p_}; } + UnownedSession GetUnowned() const { return UnownedSession{this->p_}; } +}; + +namespace detail { +template +struct MemoryInfoImpl : Base { + using B = Base; + using B::B; + + std::string GetAllocatorName() const; + OrtAllocatorType GetAllocatorType() const; + int GetDeviceId() const; + OrtMemoryInfoDeviceType GetDeviceType() const; + OrtMemType GetMemoryType() const; + + template + bool operator==(const MemoryInfoImpl& o) const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstMemoryInfo = detail::MemoryInfoImpl>; + +/** \brief Wrapper around ::OrtMemoryInfo + * + */ +struct MemoryInfo : detail::MemoryInfoImpl { + static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1); + explicit MemoryInfo(std::nullptr_t) {} ///< No instance is created + explicit MemoryInfo(OrtMemoryInfo* p) : MemoryInfoImpl{p} {} ///< Take ownership of a pointer created by C Api + MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type); + ConstMemoryInfo GetConst() const { return ConstMemoryInfo{this->p_}; } +}; + +namespace detail { +template +struct TensorTypeAndShapeInfoImpl : Base { + using B = Base; + using B::B; + + ONNXTensorElementDataType GetElementType() const; ///< Wraps OrtApi::GetTensorElementType + size_t GetElementCount() const; ///< Wraps OrtApi::GetTensorShapeElementCount + + size_t GetDimensionsCount() const; ///< Wraps OrtApi::GetDimensionsCount + + /** \deprecated use GetShape() returning std::vector + * [[deprecated]] + * This interface is unsafe to use + */ + [[deprecated("use GetShape()")]] void GetDimensions(int64_t* values, size_t values_count) const; ///< Wraps OrtApi::GetDimensions + + void GetSymbolicDimensions(const char** values, size_t values_count) const; ///< Wraps OrtApi::GetSymbolicDimensions + + std::vector GetShape() const; ///< Uses GetDimensionsCount & GetDimensions to return a std::vector of the shape +}; + +} // namespace detail + +using ConstTensorTypeAndShapeInfo = detail::TensorTypeAndShapeInfoImpl>; + +/** \brief Wrapper around ::OrtTensorTypeAndShapeInfo + * + */ +struct TensorTypeAndShapeInfo : detail::TensorTypeAndShapeInfoImpl { + explicit TensorTypeAndShapeInfo(std::nullptr_t) {} ///< Create an empty TensorTypeAndShapeInfo object, must be assigned a valid one to be used + explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : TensorTypeAndShapeInfoImpl{p} {} ///< Used for interop with the C API + ConstTensorTypeAndShapeInfo GetConst() const { return ConstTensorTypeAndShapeInfo{this->p_}; } +}; + +namespace detail { +template +struct SequenceTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetSequenceElementType() const; ///< Wraps OrtApi::GetSequenceElementType +}; + +} // namespace detail + +using ConstSequenceTypeInfo = detail::SequenceTypeInfoImpl>; + +/** \brief Wrapper around ::OrtSequenceTypeInfo + * + */ +struct SequenceTypeInfo : detail::SequenceTypeInfoImpl { + explicit SequenceTypeInfo(std::nullptr_t) {} ///< Create an empty SequenceTypeInfo object, must be assigned a valid one to be used + explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : SequenceTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstSequenceTypeInfo GetConst() const { return ConstSequenceTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct OptionalTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetOptionalElementType() const; ///< Wraps OrtApi::CastOptionalTypeToContainedTypeInfo +}; + +} // namespace detail + +// This is always owned by the TypeInfo and can only be obtained from it. +using ConstOptionalTypeInfo = detail::OptionalTypeInfoImpl>; + +namespace detail { +template +struct MapTypeInfoImpl : detail::Base { + using B = Base; + using B::B; + ONNXTensorElementDataType GetMapKeyType() const; ///< Wraps OrtApi::GetMapKeyType + TypeInfo GetMapValueType() const; ///< Wraps OrtApi::GetMapValueType +}; + +} // namespace detail + +using ConstMapTypeInfo = detail::MapTypeInfoImpl>; + +/** \brief Wrapper around ::OrtMapTypeInfo + * + */ +struct MapTypeInfo : detail::MapTypeInfoImpl { + explicit MapTypeInfo(std::nullptr_t) {} ///< Create an empty MapTypeInfo object, must be assigned a valid one to be used + explicit MapTypeInfo(OrtMapTypeInfo* p) : MapTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstMapTypeInfo GetConst() const { return ConstMapTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct TypeInfoImpl : detail::Base { + using B = Base; + using B::B; + + ConstTensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; ///< Wraps OrtApi::CastTypeInfoToTensorInfo + ConstSequenceTypeInfo GetSequenceTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToSequenceTypeInfo + ConstMapTypeInfo GetMapTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToMapTypeInfo + ConstOptionalTypeInfo GetOptionalTypeInfo() const; ///< wraps OrtApi::CastTypeInfoToOptionalTypeInfo + + ONNXType GetONNXType() const; +}; +} // namespace detail + +/// +/// Contains a constant, unowned OrtTypeInfo that can be copied and passed around by value. +/// Provides access to const OrtTypeInfo APIs. +/// +using ConstTypeInfo = detail::TypeInfoImpl>; + +/// +/// Type information that may contain either TensorTypeAndShapeInfo or +/// the information about contained sequence or map depending on the ONNXType. +/// +struct TypeInfo : detail::TypeInfoImpl { + explicit TypeInfo(std::nullptr_t) {} ///< Create an empty TypeInfo object, must be assigned a valid one to be used + explicit TypeInfo(OrtTypeInfo* p) : TypeInfoImpl{p} {} ///< C API Interop + + ConstTypeInfo GetConst() const { return ConstTypeInfo{this->p_}; } +}; + +namespace detail { +// This structure is used to feed sparse tensor values +// information for use with FillSparseTensor() API +// if the data type for the sparse tensor values is numeric +// use data.p_data, otherwise, use data.str pointer to feed +// values. data.str is an array of const char* that are zero terminated. +// number of strings in the array must match shape size. +// For fully sparse tensors use shape {0} and set p_data/str +// to nullptr. +struct OrtSparseValuesParam { + const int64_t* values_shape; + size_t values_shape_len; + union { + const void* p_data; + const char** str; + } data; +}; + +// Provides a way to pass shape in a single +// argument +struct Shape { + const int64_t* shape; + size_t shape_len; +}; + +template +struct ConstValueImpl : Base { + using B = Base; + using B::B; + + /// + /// Obtains a pointer to a user defined data for experimental purposes + /// + template + void GetOpaqueData(const char* domain, const char* type_name, R&) const; ///< Wraps OrtApi::GetOpaqueValue + + bool IsTensor() const; ///< Returns true if Value is a tensor, false for other types like map/sequence/etc + bool HasValue() const; /// < Return true if OrtValue contains data and returns false if the OrtValue is a None + + size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements + Value GetValue(int index, OrtAllocator* allocator) const; + + /// + /// This API returns a full length of string data contained within either a tensor or a sparse Tensor. + /// For sparse tensor it returns a full length of stored non-empty strings (values). The API is useful + /// for allocating necessary memory and calling GetStringTensorContent(). + /// + /// total length of UTF-8 encoded bytes contained. No zero terminators counted. + size_t GetStringTensorDataLength() const; + + /// + /// The API copies all of the UTF-8 encoded string data contained within a tensor or a sparse tensor + /// into a supplied buffer. Use GetStringTensorDataLength() to find out the length of the buffer to allocate. + /// The user must also allocate offsets buffer with the number of entries equal to that of the contained + /// strings. + /// + /// Strings are always assumed to be on CPU, no X-device copy. + /// + /// user allocated buffer + /// length in bytes of the allocated buffer + /// a pointer to the offsets user allocated buffer + /// count of offsets, must be equal to the number of strings contained. + /// that can be obtained from the shape of the tensor or from GetSparseTensorValuesTypeAndShapeInfo() + /// for sparse tensors + void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const; + + /// + /// Returns a const typed pointer to the tensor contained data. + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// + /// const pointer to data, no copies made + template + const R* GetTensorData() const; ///< Wraps OrtApi::GetTensorMutableData /// + + /// + /// Returns a non-typed pointer to a tensor contained data. + /// + /// const pointer to data, no copies made + const void* GetTensorRawData() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TypeInfo + TypeInfo GetTypeInfo() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TensorTypeAndShapeInfo + TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; + + /// + /// This API returns information about the memory allocation used to hold data. + /// + /// Non owning instance of MemoryInfo + ConstMemoryInfo GetTensorMemoryInfo() const; + + /// + /// The API copies UTF-8 encoded bytes for the requested string element + /// contained within a tensor or a sparse tensor into a provided buffer. + /// Use GetStringTensorElementLength() to obtain the length of the buffer to allocate. + /// + /// + /// + /// + void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const; + + /// + /// Returns string tensor UTF-8 encoded string element. + /// Use of this API is recommended over GetStringTensorElement() that takes void* buffer pointer. + /// + /// + /// std::string + std::string GetStringTensorElement(size_t element_index) const; + + /// + /// The API returns a byte length of UTF-8 encoded string element + /// contained in either a tensor or a spare tensor values. + /// + /// + /// byte length for the specified string element + size_t GetStringTensorElementLength(size_t element_index) const; + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// The API returns the sparse data format this OrtValue holds in a sparse tensor. + /// If the sparse tensor was not fully constructed, i.e. Use*() or Fill*() API were not used + /// the value returned is ORT_SPARSE_UNDEFINED. + /// + /// Format enum + OrtSparseFormat GetSparseFormat() const; + + /// + /// The API returns type and shape information for stored non-zero values of the + /// sparse tensor. Use GetSparseTensorValues() to obtain values buffer pointer. + /// + /// TensorTypeAndShapeInfo values information + TensorTypeAndShapeInfo GetSparseTensorValuesTypeAndShapeInfo() const; + + /// + /// The API returns type and shape information for the specified indices. Each supported + /// indices have their own enum values even if a give format has more than one kind of indices. + /// Use GetSparseTensorIndicesData() to obtain pointer to indices buffer. + /// + /// enum requested + /// type and shape information + TensorTypeAndShapeInfo GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat format) const; + + /// + /// The API retrieves a pointer to the internal indices buffer. The API merely performs + /// a convenience data type casting on the return type pointer. Make sure you are requesting + /// the right type, use GetSparseTensorIndicesTypeShapeInfo(); + /// + /// type to cast to + /// requested indices kind + /// number of indices entries + /// Pinter to the internal sparse tensor buffer containing indices. Do not free this pointer. + template + const R* GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const; + + /// + /// Returns true if the OrtValue contains a sparse tensor + /// + /// + bool IsSparseTensor() const; + + /// + /// The API returns a pointer to an internal buffer of the sparse tensor + /// containing non-zero values. The API merely does casting. Make sure you + /// are requesting the right data type by calling GetSparseTensorValuesTypeAndShapeInfo() + /// first. + /// + /// numeric data types only. Use GetStringTensor*() to retrieve strings. + /// a pointer to the internal values buffer. Do not free this pointer. + template + const R* GetSparseTensorValues() const; + +#endif +}; + +template +struct ValueImpl : ConstValueImpl { + using B = ConstValueImpl; + using B::B; + + /// + /// Returns a non-const typed pointer to an OrtValue/Tensor contained buffer + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// non-const pointer to data, no copies made + template + R* GetTensorMutableData(); + + /// + /// Returns a non-typed non-const pointer to a tensor contained data. + /// + /// pointer to data, no copies made + void* GetTensorMutableRawData(); + + /// + // Obtain a reference to an element of data at the location specified + /// by the vector of dims. + /// + /// + /// [in] expressed by a vecotr of dimensions offsets + /// + template + R& At(const std::vector& location); + + /// + /// Set all strings at once in a string tensor + /// + /// [in] An array of strings. Each string in this array must be null terminated. + /// [in] Count of strings in s (Must match the size of \p value's tensor shape) + void FillStringTensor(const char* const* s, size_t s_len); + + /// + /// Set a single string in a string tensor + /// + /// [in] A null terminated UTF-8 encoded string + /// [in] Index of the string in the tensor to set + void FillStringTensorElement(const char* s, size_t index); + + /// + /// Allocate if necessary and obtain a pointer to a UTF-8 + /// encoded string element buffer indexed by the flat element index, + /// of the specified length. + /// + /// This API is for advanced usage. It avoids a need to construct + /// an auxiliary array of string pointers, and allows to write data directly + /// (do not zero terminate). + /// + /// + /// + /// a pointer to a writable buffer + char* GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length); + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// Supplies COO format specific indices and marks the contained sparse tensor as being a COO format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with indices. Use nullptr for fully sparse tensors. + /// number of indices entries. Use 0 for fully sparse tensors + void UseCooIndices(int64_t* indices_data, size_t indices_num); + + /// + /// Supplies CSR format specific indices and marks the contained sparse tensor as being a CSR format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with inner indices or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to the user allocated buffer with outer indices or nullptr for fully sparse tensors + /// number of csr outer indices or 0 for fully sparse tensors + void UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num); + + /// + /// Supplies BlockSparse format specific indices and marks the contained sparse tensor as being a BlockSparse format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// indices shape or a {0} for fully sparse + /// user allocated buffer with indices or nullptr for fully spare tensors + void UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and COO indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information. + /// coo indices buffer or nullptr for fully sparse data + /// number of COO indices or 0 for fully sparse data + void FillSparseTensorCoo(const OrtMemoryInfo* data_mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and CSR indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// csr inner indices pointer or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to csr indices data or nullptr for fully sparse tensors + /// number of csr outer indices or 0 + void FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and BlockSparse indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// indices shape. use {0} for fully sparse tensors + /// pointer to indices data or nullptr for fully sparse tensors + void FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data); + +#endif +}; + +} // namespace detail + +using ConstValue = detail::ConstValueImpl>; +using UnownedValue = detail::ValueImpl>; + +/** \brief Wrapper around ::OrtValue + * + */ +struct Value : detail::ValueImpl { + using Base = detail::ValueImpl; + using OrtSparseValuesParam = detail::OrtSparseValuesParam; + using Shape = detail::Shape; + + explicit Value(std::nullptr_t) {} ///< Create an empty Value object, must be assigned a valid one to be used + explicit Value(OrtValue* p) : Base{p} {} ///< Used for interop with the C API + Value(Value&&) = default; + Value& operator=(Value&&) = default; + + ConstValue GetConst() const { return ConstValue{this->p_}; } + UnownedValue GetUnowned() const { return UnownedValue{this->p_}; } + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_element_count The number of elements in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len); + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_byte_count The number of bytes in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a tensor using a supplied OrtAllocator. Wraps OrtApi::CreateTensorAsOrtValue. + * This overload will allocate the buffer for the tensor according to the supplied shape and data type. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len); + + /** \brief Creates an OrtValue with a tensor using the supplied OrtAllocator. + * Wraps OrtApi::CreateTensorAsOrtValue. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a Map Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release keys and values after the call + * returns. + * + * \param keys an OrtValue containing a tensor with primitive data type keys. + * \param values an OrtValue that may contain a tensor. Ort currently supports only primitive data type values. + */ + static Value CreateMap(const Value& keys, const Value& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue with a Sequence Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release the values after the call + * returns. + * + * \param values a vector of OrtValues that must have the same Onnx value type. + */ + static Value CreateSequence(const std::vector& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue wrapping an Opaque type. + * This is used for experimental support of non-tensor types. + * + * \tparam T - the type of the value. + * \param domain - zero terminated utf-8 string. Domain of the type. + * \param type_name - zero terminated utf-8 string. Name of the type. + * \param value - the value to be wrapped. + */ + template + static Value CreateOpaque(const char* domain, const char* type_name, const T& value); ///< Wraps OrtApi::CreateOpaqueValue + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// This is a simple forwarding method to the other overload that helps deducing + /// data type enum value from the type of the buffer. + /// + /// numeric datatype. This API is not suitable for strings. + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// + template + static Value CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape); + + /// + /// Creates an OrtValue instance containing SparseTensor. This constructs + /// a sparse tensor that makes use of user allocated buffers. It does not make copies + /// of the user provided data and does not modify it. The lifespan of user provided buffers should + /// eclipse the life span of the resulting OrtValue. This call constructs an instance that only contain + /// a pointer to non-zero values. To fully populate the sparse tensor call UseIndices() API below + /// to supply a sparse format specific indices. + /// This API is not suitable for string data. Use CreateSparseTensor() with allocator specified so strings + /// can be properly copied into the allocated buffer. + /// + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// data type + /// Ort::Value instance containing SparseTensor + static Value CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type); + + /// + /// This is a simple forwarding method to the below CreateSparseTensor. + /// This helps to specify data type enum in terms of C++ data type. + /// Use CreateSparseTensor + /// + /// numeric data type only. String data enum must be specified explicitly. + /// allocator to use + /// a would be dense shape of the tensor + /// Ort::Value + template + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape); + + /// + /// Creates an instance of OrtValue containing sparse tensor. The created instance has no data. + /// The data must be supplied by on of the FillSparseTensor() methods that take both non-zero values + /// and indices. The data will be copied into a buffer that would be allocated using the supplied allocator. + /// Use this API to create OrtValues that contain sparse tensors with all supported data types including + /// strings. + /// + /// allocator to use. The allocator lifespan must eclipse that of the resulting OrtValue + /// a would be dense shape of the tensor + /// data type + /// an instance of Ort::Value + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, ONNXTensorElementDataType type); + +#endif // !defined(DISABLE_SPARSE_TENSORS) +}; + +/// +/// Represents native memory allocation coming from one of the +/// OrtAllocators registered with OnnxRuntime. +/// Use it to wrap an allocation made by an allocator +/// so it can be automatically released when no longer needed. +/// +struct MemoryAllocation { + MemoryAllocation(OrtAllocator* allocator, void* p, size_t size); + ~MemoryAllocation(); + MemoryAllocation(const MemoryAllocation&) = delete; + MemoryAllocation& operator=(const MemoryAllocation&) = delete; + MemoryAllocation(MemoryAllocation&&) noexcept; + MemoryAllocation& operator=(MemoryAllocation&&) noexcept; + + void* get() { return p_; } + size_t size() const { return size_; } + + private: + OrtAllocator* allocator_; + void* p_; + size_t size_; +}; + +namespace detail { +template +struct AllocatorImpl : Base { + using B = Base; + using B::B; + + void* Alloc(size_t size); + MemoryAllocation GetAllocation(size_t size); + void Free(void* p); + ConstMemoryInfo GetInfo() const; +}; + +} // namespace detail + +/** \brief Wrapper around ::OrtAllocator default instance that is owned by Onnxruntime + * + */ +struct AllocatorWithDefaultOptions : detail::AllocatorImpl> { + explicit AllocatorWithDefaultOptions(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + AllocatorWithDefaultOptions(); +}; + +/** \brief Wrapper around ::OrtAllocator + * + */ +struct Allocator : detail::AllocatorImpl { + explicit Allocator(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + Allocator(const Session& session, const OrtMemoryInfo*); +}; + +using UnownedAllocator = detail::AllocatorImpl>; + +namespace detail { +namespace binding_utils { +// Bring these out of template +std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator*); +std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator*); +} // namespace binding_utils + +template +struct ConstIoBindingImpl : Base { + using B = Base; + using B::B; + + std::vector GetOutputNames() const; + std::vector GetOutputNames(OrtAllocator*) const; + std::vector GetOutputValues() const; + std::vector GetOutputValues(OrtAllocator*) const; +}; + +template +struct IoBindingImpl : ConstIoBindingImpl { + using B = ConstIoBindingImpl; + using B::B; + + void BindInput(const char* name, const Value&); + void BindOutput(const char* name, const Value&); + void BindOutput(const char* name, const OrtMemoryInfo*); + void ClearBoundInputs(); + void ClearBoundOutputs(); + void SynchronizeInputs(); + void SynchronizeOutputs(); +}; + +} // namespace detail + +using ConstIoBinding = detail::ConstIoBindingImpl>; +using UnownedIoBinding = detail::IoBindingImpl>; + +/** \brief Wrapper around ::OrtIoBinding + * + */ +struct IoBinding : detail::IoBindingImpl { + explicit IoBinding(std::nullptr_t) {} ///< Create an empty object for convenience. Sometimes, we want to initialize members later. + explicit IoBinding(Session& session); + ConstIoBinding GetConst() const { return ConstIoBinding{this->p_}; } + UnownedIoBinding GetUnowned() const { return UnownedIoBinding{this->p_}; } +}; + +/*! \struct Ort::ArenaCfg + * \brief it is a structure that represents the configuration of an arena based allocator + * \details Please see docs/C_API.md for details + */ +struct ArenaCfg : detail::Base { + explicit ArenaCfg(std::nullptr_t) {} ///< Create an empty ArenaCfg object, must be assigned a valid one to be used + /** + * Wraps OrtApi::CreateArenaCfg + * \param max_mem - use 0 to allow ORT to choose the default + * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default + * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default + * See docs/C_API.md for details on what the following parameters mean and how to choose these values + */ + ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk); +}; + +// +// Custom OPs (only needed to implement custom OPs) +// + +/// +/// This struct provides life time management for custom op attribute +/// +struct OpAttr : detail::Base { + OpAttr(const char* name, const void* data, int len, OrtOpAttrType type); +}; + +/** + * Macro that logs a message using the provided logger. Throws an exception if OrtApi::Logger_LogMessage fails. + * Example: ORT_CXX_LOG(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a message using the provided logger. Can be used in noexcept code since errors are silently ignored. + * Example: ORT_CXX_LOG_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG_NOEXCEPT(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Throws an exception if + * OrtApi::Logger_LogMessage fails or if a formatting error occurs. + * Example: ORT_CXX_LOGF(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Can be used in noexcept code since errors + * are silently ignored. + * Example: ORT_CXX_LOGF_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF_NOEXCEPT(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/// +/// This class represents an ONNX Runtime logger that can be used to log information with an +/// associated severity level and source code location (file path, line number, function name). +/// +/// A Logger can be obtained from within custom operators by calling Ort::KernelInfo::GetLogger(). +/// Instances of Ort::Logger are the size of two pointers and can be passed by value. +/// +/// Use the ORT_CXX_LOG macros to ensure the source code location is set properly from the callsite +/// and to take advantage of a cached logging severity level that can bypass calls to the underlying C API. +/// +struct Logger { + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + Logger() = default; + + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + explicit Logger(std::nullptr_t) {} + + /** + * Creates a logger from an ::OrtLogger instance. Caches the logger's current severity level by calling + * OrtApi::Logger_GetLoggingSeverityLevel. Throws an exception if OrtApi::Logger_GetLoggingSeverityLevel fails. + * + * \param logger The ::OrtLogger to wrap. + */ + explicit Logger(const OrtLogger* logger); + + ~Logger() = default; + + Logger(const Logger&) = default; + Logger& operator=(const Logger&) = default; + + Logger(Logger&& v) noexcept = default; + Logger& operator=(Logger&& v) noexcept = default; + + /** + * Returns the logger's current severity level from the cached member. + * + * \return The current ::OrtLoggingLevel. + */ + OrtLoggingLevel GetLoggingSeverityLevel() const noexcept; + + /** + * Logs the provided message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOG or ORT_CXX_LOG_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param message The message to log. + * \return A Ort::Status value to indicate error or success. + */ + Status LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept; + + /** + * Logs a printf-like formatted message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOGF or ORT_CXX_LOGF_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. Returns an error status if a formatting error occurs. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param args Zero or more variadic arguments referenced by the format string. + * \return A Ort::Status value to indicate error or success. + */ + template + Status LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* format, Args&&... args) const noexcept; + + private: + const OrtLogger* logger_{}; + OrtLoggingLevel cached_severity_level_{}; +}; + +/// +/// This class wraps a raw pointer OrtKernelContext* that is being passed +/// to the custom kernel Compute() method. Use it to safely access context +/// attributes, input and output parameters with exception safety guarantees. +/// See usage example in onnxruntime/test/testdata/custom_op_library/custom_op_library.cc +/// +struct KernelContext { + explicit KernelContext(OrtKernelContext* context); + size_t GetInputCount() const; + size_t GetOutputCount() const; + ConstValue GetInput(size_t index) const; + UnownedValue GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const; + UnownedValue GetOutput(size_t index, const std::vector& dims) const; + void* GetGPUComputeStream() const; + Logger GetLogger() const; + OrtAllocator* GetAllocator(const OrtMemoryInfo& memory_info) const; + + private: + OrtKernelContext* ctx_; +}; + +struct KernelInfo; + +namespace detail { +namespace attr_utils { +void GetAttr(const OrtKernelInfo* p, const char* name, float&); +void GetAttr(const OrtKernelInfo* p, const char* name, int64_t&); +void GetAttr(const OrtKernelInfo* p, const char* name, std::string&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +} // namespace attr_utils + +template +struct KernelInfoImpl : Base { + using B = Base; + using B::B; + + KernelInfo Copy() const; + + template // R is only implemented for float, int64_t, and string + R GetAttribute(const char* name) const { + R val; + attr_utils::GetAttr(this->p_, name, val); + return val; + } + + template // R is only implemented for std::vector, std::vector + std::vector GetAttributes(const char* name) const { + std::vector result; + attr_utils::GetAttrs(this->p_, name, result); + return result; + } + + Value GetTensorAttribute(const char* name, OrtAllocator* allocator) const; + + size_t GetInputCount() const; + size_t GetOutputCount() const; + + std::string GetInputName(size_t index) const; + std::string GetOutputName(size_t index) const; + + TypeInfo GetInputTypeInfo(size_t index) const; + TypeInfo GetOutputTypeInfo(size_t index) const; + + ConstValue GetTensorConstantInput(size_t index, int* is_constant) const; + + std::string GetNodeName() const; + Logger GetLogger() const; +}; + +} // namespace detail + +using ConstKernelInfo = detail::KernelInfoImpl>; + +/// +/// This struct owns the OrtKernInfo* pointer when a copy is made. +/// For convenient wrapping of OrtKernelInfo* passed to kernel constructor +/// and query attributes, warp the pointer with Ort::Unowned instance +/// so it does not destroy the pointer the kernel does not own. +/// +struct KernelInfo : detail::KernelInfoImpl { + explicit KernelInfo(std::nullptr_t) {} ///< Create an empty instance to initialize later + explicit KernelInfo(OrtKernelInfo* info); ///< Take ownership of the instance + ConstKernelInfo GetConst() const { return ConstKernelInfo{this->p_}; } +}; + +/// +/// Create and own custom defined operation. +/// +struct Op : detail::Base { + explicit Op(std::nullptr_t) {} ///< Create an empty Operator object, must be assigned a valid one to be used + + explicit Op(OrtOp*); ///< Take ownership of the OrtOp + + static Op Create(const OrtKernelInfo* info, const char* op_name, const char* domain, + int version, const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, + size_t attr_count, + size_t input_count, size_t output_count); + + void Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count); + + // For easier refactoring + void Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count); +}; + +template +struct CustomOpBase : OrtCustomOp { + CustomOpBase() { + OrtCustomOp::version = ORT_API_VERSION; + OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast(this_)->GetName(); }; + + OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast(this_)->GetExecutionProviderType(); }; + + OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetInputTypeCount(); }; + OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputType(index); }; + OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputMemoryType(index); }; + + OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetOutputTypeCount(); }; + OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputType(index); }; + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +#pragma warning(disable : 26409) +#endif + OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast(op_kernel); }; +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif + OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputCharacteristic(index); }; + OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputCharacteristic(index); }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicInputMinArity(); }; + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicInputHomogeneity()); }; + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicOutputMinArity(); }; + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicOutputHomogeneity()); }; +#ifdef __cpp_if_constexpr + if constexpr (WithStatus) { +#else + if (WithStatus) { +#endif + OrtCustomOp::CreateKernelV2 = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info, void** op_kernel) -> OrtStatusPtr { + return static_cast(this_)->CreateKernelV2(*api, info, op_kernel); + }; + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + return static_cast(op_kernel)->ComputeV2(context); + }; + } else { + OrtCustomOp::CreateKernelV2 = nullptr; + OrtCustomOp::KernelComputeV2 = nullptr; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast(this_)->CreateKernel(*api, info); }; + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + static_cast(op_kernel)->Compute(context); + }; + } + } + + // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider + const char* GetExecutionProviderType() const { return nullptr; } + + // Default implementations of GetInputCharacteristic() and GetOutputCharacteristic() below + // (inputs and outputs are required by default) + OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + // Default implemention of GetInputMemoryType() that returns OrtMemTypeDefault + OrtMemType GetInputMemoryType(size_t /*index*/) const { + return OrtMemTypeDefault; + } + + // Default implementation of GetVariadicInputMinArity() returns 1 to specify that a variadic input + // should expect at least 1 argument. + int GetVariadicInputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicInputHomegeneity() returns true to specify that all arguments + // to a variadic input should be of the same type. + bool GetVariadicInputHomogeneity() const { + return true; + } + + // Default implementation of GetVariadicOutputMinArity() returns 1 to specify that a variadic output + // should produce at least 1 output value. + int GetVariadicOutputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicOutputHomegeneity() returns true to specify that all output values + // produced by a variadic output should be of the same type. + bool GetVariadicOutputHomogeneity() const { + return true; + } + + // Declare list of session config entries used by this Custom Op. + // Implement this function in order to get configs from CustomOpBase::GetSessionConfigs(). + // This default implementation returns an empty vector of config entries. + std::vector GetSessionConfigKeys() const { + return std::vector{}; + } + + protected: + // Helper function that returns a map of session config entries specified by CustomOpBase::GetSessionConfigKeys. + void GetSessionConfigs(std::unordered_map& out, ConstSessionOptions options) const; +}; + +} // namespace Ort + +#include "onnxruntime_cxx_inline.h" diff --git a/runexamples/cpp/onnx/include/onnxruntime_cxx_inline.h b/runexamples/cpp/onnx/include/onnxruntime_cxx_inline.h new file mode 100644 index 0000000..2217283 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_cxx_inline.h @@ -0,0 +1,1886 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead. +// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead. +// +// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter +// the main C++ file with implementation details. + +#include + +namespace Ort { + +namespace detail { +inline void ThrowStatus(const Status& st) { + std::string error_message = st.GetErrorMessage(); + OrtErrorCode error_code = st.GetErrorCode(); + ORT_CXX_API_THROW(std::move(error_message), error_code); +} +} // namespace detail + +inline void ThrowOnError(OrtStatus* ort_status) { + if (ort_status) { + Ort::Status st(ort_status); + detail::ThrowStatus(st); + } +} + +inline void ThrowOnError(const Status& st) { + if (st) { + detail::ThrowStatus(st); + } +} + +inline Status::Status(OrtStatus* status) noexcept : Base{status} { +} + +inline Status::Status(const std::exception& e) noexcept { + p_ = GetApi().CreateStatus(ORT_FAIL, e.what()); +} + +inline Status::Status(const Exception& e) noexcept { + p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what()); +} + +inline Status::Status(const char* message, OrtErrorCode code) noexcept { + p_ = GetApi().CreateStatus(code, message); +} + +inline std::string Status::GetErrorMessage() const { + std::string message(GetApi().GetErrorMessage(p_)); + return message; +} + +inline OrtErrorCode Status::GetErrorCode() const { + return GetApi().GetErrorCode(p_); +} + +inline bool Status::IsOK() const noexcept { + return (p_ == nullptr); +} + +// This template converts a C++ type into it's ONNXTensorElementDataType +template +struct TypeToTensorType; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; +}; + +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ; +}; + +inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; +} + +inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); +} + +inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size) + : allocator_(allocator), p_(p), size_(size) { +} + +inline MemoryAllocation::~MemoryAllocation() { + if (p_ != nullptr) { + // We do not throw out of destructor + auto ret = GetApi().AllocatorFree(allocator_, p_); + static_cast(ret); + } +} + +inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) { + *this = std::move(o); +} + +inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept { + OrtAllocator* alloc = nullptr; + void* p = nullptr; + size_t sz = 0; + + // Swap out this + std::swap(alloc, allocator_); + std::swap(p, p_); + std::swap(sz, size_); + + // Swap with incoming + std::swap(allocator_, o.allocator_); + std::swap(p_, o.p_); + std::swap(size_, o.size_); + + // Destroy this instance if needed + MemoryAllocation this_alloc(alloc, p, sz); + return *this; +} + +namespace detail { + +template +inline void* AllocatorImpl::Alloc(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + return out; +} + +template +inline MemoryAllocation AllocatorImpl::GetAllocation(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + MemoryAllocation result(this->p_, out, size); + return result; +} + +template +inline void AllocatorImpl::Free(void* p) { + ThrowOnError(GetApi().AllocatorFree(this->p_, p)); +} + +template +inline ConstMemoryInfo AllocatorImpl::GetInfo() const { + const OrtMemoryInfo* out; + ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out)); + return ConstMemoryInfo{out}; +} + +} // namespace detail + +inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() { + ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_)); +} + +inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_)); +} + +namespace detail { + +template +inline std::string MemoryInfoImpl::GetAllocatorName() const { + const char* name = nullptr; + ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name)); + return std::string(name); +} + +template +inline OrtAllocatorType MemoryInfoImpl::GetAllocatorType() const { + OrtAllocatorType type; + ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type)); + return type; +} + +template +inline int MemoryInfoImpl::GetDeviceId() const { + int id = 0; + ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id)); + return id; +} + +template +inline OrtMemoryInfoDeviceType MemoryInfoImpl::GetDeviceType() const { + OrtMemoryInfoDeviceType type; + GetApi().MemoryInfoGetDeviceType(this->p_, &type); + return type; +} + +template +inline OrtMemType MemoryInfoImpl::GetMemoryType() const { + OrtMemType type; + ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type)); + return type; +} + +template +template +inline bool MemoryInfoImpl::operator==(const MemoryInfoImpl& o) const { + int comp_result = 0; + ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result)); + return comp_result == 0; +} + +} // namespace detail + +inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) { + OrtMemoryInfo* p; + ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p)); + return MemoryInfo(p); +} + +inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) { + ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_)); +} + +namespace detail { +template +inline std::vector ConstIoBindingImpl::GetOutputNames() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputNames(OrtAllocator* allocator) const { + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues(OrtAllocator* allocator) const { + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline void IoBindingImpl::BindInput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindInput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindOutput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info)); +} + +template +inline void IoBindingImpl::ClearBoundInputs() { + GetApi().ClearBoundInputs(this->p_); +} + +template +inline void IoBindingImpl::ClearBoundOutputs() { + GetApi().ClearBoundOutputs(this->p_); +} + +template +inline void IoBindingImpl::SynchronizeInputs() { + ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_)); +} + +template +inline void IoBindingImpl::SynchronizeOutputs() { + ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_)); +} + +namespace binding_utils { +inline std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + auto free_fn = detail::AllocatedFree(allocator); + using Ptr = std::unique_ptr; + + char* buffer = nullptr; + size_t* lengths = nullptr; + size_t count = 0; + ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count)); + + if (count == 0) { + return result; + } + + Ptr buffer_g(buffer, free_fn); + Ptr lengths_g(lengths, free_fn); + + result.reserve(count); + for (size_t i = 0; i < count; ++i) { + auto sz = *lengths; + result.emplace_back(buffer, sz); + buffer += sz; + ++lengths; + } + return result; +} + +inline std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + size_t owned = 0; + size_t output_count = 0; + // Lambda to release the buffer when no longer needed and + // make sure that we destroy all instances on exception + auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) { + if (buffer) { + while (owned < output_count) { + auto* p = buffer + owned++; + GetApi().ReleaseValue(*p); + } + allocator->Free(allocator, buffer); + } + }; + using Ptr = std::unique_ptr; + + OrtValue** output_buffer = nullptr; + ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count)); + if (output_count == 0) { + return result; + } + + Ptr buffer_g(output_buffer, free_fn); + + result.reserve(output_count); + for (size_t i = 0; i < output_count; ++i) { + result.emplace_back(output_buffer[i]); + ++owned; + } + return result; +} + +} // namespace binding_utils +} // namespace detail + +inline IoBinding::IoBinding(Session& session) { + ThrowOnError(GetApi().CreateIoBinding(session, &this->p_)); +} + +inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) { + ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_)); +} + +inline ThreadingOptions::ThreadingOptions() { + ThrowOnError(GetApi().CreateThreadingOptions(&p_)); +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) { + ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() { + ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn)); + return *this; +} + +inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) { + ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env& Env::EnableTelemetryEvents() { + ThrowOnError(GetApi().EnableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::DisableTelemetryEvents() { + ThrowOnError(GetApi().DisableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) { + ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) { + ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { + std::vector keys, values; + auto num_entries = options.size(); + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + for (const auto& entry : options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries)); + return *this; +} + +inline CustomOpDomain::CustomOpDomain(const char* domain) { + ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_)); +} + +inline void CustomOpDomain::Add(const OrtCustomOp* op) { + ThrowOnError(GetApi().CustomOpDomain_Add(p_, op)); +} + +inline RunOptions::RunOptions() { + ThrowOnError(GetApi().CreateRunOptions(&p_)); +} + +inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level)); + return *this; +} + +inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level)); + return *this; +} + +inline int RunOptions::GetRunLogVerbosityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out)); + return out; +} + +inline int RunOptions::GetRunLogSeverityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::SetRunTag(const char* run_tag) { + ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag)); + return *this; +} + +inline const char* RunOptions::GetRunTag() const { + const char* out; + ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value)); + return *this; +} + +inline RunOptions& RunOptions::SetTerminate() { + ThrowOnError(GetApi().RunOptionsSetTerminate(p_)); + return *this; +} + +inline RunOptions& RunOptions::UnsetTerminate() { + ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_)); + return *this; +} + +namespace detail { + +template +inline Ort::SessionOptions ConstSessionOptionsImpl::Clone() const { + OrtSessionOptions* out; + ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out)); + return SessionOptions{out}; +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntry(const char* config_key) const { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline bool ConstSessionOptionsImpl::HasConfigEntry(const char* config_key) const { + int out = 0; + Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out)); + return static_cast(out); +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntryOrDefault(const char* config_key, const std::string& def) { + if (!this->HasConfigEntry(config_key)) { + return def; + } + + return this->GetConfigEntry(config_key); +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) { + ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) { + ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableProfiling(const ORTCHAR_T* profile_file_prefix) { + ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableProfiling() { + ThrowOnError(GetApi().DisableProfiling(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableOrtCustomOps() { + ThrowOnError(GetApi().EnableOrtCustomOps(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableMemPattern() { + ThrowOnError(GetApi().EnableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableMemPattern() { + ThrowOnError(GetApi().DisableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableCpuMemArena() { + ThrowOnError(GetApi().EnableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableCpuMemArena() { + ThrowOnError(GetApi().DisableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetExecutionMode(ExecutionMode execution_mode) { + ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogId(const char* logid) { + ThrowOnError(GetApi().SetSessionLogId(this->p_, logid)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogSeverityLevel(int level) { + ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::Add(OrtCustomOpDomain* custom_op_domain) { + ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddInitializer(const char* name, const OrtValue* ort_val) { + ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisablePerSessionThreads() { + ThrowOnError(GetApi().DisablePerSessionThreads(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializers(const std::vector& names, + const std::vector& ort_values) { + const size_t inputs_num = names.size(); + if (inputs_num != ort_values.size()) { + ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT); + } + std::vector names_ptr; + std::vector ort_values_ptrs; + names_ptr.reserve(inputs_num); + ort_values_ptrs.reserve(inputs_num); + for (size_t i = 0; i < inputs_num; ++i) { + names_ptr.push_back(names[i].c_str()); + ort_values_ptrs.push_back(ort_values[i]); + } + ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider( + const std::string& provider_name, + const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(), + keys.data(), values.data(), num_entries)); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, + const CustomOpConfigs& custom_op_configs) { + // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by + // the custom op library. + for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) { + AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str()); + } + + ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsUsingFunction(const char* registration_function_name) { + ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name)); + return *this; +} + +/// Session +template +inline size_t ConstSessionImpl::GetInputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOutputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOverridableInitializerCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out)); + return out; +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline uint64_t ConstSessionImpl::GetProfilingStartTimeNs() const { + uint64_t out; + ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out)); + return out; +} + +template +inline ModelMetadata ConstSessionImpl::GetModelMetadata() const { + OrtModelMetadata* out; + ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out)); + return ModelMetadata{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOverridableInitializerTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline std::vector SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count) { + std::vector output_values; + output_values.reserve(output_count); + for (size_t i = 0; i < output_count; i++) + output_values.emplace_back(nullptr); + Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count); + return output_values; +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values)); +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const IoBinding& io_binding) { + ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding)); +} + +template +inline void SessionImpl::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) { + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names, + ort_input_values, input_count, output_names, output_count, + ort_output_values, callback, user_data)); +} + +template +inline AllocatedStringPtr SessionImpl::EndProfilingAllocated(OrtAllocator* allocator) { + char* out = nullptr; + ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +} // namespace detail + +inline SessionOptions::SessionOptions() { + ThrowOnError(GetApi().CreateSessionOptions(&this->p_)); +} + +/// CustomOpConfigs +inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) { + std::string config_key = "custom_op."; + + config_key += custom_op_name; + config_key += "."; + config_key += config; + + return config_key; +} + +inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) { + const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key); + flat_configs_[full_flat_key] = config_value; + return *this; +} + +inline const std::unordered_map& CustomOpConfigs::GetFlattenedConfigs() const { + return flat_configs_; +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_)); +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options, + prepacked_weights_container, &this->p_)); +} + +inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline std::vector ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const { + auto deletor = detail::AllocatedFree(allocator); + std::vector result; + + char** out = nullptr; + int64_t num_keys = 0; + ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys)); + if (num_keys <= 0) { + return result; + } + + // array of pointers will be freed + std::unique_ptr array_guard(out, deletor); + // reserve may throw + auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); }; + std::unique_ptr strings_guard(out, strings_deletor); + result.reserve(static_cast(num_keys)); + strings_guard.release(); + for (int64_t i = 0; i < num_keys; ++i) { + result.push_back(AllocatedStringPtr(out[i], deletor)); + } + + return result; +} + +inline int64_t ModelMetadata::GetVersion() const { + int64_t out; + ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out)); + return out; +} + +namespace detail { + +template +inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl::GetElementType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetTensorElementType(this->p_, &out)); + return out; +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetElementCount() const { + size_t out; + ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out)); + return static_cast(out); +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetDimensionsCount() const { + size_t out; + ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out)); + return out; +} + +template +inline void TensorTypeAndShapeInfoImpl::GetDimensions(int64_t* values, size_t values_count) const { + ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count)); +} + +template +inline void TensorTypeAndShapeInfoImpl::GetSymbolicDimensions(const char** values, size_t values_count) const { + ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count)); +} + +template +inline std::vector TensorTypeAndShapeInfoImpl::GetShape() const { + std::vector out(GetDimensionsCount(), 0); + ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size())); + return out; +} + +template +inline ConstTensorTypeAndShapeInfo TypeInfoImpl::GetTensorTypeAndShapeInfo() const { + const OrtTensorTypeAndShapeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out)); + return ConstTensorTypeAndShapeInfo{out}; +} + +template +inline ConstSequenceTypeInfo TypeInfoImpl::GetSequenceTypeInfo() const { + const OrtSequenceTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out)); + return ConstSequenceTypeInfo{out}; +} + +template +inline ConstMapTypeInfo TypeInfoImpl::GetMapTypeInfo() const { + const OrtMapTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out)); + return ConstMapTypeInfo{out}; +} + +template +inline ONNXType TypeInfoImpl::GetONNXType() const { + ONNXType out; + ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out)); + return out; +} + +template +inline TypeInfo SequenceTypeInfoImpl::GetSequenceElementType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TypeInfo OptionalTypeInfoImpl::GetOptionalElementType() const { + OrtTypeInfo* info; + ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info)); + return TypeInfo{info}; +} + +template +inline ONNXTensorElementDataType MapTypeInfoImpl::GetMapKeyType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetMapKeyType(this->p_, &out)); + return out; +} + +template +inline TypeInfo MapTypeInfoImpl::GetMapValueType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetMapValueType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline ConstOptionalTypeInfo TypeInfoImpl::GetOptionalTypeInfo() const { + const OrtOptionalTypeInfo* info; + ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info)); + return ConstOptionalTypeInfo{info}; +} + +} // namespace detail + +namespace detail { + +template +template +inline void ConstValueImpl::GetOpaqueData(const char* domain, const char* type_name, R& out) const { + ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R))); +} + +template +inline bool ConstValueImpl::IsTensor() const { + int out; + ThrowOnError(GetApi().IsTensor(this->p_, &out)); + return out != 0; +} + +template +inline bool ConstValueImpl::HasValue() const { + int out; + ThrowOnError(GetApi().HasValue(this->p_, &out)); + return out != 0; +} + +template +inline size_t ConstValueImpl::GetCount() const { + size_t out; + ThrowOnError(GetApi().GetValueCount(this->p_, &out)); + return out; +} + +template +inline Value ConstValueImpl::GetValue(int index, OrtAllocator* allocator) const { + OrtValue* out; + ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out)); + return Value{out}; +} + +template +inline size_t ConstValueImpl::GetStringTensorDataLength() const { + size_t out; + ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out)); + return out; +} + +template +inline size_t ConstValueImpl::GetStringTensorElementLength(size_t element_index) const { + size_t out; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out)); + return out; +} + +template +template +inline const R* ConstValueImpl::GetTensorData() const { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), (void**)&out)); + return out; +} + +template +inline const void* ConstValueImpl::GetTensorRawData() const { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), &out)); + return out; +} + +template +inline TypeInfo ConstValueImpl::GetTypeInfo() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetTypeInfo(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetTensorTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline ConstMemoryInfo ConstValueImpl::GetTensorMemoryInfo() const { + const OrtMemoryInfo* mem_info; + ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info)); + return ConstMemoryInfo(mem_info); +} + +template +inline void ConstValueImpl::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const { + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer)); +} + +template +inline std::string ConstValueImpl::GetStringTensorElement(size_t element_index) const { + size_t buffer_length; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length)); + + std::string s; + s.resize(buffer_length); + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0])); + return s; +} + +template +inline void ConstValueImpl::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const { + ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count)); +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +inline OrtSparseFormat ConstValueImpl::GetSparseFormat() const { + OrtSparseFormat format; + ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format)); + return format; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorValuesTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out)); + return reinterpret_cast(out); +} + +template +inline bool ConstValueImpl::IsSparseTensor() const { + int out; + ThrowOnError(GetApi().IsSparseTensor(this->p_, &out)); + return out != 0; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorValues() const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out)); + return reinterpret_cast(out); +} + +#endif + +template +void ValueImpl::FillStringTensor(const char* const* s, size_t s_len) { + ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len)); +} + +template +void ValueImpl::FillStringTensorElement(const char* s, size_t index) { + ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index)); +} + +template +inline char* ValueImpl::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) { + char* result; + ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result)); + return result; +} + +template +void* ValueImpl::GetTensorMutableRawData() { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out)); + return out; +} + +template +template +R* ValueImpl::GetTensorMutableData() { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out)); + return out; +} + +template +template +R& ValueImpl::At(const std::vector& location) { + static_assert(!std::is_same::value, "this api does not support std::string"); + R* out; + ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out)); + return *out; +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +void ValueImpl::UseCooIndices(int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num)); +} + +template +void ValueImpl::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) { + ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num)); +} + +template +void ValueImpl::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) { + ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data)); +} + +template +void ValueImpl::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape, + values_param.values_shape_len, values_param.data.p_data, + indices_data, indices_num)); +} + +template +void ValueImpl::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num) { + ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + inner_indices_data, inner_indices_num, + outer_indices_data, outer_indices_num)); +} + +template +void ValueImpl::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data) { + ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + indices_shape.shape, indices_shape.shape_len, + indices_data)); +} + +#endif // !defined(DISABLE_SPARSE_TENSORS) + +} // namespace detail + +template +inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len) { + return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out)); + return Value{out}; +} + +template +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) { + return CreateTensor(allocator, shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out)); + return Value{out}; +} + +#if !defined(DISABLE_SPARSE_TENSORS) + +template +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape) { + return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len, + values_shape.shape, values_shape.shape_len, type, &out)); + return Value{out}; +} + +template +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) { + return CreateSparseTensor(allocator, dense_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out)); + return Value{out}; +} +#endif // !defined(DISABLE_SPARSE_TENSORS) + +inline Value Value::CreateMap(const Value& keys, const Value& values) { + OrtValue* out; + const OrtValue* inputs[2] = {keys, values}; + ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out)); + return Value{out}; +} + +inline Value Value::CreateSequence(const std::vector& values) { + OrtValue* out; + std::vector values_ort{values.data(), values.data() + values.size()}; + ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out)); + return Value{out}; +} + +template +inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) { + OrtValue* out; + ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out)); + return Value{out}; +} + +// +// Custom OP Inlines +// +inline Logger::Logger(const OrtLogger* logger) : logger_(logger) { + Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_)); +} + +inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept { + return cached_severity_level_; +} + +inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept { + OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number, + func_name); + return Status{status}; +} + +// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security) +// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply +// __attribute__(format(printf...)), which does not work with variadic templates. +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#pragma GCC diagnostic ignored "-Wformat-security" +#elif defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#pragma clang diagnostic ignored "-Wformat-security" +#endif +template +inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, + int line_number, const char* func_name, const char* format, + Args&&... args) const noexcept { + int msg_len = std::snprintf(nullptr, 0U, format, std::forward(args)...); + + if (msg_len < 0) { // Formatting error + return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL); + } + + OrtStatus* status = nullptr; + const size_t buffer_size = static_cast(msg_len) + 1U; + + constexpr size_t kStackBufferSize = 1024; + + if (buffer_size < kStackBufferSize) { + char buffer[kStackBufferSize]; + snprintf(buffer, kStackBufferSize, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name); + } else { + // std::make_unique is only supported starting at C++14. +#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900) + auto buffer = std::make_unique(buffer_size); +#else + std::unique_ptr buffer(new char[buffer_size]); +#endif + std::snprintf(buffer.get(), buffer_size, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name); + } + + return Status{status}; +} +// Re-enable -Wformat-nonliteral and -Wformat-security +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#elif defined(__clang__) +#pragma clang diagnostic pop +#endif + +inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) { +} + +inline size_t KernelContext::GetInputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out)); + return out; +} + +inline size_t KernelContext::GetOutputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out)); + return out; +} + +inline ConstValue KernelContext::GetInput(size_t index) const { + const OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out)); + return ConstValue{out}; +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out)); + return UnownedValue(out); +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector& dims) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out)); + return UnownedValue(out); +} + +inline void* KernelContext::GetGPUComputeStream() const { + void* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out)); + return out; +} + +inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const { + OrtAllocator* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out)); + return out; +} + +inline Logger KernelContext::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out)); + return Logger{out}; +} + +inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) { + Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_)); +} + +namespace detail { +template +inline KernelInfo KernelInfoImpl::Copy() const { + OrtKernelInfo* info_copy = nullptr; + Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy)); + return KernelInfo{info_copy}; +} + +template +inline size_t KernelInfoImpl::GetInputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t KernelInfoImpl::GetOutputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out)); + return out; +} + +template +inline std::string KernelInfoImpl::GetInputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline std::string KernelInfoImpl::GetOutputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline TypeInfo KernelInfoImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo KernelInfoImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline Value KernelInfoImpl::GetTensorAttribute(const char* name, OrtAllocator* allocator) const { + OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out)); + return Value{out}; +} + +template +inline ConstValue KernelInfoImpl::GetTensorConstantInput(size_t index, int* is_constant) const { + const OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out)); + return ConstValue{out}; +} + +template +inline std::string KernelInfoImpl::GetNodeName() const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline Logger KernelInfoImpl::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out)); + return Logger{out}; +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size)); + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size)); + out.swap(result); +} +} // namespace detail + +inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl{info} {} + +inline Op::Op(OrtOp* p) : Base(p) {} + +inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version, + const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, size_t attr_count, + size_t input_count, size_t output_count) { + static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*), + "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely"); + auto attr_input_values = reinterpret_cast(attr_values); + OrtOp* op; + Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values, + static_cast(type_constraint_count), + attr_input_values, + static_cast(attr_count), + static_cast(input_count), + static_cast(output_count), &op)); + return Op{op}; +} + +inline void Op::Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), + "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast(input_count), + ort_output_values, static_cast(output_count))); +} + +inline void Op::Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count) { + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast(input_count), + output_values, static_cast(output_count))); +} + +inline std::string GetVersionString() { + return OrtGetApiBase()->GetVersionString(); +} + +inline std::string GetBuildInfoString() { + return GetApi().GetBuildInfoString(); +} + +inline std::vector GetAvailableProviders() { + char** providers; + int len; + + auto release_fn = [&len](char** providers) { + // This should always return nullptr. + ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len)); + }; + + ThrowOnError(GetApi().GetAvailableProviders(&providers, &len)); + std::unique_ptr guard(providers, release_fn); + std::vector available_providers; + available_providers.reserve(static_cast(len)); + for (int i = 0; i < len; ++i) { + available_providers.emplace_back(providers[i]); + } + return available_providers; +} + +template +void CustomOpBase::GetSessionConfigs(std::unordered_map& out, + ConstSessionOptions options) const { + const TOp* derived = static_cast(this); + std::vector keys = derived->GetSessionConfigKeys(); + + out.reserve(keys.size()); + + std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), ""); + const size_t prefix_size = config_entry_key.length(); + + for (const auto& key : keys) { + config_entry_key.resize(prefix_size); + config_entry_key.append(key); + out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), ""); + } +} + +} // namespace Ort diff --git a/runexamples/cpp/onnx/include/onnxruntime_float16.h b/runexamples/cpp/onnx/include/onnxruntime_float16.h new file mode 100644 index 0000000..0b066a9 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_float16.h @@ -0,0 +1,540 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include + +namespace onnxruntime_float16 { + +namespace detail { + +enum class endian { +#if defined(_WIN32) + little = 0, + big = 1, + native = little, +#elif defined(__GNUC__) || defined(__clang__) + little = __ORDER_LITTLE_ENDIAN__, + big = __ORDER_BIG_ENDIAN__, + native = __BYTE_ORDER__, +#else +#error onnxruntime_float16::detail::endian is not implemented in this environment. +#endif +}; + +static_assert( + endian::native == endian::little || endian::native == endian::big, + "Only little-endian or big-endian native byte orders are supported."); + +} // namespace detail + +/// +/// Shared implementation between public and internal classes. CRTP pattern. +/// +template +struct Float16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + constexpr static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7C00U; + static constexpr uint16_t kPositiveInfinityBits = 0x7C00U; + static constexpr uint16_t kNegativeInfinityBits = 0xFC00U; + static constexpr uint16_t kPositiveQNaNBits = 0x7E00U; + static constexpr uint16_t kNegativeQNaNBits = 0xFE00U; + static constexpr uint16_t kEpsilonBits = 0x4170U; + static constexpr uint16_t kMinValueBits = 0xFBFFU; // Minimum normal number + static constexpr uint16_t kMaxValueBits = 0x7BFFU; // Largest normal number + static constexpr uint16_t kOneBits = 0x3C00U; + static constexpr uint16_t kMinusOneBits = 0xBC00U; + + uint16_t val{0}; + + Float16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const Float16Impl& lhs, const Float16Impl& rhs) noexcept { + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } + + bool operator==(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; + } + + bool operator!=(const Float16Impl& rhs) const noexcept { return !(*this == rhs); } + + bool operator<(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); + } +}; + +// The following Float16_t conversions are based on the code from +// Eigen library. + +// The conversion routines are Copyright (c) Fabian Giesen, 2016. +// The original license follows: +// +// Copyright (c) Fabian Giesen, 2016 +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +namespace detail { +union float32_bits { + unsigned int u; + float f; +}; +} // namespace detail + +template +inline constexpr uint16_t Float16Impl::ToUint16Impl(float v) noexcept { + detail::float32_bits f{}; + f.f = v; + + constexpr detail::float32_bits f32infty = {255 << 23}; + constexpr detail::float32_bits f16max = {(127 + 16) << 23}; + constexpr detail::float32_bits denorm_magic = {((127 - 15) + (23 - 10) + 1) << 23}; + constexpr unsigned int sign_mask = 0x80000000u; + uint16_t val = static_cast(0x0u); + + unsigned int sign = f.u & sign_mask; + f.u ^= sign; + + // NOTE all the integer compares in this function can be safely + // compiled into signed compares since all operands are below + // 0x80000000. Important if you want fast straight SSE2 code + // (since there's no unsigned PCMPGTD). + + if (f.u >= f16max.u) { // result is Inf or NaN (all exponent bits set) + val = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf + } else { // (De)normalized number or zero + if (f.u < (113 << 23)) { // resulting FP16 is subnormal or zero + // use a magic value to align our 10 mantissa bits at the bottom of + // the float. as long as FP addition is round-to-nearest-even this + // just works. + f.f += denorm_magic.f; + + // and one integer subtract of the bias later, we have our final float! + val = static_cast(f.u - denorm_magic.u); + } else { + unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd + + // update exponent, rounding bias part 1 + // Equivalent to `f.u += ((unsigned int)(15 - 127) << 23) + 0xfff`, but + // without arithmetic overflow. + f.u += 0xc8000fffU; + // rounding bias part 2 + f.u += mant_odd; + // take the bits! + val = static_cast(f.u >> 13); + } + } + + val |= static_cast(sign >> 16); + return val; +} + +template +inline float Float16Impl::ToFloatImpl() const noexcept { + constexpr detail::float32_bits magic = {113 << 23}; + constexpr unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift + detail::float32_bits o{}; + + o.u = (val & 0x7fff) << 13; // exponent/mantissa bits + unsigned int exp = shifted_exp & o.u; // just the exponent + o.u += (127 - 15) << 23; // exponent adjust + + // handle exponent special cases + if (exp == shifted_exp) { // Inf/NaN? + o.u += (128 - 16) << 23; // extra exp adjust + } else if (exp == 0) { // Zero/Denormal? + o.u += 1 << 23; // extra exp adjust + o.f -= magic.f; // re-normalize + } + + // Attempt to workaround the Internal Compiler Error on ARM64 + // for bitwise | operator, including std::bitset +#if (defined _MSC_VER) && (defined _M_ARM || defined _M_ARM64 || defined _M_ARM64EC) + if (IsNegative()) { + return -o.f; + } +#else + // original code: + o.u |= (val & 0x8000U) << 16U; // sign bit +#endif + return o.f; +} + +/// Shared implementation between public and internal classes. CRTP pattern. +template +struct BFloat16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7F80U; + static constexpr uint16_t kPositiveInfinityBits = 0x7F80U; + static constexpr uint16_t kNegativeInfinityBits = 0xFF80U; + static constexpr uint16_t kPositiveQNaNBits = 0x7FC1U; + static constexpr uint16_t kNegativeQNaNBits = 0xFFC1U; + static constexpr uint16_t kSignaling_NaNBits = 0x7F80U; + static constexpr uint16_t kEpsilonBits = 0x0080U; + static constexpr uint16_t kMinValueBits = 0xFF7FU; + static constexpr uint16_t kMaxValueBits = 0x7F7FU; + static constexpr uint16_t kRoundToNearest = 0x7FFFU; + static constexpr uint16_t kOneBits = 0x3F80U; + static constexpr uint16_t kMinusOneBits = 0xBF80U; + + uint16_t val{0}; + + BFloat16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const BFloat16Impl& lhs, const BFloat16Impl& rhs) noexcept { + // IEEE defines that positive and negative zero are equal, this gives us a quick equality check + // for two values by or'ing the private bits together and stripping the sign. They are both zero, + // and therefore equivalent, if the resulting value is still zero. + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } +}; + +template +inline uint16_t BFloat16Impl::ToUint16Impl(float v) noexcept { + uint16_t result; + if (std::isnan(v)) { + result = kPositiveQNaNBits; + } else { + auto get_msb_half = [](float fl) { + uint16_t result; +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memcpy(&result, reinterpret_cast(&fl) + sizeof(uint16_t), sizeof(uint16_t)); + } else { + std::memcpy(&result, &fl, sizeof(uint16_t)); + } + return result; + }; + + uint16_t upper_bits = get_msb_half(v); + union { + uint32_t U32; + float F32; + }; + F32 = v; + U32 += (upper_bits & 1) + kRoundToNearest; + result = get_msb_half(F32); + } + return result; +} + +template +inline float BFloat16Impl::ToFloatImpl() const noexcept { + if (IsNaN()) { + return std::numeric_limits::quiet_NaN(); + } + float result; + char* const first = reinterpret_cast(&result); + char* const second = first + sizeof(uint16_t); +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memset(first, 0, sizeof(uint16_t)); + std::memcpy(second, &val, sizeof(uint16_t)); + } else { + std::memcpy(first, &val, sizeof(uint16_t)); + std::memset(second, 0, sizeof(uint16_t)); + } + return result; +} + +} // namespace onnxruntime_float16 diff --git a/runexamples/cpp/onnx/include/onnxruntime_run_options_config_keys.h b/runexamples/cpp/onnx/include/onnxruntime_run_options_config_keys.h new file mode 100644 index 0000000..1f5fcd5 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_run_options_config_keys.h @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines RunOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a RunOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 128 + * + * The string format of a RunOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 1024 + */ + +// Key for enabling shrinkages of user listed device memory arenas. +// Expects a list of semi-colon separated key value pairs separated by colon in the following format: +// "device_0:device_id_0;device_1:device_id_1" +// No white-spaces allowed in the provided list string. +// Currently, the only supported devices are : "cpu", "gpu" (case sensitive). +// If "cpu" is included in the list, DisableCpuMemArena() API must not be called (i.e.) arena for cpu should be enabled. +// Example usage: "cpu:0;gpu:0" (or) "gpu:0" +// By default, the value for this key is empty (i.e.) no memory arenas are shrunk +static const char* const kOrtRunOptionsConfigEnableMemoryArenaShrinkage = "memory.enable_memory_arena_shrinkage"; + +// Set to '1' to not synchronize execution providers with CPU at the end of session run. +// Per default it will be set to '0' +// Taking CUDA EP as an example, it omit triggering cudaStreamSynchronize on the compute stream. +static const char* const kOrtRunOptionsConfigDisableSynchronizeExecutionProviders = "disable_synchronize_execution_providers"; diff --git a/runexamples/cpp/onnx/include/onnxruntime_session_options_config_keys.h b/runexamples/cpp/onnx/include/onnxruntime_session_options_config_keys.h new file mode 100644 index 0000000..37545f4 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_session_options_config_keys.h @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines SessionOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a SessionOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 128 + * + * The string format of a SessionOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 1024 + */ + +// Key for disable PrePacking, +// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value) +static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking"; + +// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session +// will be used. Use this to override the usage of env allocators on a per session level. +static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators"; + +// Set to 'ORT' (case sensitive) to load an ORT format model. +// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT +static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format"; + +// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set. +// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'. +static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format"; + +// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0". +// When multiple sessions are created, a main thread doesn't override changes from succeeding session options, +// but threads in session thread pools follow option changes. +// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and +// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool. +// Note that an alternative way not using this option at runtime is to train and export a model without denormals +// and that's recommended because turning this option on may hurt model accuracy. +static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero"; + +// It controls to run quantization model in QDQ (QuantizelinearDeQuantizelinear) format or not. +// "0": enable. ORT does fusion logic for QDQ format. +// "1": disable. ORT doesn't do fusion logic for QDQ format. +// Its default value is "0" unless the DirectML execution provider is registered, in which case it defaults to "1". +static const char* const kOrtSessionOptionsDisableQuantQDQ = "session.disable_quant_qdq"; + +// It controls whether to enable Double QDQ remover and Identical Children Consolidation +// "0": not to disable. ORT does remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// "1": disable. ORT doesn't remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// Its default value is "0" +static const char* const kOrtSessionOptionsDisableDoubleQDQRemover = "session.disable_double_qdq_remover"; + +// If set to "1", enables the removal of QuantizeLinear/DequantizeLinear node pairs once all QDQ handling has been +// completed. e.g. If after all QDQ handling has completed and we have -> FloatOp -> Q -> DQ -> FloatOp -> the +// Q -> DQ could potentially be removed. This will provide a performance benefit by avoiding going from float to +// 8-bit and back to float, but could impact accuracy. The impact on accuracy will be model specific and depend on +// other factors like whether the model was created using Quantization Aware Training or Post Training Quantization. +// As such, it's best to test to determine if enabling this works well for your scenario. +// The default value is "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsEnableQuantQDQCleanup = "session.enable_quant_qdq_cleanup"; + +// Enable or disable gelu approximation in graph optimization. "0": disable; "1": enable. The default is "0". +// GeluApproximation has side effects which may change the inference results. It is disabled by default due to this. +static const char* const kOrtSessionOptionsEnableGeluApproximation = "optimization.enable_gelu_approximation"; + +#ifdef ENABLE_TRAINING +// Specifies a list of op types for memory footprint reduction. +// The value should be a ","-delimited list of pair of +// . +// For example, "Gelu+Cast+:1:0,Dropout+:1:1". +// A valid "subgraph string" should be one subgraph representation output by ORT graph transformations. +// "optimization strategy" currently has valid values: 0 - disabled, 1 - recompute. +// "number of subgraph to apply" is used to control how many subgraphs to apply optimization, to avoid "oversaving" +// the memory. +static const char* const kOrtSessionOptionsMemoryOptimizerEnabler = "optimization.enable_memory_optimizer"; + +// Specifies the level for detecting subgraphs for memory footprint reduction. +// The value should be an integer. The default value is 0. +static const char* const kOrtSessionOptionsMemoryOptimizerProbeLevel = "optimization.enable_memory_probe_recompute_level"; +#endif + +// Enable or disable using device allocator for allocating initialized tensor memory. "1": enable; "0": disable. The default is "0". +// Using device allocators means the memory allocation is made using malloc/new. +static const char* const kOrtSessionOptionsUseDeviceAllocatorForInitializers = "session.use_device_allocator_for_initializers"; + +// Configure whether to allow the inter_op/intra_op threads spinning a number of times before blocking +// "0": thread will block if found no job to run +// "1": default, thread will spin a number of times before blocking +static const char* const kOrtSessionOptionsConfigAllowInterOpSpinning = "session.inter_op.allow_spinning"; +static const char* const kOrtSessionOptionsConfigAllowIntraOpSpinning = "session.intra_op.allow_spinning"; + +// Key for using model bytes directly for ORT format +// If a session is created using an input byte array contains the ORT format model data, +// By default we will copy the model bytes at the time of session creation to ensure the model bytes +// buffer is valid. +// Setting this option to "1" will disable copy the model bytes, and use the model bytes directly. The caller +// has to guarantee that the model bytes are valid until the ORT session using the model bytes is destroyed. +static const char* const kOrtSessionOptionsConfigUseORTModelBytesDirectly = "session.use_ort_model_bytes_directly"; + +/// +/// Key for using the ORT format model flatbuffer bytes directly for initializers. +/// This avoids copying the bytes and reduces peak memory usage during model loading and initialization. +/// Requires `session.use_ort_model_bytes_directly` to be true. +/// If set, the flatbuffer bytes provided when creating the InferenceSession MUST remain valid for the entire +/// duration of the InferenceSession. +/// +static const char* const kOrtSessionOptionsConfigUseORTModelBytesForInitializers = + "session.use_ort_model_bytes_for_initializers"; + +// This should only be specified when exporting an ORT format model for use on a different platform. +// If the ORT format model will be used on ARM platforms set to "1". For other platforms set to "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsQDQIsInt8Allowed = "session.qdqisint8allowed"; + +// x64 SSE4.1/AVX2/AVX512(with no VNNI) has overflow problem with quantizied matrix multiplication with U8S8. +// To avoid this we need to use slower U8U8 matrix multiplication instead. This option, if +// turned on, use slower U8U8 matrix multiplications. Only effective with AVX2 or AVX512 +// platforms. +static const char* const kOrtSessionOptionsAvx2PrecisionMode = "session.x64quantprecision"; + +// Specifies how minimal build graph optimizations are handled in a full build. +// These optimizations are at the extended level or higher. +// Possible values and their effects are: +// "save": Save runtime optimizations when saving an ORT format model. +// "apply": Only apply optimizations available in a minimal build. +// ""/: Apply optimizations available in a full build. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigMinimalBuildOptimizations = + "optimization.minimal_build_optimizations"; + +// Note: The options specific to an EP should be specified prior to appending that EP to the session options object in +// order for them to take effect. + +// Specifies a list of stop op types. Nodes of a type in the stop op types and nodes downstream from them will not be +// run by the NNAPI EP. +// The value should be a ","-delimited list of op types. For example, "Add,Sub". +// If not specified, the default set of stop ops is used. To specify an empty stop ops types list and disable stop op +// exclusion, set the value to "". +static const char* const kOrtSessionOptionsConfigNnapiEpPartitioningStopOps = "ep.nnapi.partitioning_stop_ops"; + +// Enabling dynamic block-sizing for multithreading. +// With a positive value, thread pool will split a task of N iterations to blocks of size starting from: +// N / (num_of_threads * dynamic_block_base) +// As execution progresses, the size will decrease according to the diminishing residual of N, +// meaning the task will be distributed in smaller granularity for better parallelism. +// For some models, it helps to reduce the variance of E2E inference latency and boost performance. +// The feature will not function by default, specify any positive integer, e.g. "4", to enable it. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigDynamicBlockBase = "session.dynamic_block_base"; + +// This option allows to decrease CPU usage between infrequent +// requests and forces any TP threads spinning stop immediately when the last of +// concurrent Run() call returns. +// Spinning is restarted on the next Run() call. +// Applies only to internal thread-pools +static const char* const kOrtSessionOptionsConfigForceSpinningStop = "session.force_spinning_stop"; + +// "1": all inconsistencies encountered during shape and type inference +// will result in failures. +// "0": in some cases warnings will be logged but processing will continue. The default. +// May be useful to expose bugs in models. +static const char* const kOrtSessionOptionsConfigStrictShapeTypeInference = "session.strict_shape_type_inference"; + +// "1": every model using a more recent opset than the latest released one will fail +// "0": the model may or may not work if onnxruntime cannot find an implementation, this option +// is used for development purpose. +static const char* const kOrtSessionOptionsConfigStrictAllowReleasedOpsetsOnly = "session.allow_released_opsets_only"; + +// The file saves configuration for partitioning node among logic streams +static const char* const kNodePartitionConfigFile = "session.node_partition_config_file"; + +// This Option allows setting affinities for intra op threads. +// Affinity string follows format: +// logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id +// Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. +// e.g.1,2,3;4,5 +// specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. +// To ease the configuration, an "interval" is also allowed: +// e.g. 1-8;8-16;17-24 +// orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. +// Note: +// 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, since ort does not set affinity on the main thread which +// is started and managed by the calling app; +// 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, +// an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. +// Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. +static const char* const kOrtSessionOptionsConfigIntraOpThreadAffinities = "session.intra_op_thread_affinities"; + +// This option will dump out the model to assist debugging any issues with layout transformation, +// and is primarily intended for developer usage. It is only relevant if an execution provider that requests +// NHWC layout is enabled such as NNAPI, XNNPACK or QNN. +// +// Default is off. Set to "1" to enable. +// +// If modified by layout transformation the model will be dumped after these steps: +// 1) insertion of the layout transformation Transpose nodes +// 2) after those are optimized using the transpose optimizer, +// 3) after the L1 transformers are applied to the updated graph. +// The model will be saved to filename post_layout_transform_step_.onnx. +static const char* const kDebugLayoutTransformation = "session.debug_layout_transformation"; + +// Graph nodes that are not supported by the execution providers (EPs) explicitly added to the session are +// assigned (i.e., "fallback") to the CPU EP by default. +// +// This option allows the user to disable the fallback of unsupported graph nodes to the CPU EP. +// If this option is set to "1", session creation will fail if the execution providers other than the CPU EP cannot +// fully support all of the nodes in the graph. +// +// It is invalid to set this option and explicitly add the CPU EP to the session. In this case, session creation +// will also fail with an error. +// +// Option values: +// - "0": CPU EP fallback is not disabled. [DEFAULT] +// - "1": CPU EP fallback is disabled. +static const char* const kOrtSessionOptionsDisableCPUEPFallback = "session.disable_cpu_ep_fallback"; + +// Use this config when serializing a large model after optimization to specify an external initializers file +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersFileName = + "session.optimized_model_external_initializers_file_name"; + +// Use this config to control the minimum size of the initializer when externalizing it during serialization +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersMinSizeInBytes = + "session.optimized_model_external_initializers_min_size_in_bytes"; diff --git a/runexamples/cpp/onnx/include/onnxruntime_training_c_api.h b/runexamples/cpp/onnx/include/onnxruntime_training_c_api.h new file mode 100644 index 0000000..0e8544a --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_training_c_api.h @@ -0,0 +1,728 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// This file contains the training c apis. + +#pragma once +#include +#include "onnxruntime_c_api.h" + +/** \page training_c_cpp_api Training C & C++ APIs + * + * Training C and C++ APIs are an extension of the \ref c_cpp_api "onnxruntime core C and C++ APIs" and should be used in conjunction with them. + * + * In order to train a model with onnxruntime, the following training artifacts must be generated: + * - The training onnx model + * - The checkpoint file + * - The optimizer onnx model + * - The eval onnx model model (optional) + * + * These training artifacts can be generated as part of an offline step using the python [utilities](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md) made available in the `onnxruntime-training` python package. + * + * After these artifacts have been generated, the C and C++ utilities listed in this documentation can be leveraged to perform training. + * + * If any problem is encountered, please create an [issue](https://github.com/microsoft/onnxruntime/issues/new) with your scenario and requirements, and we will be sure to respond and follow up on the request. + * + *

Training C API

+ * + * ::OrtTrainingApi - Training C API functions. + * + * This C structure contains functions that enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```c + * #include + * + * OrtApi* g_ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION); + * OrtTrainingApi* g_ort_training_api = g_ort_api->GetTrainingApi(ORT_API_VERSION); + * + * OrtEnv* env = NULL; + * g_ort_api->CreateEnv(logging_level, logid, &env); + * OrtSessionOptions* session_options = NULL; + * g_ort_api->CreateSessionOptions(&session_options); + * + * OrtCheckpointState* state = NULL; + * g_ort_training_api->LoadCheckpoint(path_to_checkpoint, &state); + * + * OrtTrainingSession* training_session = NULL; + * g_ort_training_api->CreateTrainingSession(env, session_options, training_model_path, + * state, eval_model_path, optimizer_model_path, + * &training_session); + * // Training loop + * { + * g_ort_training_api->TrainStep(...); + * g_ort_training_api->OptimizerStep(...); + * g_ort_training_api->LazyResetGrad(...); + * } + * + * g_ort_training_api->ExportModelForInferencing(training_session, inference_model_path, ...); + * g_ort_training_api->SaveCheckpoint(state, path_to_checkpoint, false); + * + * g_ort_training_api->ReleaseTrainingSession(training_session); + * g_ort_training_api->ReleaseCheckpointState(state); + * ``` + * + * > **Note** + * > The ::OrtCheckpointState contains the entire training state that the ::OrtTrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::OrtCheckpointState instance must outlive the lifetime of the ::OrtTrainingSession instance. + * + *

Training C++ API

+ * + * @ref TrainingCpp - Training C++ API classes and functions. + * + * These C++ classes and functions enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```cc + * #include + * + * Ort::Env env; + * Ort::SessionOptions session_options; + * + * auto state = Ort::CheckpointState::LoadCheckpoint(path_to_checkpoint); + * auto training_session = Ort::TrainingSession(env, session_options, state, training_model_path, + * eval_model_path, optimizer_model_path); + * + * // Training Loop + * { + * training_session.TrainStep(...); + * training_session.OptimizerStep(...); + * training_session.LazyResetGrad(...); + * } + * + * training_session->ExportModelForInferencing(inference_model_path, ...); + * Ort::CheckpointState::SaveCheckpoint(state, path_to_checkpoint, false); + * ``` + * > **Note** + * > The ::Ort::CheckpointState contains the entire training state that the ::Ort::TrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::Ort::CheckpointState instance must outlive the lifetime of the ::Ort::TrainingSession instance. + */ + +/** @defgroup TrainingC Ort Training C API + * @{ + */ +ORT_RUNTIME_CLASS(TrainingSession); // Type that enables performing training for the given user models. +ORT_RUNTIME_CLASS(CheckpointState); // Type that holds the training states for the training session. + +/** \brief Type of property to be added to or returned from the ::OrtCheckpointState. + */ +typedef enum OrtPropertyType { + OrtIntProperty = 0, + OrtFloatProperty = 1, + OrtStringProperty = 2, +} OrtPropertyType; + +/** \brief The Training C API that holds onnxruntime training function pointers + * + * All the Training C API functions are defined inside this structure as pointers to functions. + * Call OrtApi::GetTrainingApi to get a pointer to this struct. + * + * \nosubgrouping + */ +struct OrtTrainingApi { + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * + * \param[in] checkpoint_path Path to the checkpoint file + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpoint, _In_ const ORTCHAR_T* checkpoint_path, + _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking OrtTrainingApi::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] checkpoint_path Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SaveCheckpoint, _In_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* checkpoint_path, + const bool include_optimizer_state); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This function creates a training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * \param[out] out Created training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CreateTrainingSession, _In_ const OrtEnv* env, _In_ const OrtSessionOptions* options, + _Inout_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* train_model_path, + _In_ const ORTCHAR_T* eval_model_path, _In_ const ORTCHAR_T* optimizer_model_path, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /** \brief Create a training session that can be used to begin or resume training. + * This api provides a way to load all the training artifacts from buffers instead of files. + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing the model data to be used to perform training + * \param[in] train_data_length Length of the buffer containing train_model_data + * \param[in] eval_model_data Buffer containing the model data to be used to perform evaluation + * \param[in] eval_data_length Length of the buffer containing eval_model_data + * \param[in] optim_model_data Buffer containing the model data to be used to perform weight update + * \param[in] optim_data_length Length of the buffer containing optim_model_data + * \param[out] out Created training session. + * + */ + ORT_API2_STATUS(CreateTrainingSessionFromBuffer, _In_ const OrtEnv* env, + _In_ const OrtSessionOptions* options, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const void* train_model_data, size_t train_data_length, + _In_ const void* eval_model_data, size_t eval_data_length, + _In_ const void* optim_model_data, size_t optim_data_length, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /// @} + + /// \name Model IO Information + /// @{ + + /** \brief Retrieves the number of user outputs in the training model. + * + * This function returns the number of outputs of the training model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::TrainStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user outputs in the eval model. + * + * This function returns the number of outputs of the eval model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::EvalStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the names of user outputs in the training model. + * + * This function returns the names of outputs of the training model that can be associated with the OrtValue(s) + * returned by the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the training model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the names of user outputs in the eval model. + * + * This function returns the names of outputs of the eval model that can be associated with the OrtValue(s) returned + * by the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the eval model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next OrtTrainingApi::TrainStep. + * + * \param[in] session The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LazyResetGrad, _Inout_ OrtTrainingSession* session); + + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The OrtTrainingApi::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the OrtTrainingApi::OptimizerStep function. + * The gradients can be lazily reset by invoking the OrtTrainingApi::LazyResetGrad function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this training step. + * \param[in] inputs_len Number of user inputs to the training model. + * \param[in] inputs The user inputs to the training model. + * \param[in] outputs_len Number of user outputs expected from this training step. + * \param[out] outputs User outputs computed by train step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainStep, _Inout_ OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this eval step. + * \param[in] inputs_len Number of user inputs to the eval model. + * \param[in] inputs The user inputs to the eval model. + * \param[in] outputs_len Number of user outputs expected from this eval step. + * \param[out] outputs User outputs computed by eval step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(EvalStep, _In_ const OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function OrtTrainingApi::RegisterLinearLRScheduler. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] learning_rate Desired learning rate to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetLearningRate, _Inout_ OrtTrainingSession* sess, _In_ float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] learning_rate Learning rate currently in use by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetLearningRate, _Inout_ OrtTrainingSession* sess, _Out_ float* learning_rate); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * OrtTrainingApi::TrainStep function call. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this optimizer step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(OptimizerStep, _Inout_ OrtTrainingSession* sess, + _In_opt_ const OrtRunOptions* run_options); + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(RegisterLinearLRScheduler, _Inout_ OrtTrainingSession* sess, _In_ const int64_t warmup_step_count, + _In_ const int64_t total_step_count, _In_ const float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + * \param[in] sess The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SchedulerStep, _Inout_ OrtTrainingSession* sess); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + /** \brief Retrieves the size of all the parameters. + * + * Calculates the total number of primitive (datatype of the parameters) elements of all the parameters in the + * training state. + * When trainable_only argument is true, the size is calculated for trainable params only. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Size of all parameter elements. + * \param[in] trainable_only Whether to skip non-trainable parameters + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParametersSize, _Inout_ OrtTrainingSession* sess, _Out_ size_t* out, bool trainable_only); + + /** \brief Copy all parameters to a contiguous buffer held by the argument parameters_buffer + * + * The parameters_buffer has to be of the size given by GetParametersSize api call, + * with matching setting for the argument trainable_only. All the target parameters must be of the same + * datatype. The OrtValue must be pre-allocated onto + * the desired device. This is a complementary function to OrtTrainingApi::CopyBufferToParameters. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy onto. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyParametersToBuffer, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /** \brief Copy parameter values from the given contiguous buffer held by parameters_buffer to the training state + * + * The parameters_buffer argument has to be of the size given by OrtTrainingApi::GetParametersSize api call, + * with matching setting for trainable_only argument. All the target parameters must be of the same + * datatype. This is a complementary function to OrtTrainingApi::CopyBufferToParameters + * and can be used to load updated buffer values onto the training state. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy from. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyBufferToParameters, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /// @} + + /// \name Release Training Resources + /// @{ + + /** \brief Frees up the memory used up by the training session. + * + * This function frees up any memory that was allocated in the training session. The training + * session can no longer be used after this call. + * + */ + ORT_CLASS_RELEASE(TrainingSession); + + /** \brief Frees up the memory used up by the checkpoint state. + * + * This function frees up any memory that was allocated in the checkpoint state. The checkpoint + * state can no longer be used after this call. + * \note Note that the checkpoint state must be released only after the training session has been released. + * + */ + ORT_CLASS_RELEASE(CheckpointState); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with InferenceSession. + * \note Note that the function re-loads the eval model from the path provided to OrtTrainingApi::CreateTrainingSession + * and expects that this path still be valid. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_outputs_len Size of the graph output names array. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(ExportModelForInferencing, _Inout_ OrtTrainingSession* sess, + _In_ const ORTCHAR_T* inference_model_path, size_t graph_outputs_len, + _In_reads_(graph_outputs_len) const char* const* graph_output_names); + + /// @} + + /// \name Training Utilities + /// @{ + /** \brief Sets the seed used for random number generation in Onnxruntime. + * + * Use this function to generate reproducible results. It should be noted that completely reproducible + * results are not guaranteed. + * + * \param[in] seed The seed to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetSeed, _In_ const int64_t seed); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the number of user inputs in the training model. + * + * This function returns the number of inputs of the training model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user inputs in the eval model. + * + * This function returns the number of inputs of the eval model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the name of the user input at given index in the training model. + * + * This function returns the names of inputs of the training model that can be associated with the + * OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the training model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the training model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the name of the user input at given index in the eval model. + * + * This function returns the names of inputs of the eval model that can be associated with the OrtValue(s) provided + * to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the eval model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the eval model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] checkpoint_state The checkpoint state which should hold the property. + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_type Type of the property associated with the given name. + * \param[in] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(AddProperty, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _In_ enum OrtPropertyType property_type, + _In_ void* property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state that is currently holding the property. + * \param[in] property_name Name of the property being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the property_value. + * \param[out] property_type Type of the property associated with the given name. + * \param[out] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetProperty, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _Inout_ OrtAllocator* allocator, + _Out_ enum OrtPropertyType* property_type, _Outptr_ void** property_value); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a buffer into checkpoint_state. + * + * This function will parse a checkpoint bytes buffer, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * + * \param[in] checkpoint_buffer Path to the checkpoint bytes buffer. + * \param[in] num_bytes Number of bytes in the checkpoint buffer. + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpointFromBuffer, _In_ const void* checkpoint_buffer, + _In_ const size_t num_bytes, _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Retrieves the type and shape information of the parameter associated with the given parameter name. + * + * This function retrieves the type and shape of the parameter associated with the given parameter name. + * The parameter must exist in the checkpoint state to be able to retrieve its type and shape information successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[out] parameter_type_and_shape The type and shape of the parameter being retrieved. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameterTypeAndShape, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Outptr_ OrtTensorTypeAndShapeInfo** parameter_type_and_shape); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(UpdateParameter, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _In_ OrtValue* parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over and returned as an OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the parameter. + * \param[out] parameter The parameter data that is retrieved from the checkpoint state. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameter, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** parameter); + + /// @} +}; + +typedef struct OrtTrainingApi OrtTrainingApi; + +/// @} diff --git a/runexamples/cpp/onnx/include/onnxruntime_training_cxx_api.h b/runexamples/cpp/onnx/include/onnxruntime_training_cxx_api.h new file mode 100644 index 0000000..218bef5 --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_training_cxx_api.h @@ -0,0 +1,413 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include +#include + +namespace Ort::detail { + +#define ORT_DECLARE_TRAINING_RELEASE(NAME) \ + void OrtRelease(Ort##NAME* ptr); + +// These release methods must be forward declared before including onnxruntime_cxx_api.h +// otherwise class Base won't be aware of them +ORT_DECLARE_TRAINING_RELEASE(CheckpointState); +ORT_DECLARE_TRAINING_RELEASE(TrainingSession); + +} // namespace Ort::detail + +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +/// +/// This function returns the C training api struct with the pointers to the ort training C functions. +/// If using C++, please use the class instances instead of invoking the C functions directly. +/// +/// OrtTrainingApi struct with ort training C function pointers. +inline const OrtTrainingApi& GetTrainingApi() { return *GetApi().GetTrainingApi(ORT_API_VERSION); } + +namespace detail { + +#define ORT_DEFINE_TRAINING_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetTrainingApi().Release##NAME(ptr); } + +ORT_DEFINE_TRAINING_RELEASE(CheckpointState); +ORT_DEFINE_TRAINING_RELEASE(TrainingSession); + +#undef ORT_DECLARE_TRAINING_RELEASE +#undef ORT_DEFINE_TRAINING_RELEASE + +} // namespace detail + +using Property = std::variant; + +/** + * \defgroup TrainingCpp Ort Training C++ API + * @{ + */ + +/** \brief Holds the state of the training session. + * + * This class holds the entire training session state that includes model parameters, their gradients, + * optimizer parameters, and user properties. The Ort::TrainingSession leverages the Ort::CheckpointState + * by accessing and updating the contained training state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * The Ort::TrainingSession does not hold a copy of the Ort::CheckpointState and as a result, it is required + * that the checkpoint state outlive the lifetime of the training session. + * + */ +class CheckpointState : public detail::Base { + private: + CheckpointState(OrtCheckpointState* checkpoint_state) { p_ = checkpoint_state; } + + public: + // Construct the checkpoint state by loading the checkpoint by calling LoadCheckpoint + CheckpointState() = delete; + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] path_to_checkpoint Path to the checkpoint file + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpoint(const std::basic_string& path_to_checkpoint); + + /** \brief Load a checkpoint state from a buffer. + * + * This function will parse a checkpoint buffer, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] buffer Buffer containing the checkpoint data. + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpointFromBuffer(const std::vector& buffer); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking Ort::CheckpointState::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] path_to_checkpoint Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + */ + static void SaveCheckpoint(const CheckpointState& checkpoint_state, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state = false); + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_value Property value associated with the given name. + * + */ + void AddProperty(const std::string& property_name, const Property& property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] property_name Name of the property being retrieved. + * \return Property value associated with the given property name. + * + */ + Property GetProperty(const std::string& property_name); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + */ + void UpdateParameter(const std::string& parameter_name, const Value& parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over to the provided OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] parameter_name Name of the parameter being retrieved. + * \return The parameter data that is retrieved from the checkpoint state. + * + */ + Value GetParameter(const std::string& parameter_name); + + /// @} +}; + +/** \brief Trainer class that provides training, evaluation and optimizer methods for training an ONNX models. + * + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + */ +class TrainingSession : public detail::Base { + private: + size_t training_model_output_count_, eval_model_output_count_; + + public: + /// \name Constructing the Training Session + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This constructor instantiates the training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path = std::nullopt, + const std::optional>& optimizer_model_path = std::nullopt); + + /** \brief Create a training session that can be used to begin or resume training. + * This constructor allows the users to load the models from buffers instead of files. + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing training model data. + * \param[in] eval_model_data Buffer containing evaluation model data. + * \param[in] optim_model_data Buffer containing optimizer model (used for performing weight/parameter update). + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::vector& train_model_data, const std::vector& eval_model_data = {}, + const std::vector& optim_model_data = {}); + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The Ort::TrainingSession::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the Ort::TrainingSession::OptimizerStep function. + * The gradients can be lazily reset by invoking the Ort::TrainingSession::LazyResetGrad function. + * + * \param[in] input_values The user inputs to the training model. + * \return A std::vector of Ort::Value objects that represents the output of the forward pass of the training model. + * + * + */ + std::vector TrainStep(const std::vector& input_values); + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next Ort::TrainingSession::TrainStep. + * + */ + void LazyResetGrad(); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] input_values The user inputs to the eval model. + * \return A std::vector of Ort::Value objects that represents the output of the eval pass. + * + */ + std::vector EvalStep(const std::vector& input_values); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function Ort::TrainingSession::RegisterLinearLRScheduler. + * + * \param[in] learning_rate Desired learning rate to be set. + * + */ + void SetLearningRate(float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \return float representing the current learning rate. + * + */ + float GetLearningRate() const; + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + */ + void RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + */ + void SchedulerStep(); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * Ort::TrainingSession::TrainStep function call. + * + */ + void OptimizerStep(); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with Ort::Session. + * \note Note that the function re-loads the eval model from the path provided to Ort::TrainingSession + * and expects that this path still be valid. + * + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + */ + void ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the names of the user inputs for the training and eval models. + * + * This function returns the names of inputs of the training or eval model that can be associated + * with the Ort::Value(s) provided to the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model input names are requested or eval model input names. + * \return Graph input names for either the training model or the eval model. + * + */ + std::vector InputNames(const bool training); + + /** \brief Retrieves the names of the user outputs for the training and eval models. + * + * This function returns the names of outputs of the training or eval model that can be associated + * with the Ort::Value(s) returned by the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model output names are requested or eval model output names. + * \return Graph output names for either the training model or the eval model. + * + */ + std::vector OutputNames(const bool training); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Returns a contiguous buffer that holds a copy of all training state parameters + * + * \param[in] only_trainable Whether to only copy trainable parameters or to copy all parameters. + * \return Contiguous buffer to the model parameters. + * + */ + Value ToBuffer(const bool only_trainable); + + /** \brief Loads the training session model parameters from a contiguous buffer + * + * \param[in] buffer Contiguous buffer to load the parameters from. + */ + void FromBuffer(Value& buffer); + + /// @} +}; + +/// \name Training Utilities +/// @{ +/** \brief This function sets the seed for generating random numbers. + * + * Use this function to generate reproducible results. It should be noted that completely + * reproducible results are not guaranteed. + * + * \param[in] seed Manual seed to use for random number generation. + */ +void SetSeed(const int64_t seed); +/// @} + +/// @} + +} // namespace Ort + +#include "onnxruntime_training_cxx_inline.h" diff --git a/runexamples/cpp/onnx/include/onnxruntime_training_cxx_inline.h b/runexamples/cpp/onnx/include/onnxruntime_training_cxx_inline.h new file mode 100644 index 0000000..a5efa3c --- /dev/null +++ b/runexamples/cpp/onnx/include/onnxruntime_training_cxx_inline.h @@ -0,0 +1,294 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path, + const std::optional>& optimizer_model_path) { + ThrowOnError(GetTrainingApi().CreateTrainingSession( + env, session_options, checkpoint_state, + train_model_path.c_str(), + eval_model_path.has_value() ? eval_model_path.value().c_str() : nullptr, + optimizer_model_path.has_value() ? optimizer_model_path.value().c_str() : nullptr, + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::vector& train_model_data, + const std::vector& eval_model_data, + const std::vector& optim_model_data) { + ThrowOnError(GetTrainingApi().CreateTrainingSessionFromBuffer( + env, session_options, checkpoint_state, + train_model_data.data(), train_model_data.size(), + eval_model_data.data(), eval_model_data.size(), + optim_model_data.data(), optim_model_data.size(), + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline std::vector TrainingSession::TrainStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(training_model_output_count_); + for (size_t i = 0; i < training_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().TrainStep( + p_, run_options, input_values.size(), ort_input_values, + training_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::LazyResetGrad() { + ThrowOnError(GetTrainingApi().LazyResetGrad(p_)); +} + +inline std::vector TrainingSession::EvalStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(eval_model_output_count_); + for (size_t i = 0; i < eval_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().EvalStep( + p_, run_options, input_values.size(), ort_input_values, + training_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::SetLearningRate(float learning_rate) { + ThrowOnError(GetTrainingApi().SetLearningRate(p_, learning_rate)); +} + +inline float TrainingSession::GetLearningRate() const { + float learning_rate = 0; + ThrowOnError(GetTrainingApi().GetLearningRate(p_, &learning_rate)); + return learning_rate; +} + +inline void TrainingSession::RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr) { + ThrowOnError(GetTrainingApi().RegisterLinearLRScheduler(p_, warmup_step_count, total_step_count, + initial_lr)); +} + +inline void TrainingSession::SchedulerStep() { + ThrowOnError(GetTrainingApi().SchedulerStep(p_)); +} + +inline void TrainingSession::OptimizerStep() { + RunOptions run_options; + ThrowOnError(GetTrainingApi().OptimizerStep(p_, run_options)); +} + +inline std::vector TrainingSession::InputNames(const bool training) { + auto& input_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputCount + : GetTrainingApi().TrainingSessionGetEvalModelInputCount; + auto& input_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputName + : GetTrainingApi().TrainingSessionGetEvalModelInputName; + + size_t input_count = 0; + ThrowOnError(input_count_function(p_, &input_count)); + std::vector input_names(input_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < input_count; ++index) { + char* input_name; + ThrowOnError(input_name_function(p_, index, allocator, &input_name)); + input_names[index] = std::string(input_name); + allocator.Free(input_name); + } + + return input_names; +} + +inline std::vector TrainingSession::OutputNames(const bool training) { + auto& output_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputCount + : GetTrainingApi().TrainingSessionGetEvalModelOutputCount; + auto& output_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputName + : GetTrainingApi().TrainingSessionGetEvalModelOutputName; + + size_t output_count = 0; + ThrowOnError(output_count_function(p_, &output_count)); + std::vector output_names(output_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < output_count; ++index) { + char* output_name; + ThrowOnError(output_name_function(p_, index, allocator, &output_name)); + output_names[index] = std::string(output_name); + allocator.Free(output_name); + } + + return output_names; +} + +inline Value TrainingSession::ToBuffer(const bool only_trainable) { + size_t buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &buffer_size, only_trainable)); + + std::array buffer_shape{static_cast(buffer_size)}; + + AllocatorWithDefaultOptions allocator; + Value buffer = Value::CreateTensor(allocator, buffer_shape.data(), 1U, + ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); + + ThrowOnError(GetTrainingApi().CopyParametersToBuffer(p_, buffer, only_trainable)); + + return buffer; +} + +inline void TrainingSession::FromBuffer(Value& buffer) { + if (!buffer.IsTensor()) { + ThrowStatus(Status("Incorrect buffer received. Expected a tensor buffer.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto tensor_info = buffer.GetTensorTypeAndShapeInfo(); + auto buffer_shape = tensor_info.GetShape(); + + if (buffer_shape.size() != 1U) { + ThrowStatus(Status("Incorrect buffer received. Expected a contiguous tensor buffer.", + OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto buffer_size = buffer_shape.front(); + + size_t session_buffer_size_trainable_only = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size_trainable_only, true)); + + if (buffer_size == static_cast(session_buffer_size_trainable_only)) { + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, true)); + return; + } + + size_t session_buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size, false)); + + if (buffer_size != static_cast(session_buffer_size)) { + ThrowStatus(Status("Incorrect buffer size received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, false)); +} + +inline CheckpointState CheckpointState::LoadCheckpoint(const std::basic_string& path_to_checkpoint) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpoint(path_to_checkpoint.c_str(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline CheckpointState CheckpointState::LoadCheckpointFromBuffer(const std::vector& buffer) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpointFromBuffer(buffer.data(), buffer.size(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline void CheckpointState::SaveCheckpoint(const CheckpointState& checkpoint_states, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state) { + ThrowOnError(GetTrainingApi().SaveCheckpoint(checkpoint_states, path_to_checkpoint.c_str(), + include_optimizer_state)); +} + +inline void TrainingSession::ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names) { + std::vector output_names; + output_names.reserve(graph_output_names.size()); + for (const auto& output_name : graph_output_names) { + output_names.push_back(output_name.c_str()); + } + ThrowOnError(GetTrainingApi().ExportModelForInferencing( + p_, inference_model_path.c_str(), graph_output_names.size(), output_names.data())); +} + +inline void SetSeed(const int64_t seed) { + ThrowOnError(GetTrainingApi().SetSeed(seed)); +} + +inline void CheckpointState::AddProperty(const std::string& property_name, const Property& property_value) { + if (std::holds_alternative(property_value)) { + int64_t value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtIntProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + float value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtFloatProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + std::string value = std::get(property_value); + auto buffer = std::make_unique(value.length() + 1); + memcpy(buffer.get(), value.c_str(), value.length()); + // AddProperty takes a char* and calls PropertyBag::AddProperty which takes a std::string. The data will be + // copied at that point so buffer can free the local allocation once the call is made. + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtStringProperty, + buffer.get())); + } else { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } +} + +inline Property CheckpointState::GetProperty(const std::string& property_name) { + void* property_value = nullptr; + OrtPropertyType property_type; + + AllocatorWithDefaultOptions allocator; + ThrowOnError(GetTrainingApi().GetProperty(p_, property_name.c_str(), allocator, &property_type, &property_value)); + + Property property; + + switch (property_type) { + case OrtPropertyType::OrtIntProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtFloatProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtStringProperty: { + auto value_p = reinterpret_cast(property_value); + property = std::string(value_p); + allocator.Free(property_value); + break; + } + default: { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + break; + } + } + + return property; +} + +inline void CheckpointState::UpdateParameter(const std::string& parameter_name, const Value& parameter) { + ThrowOnError(GetTrainingApi().UpdateParameter(p_, parameter_name.c_str(), parameter)); +} + +inline Value CheckpointState::GetParameter(const std::string& parameter_name) { + AllocatorWithDefaultOptions allocator; + OrtValue* parameter; + ThrowOnError(GetTrainingApi().GetParameter(p_, parameter_name.c_str(), allocator, ¶meter)); + + return Value{parameter}; +} + +} // namespace Ort diff --git a/runexamples/cpp/onnx/include/provider_options.h b/runexamples/cpp/onnx/include/provider_options.h new file mode 100644 index 0000000..aab13e8 --- /dev/null +++ b/runexamples/cpp/onnx/include/provider_options.h @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include + +namespace onnxruntime { + +// data types for execution provider options + +using ProviderOptions = std::unordered_map; +using ProviderOptionsVector = std::vector; +using ProviderOptionsMap = std::unordered_map; + +} // namespace onnxruntime diff --git a/runexamples/cpp/onnx/lib/libonnxruntime.so b/runexamples/cpp/onnx/lib/libonnxruntime.so new file mode 120000 index 0000000..a65ba2d --- /dev/null +++ b/runexamples/cpp/onnx/lib/libonnxruntime.so @@ -0,0 +1 @@ +libonnxruntime.so.1.16.2 \ No newline at end of file diff --git a/runexamples/cpp/onnx/lib/libonnxruntime.so.1.16.2 b/runexamples/cpp/onnx/lib/libonnxruntime.so.1.16.2 new file mode 100755 index 0000000..7cbbd38 Binary files /dev/null and b/runexamples/cpp/onnx/lib/libonnxruntime.so.1.16.2 differ diff --git a/runexamples/cpp/sampler/sample.hpp b/runexamples/cpp/sampler/sample.hpp new file mode 100644 index 0000000..911f7c5 --- /dev/null +++ b/runexamples/cpp/sampler/sample.hpp @@ -0,0 +1,47 @@ +#include "NumCpp.hpp" +int typical(float* _logits, float _temp = 0.9, float _tau = 0.8) +{ + int len = pow(2,16); + // choose top token + nc::NdArray logits = nc::NdArray(1,len); + for (int i = 0; i < len; i++) { + logits[i] = _logits[i]; + } + + nc::NdArray probs = nc::special::softmax(logits); + logits = -nc::log(probs); + nc::NdArray ent = nc::nansum(logits * probs); + nc::NdArray shifted_logits = nc::abs(logits - ent); + nc::NdArray sorted_ids = nc::argsort(shifted_logits); + nc::NdArray sorted_logits = shifted_logits[sorted_ids]; + nc::NdArray sorted_probs = probs[sorted_ids]; + nc::NdArray cumulative_probs = nc::cumsum(sorted_probs); + nc::NdArray tau = nc::NdArray(1,1); + tau[0] = _tau; + auto mask = (cumulative_probs < tau); + // convert mask to int + nc::NdArray mask_int = nc::NdArray(1,mask.size()); + for (int i = 0; i < mask.size(); i++) { + mask_int[i] = mask[i]; + } + + // get cutoff + auto cutoff = nc::sum(mask_int); + // set probs to 0 + probs[shifted_logits > sorted_logits[cutoff]] = 0; + if (_temp != 1.0) { + probs = nc::power(probs, 1.0 / _temp); + } + + // get random token + auto out = nc::random::discrete(nc::shape(tau),probs); + return out[0]; +} + +std::vector typical(int batchsize, float* _logits, float _temp = 0.9, float _tau = 0.8){ + std::vector out; + for(int i = 0; i < batchsize; i++){ + out.push_back(typical(&_logits[i*int(pow(2,16))], _temp, _tau)); + } + return out; +} \ No newline at end of file diff --git a/runexamples/cpp/test.cpp b/runexamples/cpp/test.cpp new file mode 100644 index 0000000..1af068d --- /dev/null +++ b/runexamples/cpp/test.cpp @@ -0,0 +1,263 @@ +#include "./onnx/include/onnxruntime_cxx_api.h" +// string +#include +// nullable +#include +#include +#include +// std::pair +#include +#include +#include +#include "tokenizer/tokenizer.hpp" +#include "sampler/sample.hpp" + + +struct State { + std::vector& state; + std::vector& keys; + std::vector& outputkeys; +}; + +struct StateProbs { + float* probs; + State state; +}; + +struct StateToken { + std::vector token; + State state; +}; + + +class RWKV { + private: + Ort::Session* session = nullptr; + Ort::Env env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "ONNXRuntimeExample"); + Ort::SessionOptions sessionOptions; + Ort::AllocatorWithDefaultOptions allocator; + + size_t layers = 0; + size_t hidden_size = 0; + size_t num_heads = 0; + size_t vocab_size = pow(2, 16); + std::string outputName = "output0"; + + State* globalState = nullptr; + + + public: + RWKV(std::string model_path, int intraopthreads = 6, int interopthreads = 6, GraphOptimizationLevel graphoptimizationlevel = GraphOptimizationLevel::ORT_ENABLE_BASIC) { + + // Set up options for the session + + sessionOptions.SetIntraOpNumThreads(intraopthreads); + sessionOptions.SetInterOpNumThreads(interopthreads); + sessionOptions.SetGraphOptimizationLevel(graphoptimizationlevel); + sessionOptions.SetExecutionMode(ExecutionMode::ORT_PARALLEL); + + // Create a session with the model file + session = new Ort::Session(env, model_path.c_str(), sessionOptions); + + // Print some information about the model + size_t numInputNodes = session->GetInputCount(); + size_t numOutputNodes = session->GetOutputCount(); + + layers = (numInputNodes - 1) / 3; + hidden_size = session->GetInputTypeInfo(1).GetTensorTypeAndShapeInfo().GetShape()[1]; + int stateindex = 0; + while (session->GetInputTypeInfo(stateindex).GetTensorTypeAndShapeInfo().GetShape().size() < 3) { + stateindex++; + } + + for (int i = 0; i < layers*3+1; i++) { + auto type = session->GetInputTypeInfo(i).GetTensorTypeAndShapeInfo().GetElementType(); + + std::cout << "Output name: " << outputName << std::endl; + if (type == ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32) { + auto name = session->GetOutputNameAllocated(0, allocator); + outputName = std::string(name.get()); + std::cout << "Output name: " << outputName << std::endl; + break; + } + } + + num_heads = session->GetInputTypeInfo(stateindex).GetTensorTypeAndShapeInfo().GetShape()[1]; + + std::cout << "Number of inputs: " << numInputNodes << std::endl; + std::cout << "Number of outputs: " << numOutputNodes << std::endl; + std::cout << "layers: " << layers << std::endl; + std::cout << "hidden_size: " << hidden_size << std::endl; + std::cout << "num_heads: " << num_heads << std::endl; + + + globalState = newState(); + } + ~RWKV() { + } + + State* newState(int32_t batch_size = 1) { + + std::vector* inputTensors = new std::vector(); + std::vector* inputNames = new std::vector(); + std::vector* outputNames = new std::vector(); + + for(int i = 0; i < layers*2; i++) { + const auto meminfo = Ort::MemoryInfo::CreateCpu(OrtAllocatorType::OrtDeviceAllocator, OrtMemTypeDefault); + const int64_t size[2] = {batch_size, hidden_size}; + + auto key = std::string("state" + std::to_string(i)); + // OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, int64_t* shape, size_t shape_len + auto key2 = std::string("state" + std::to_string(i) + "out"); + + + inputNames->push_back(key); + outputNames->push_back(key2); + inputTensors->push_back(Ort::Value::CreateTensor(allocator,(const int64_t*)size, size_t(2))); + // ("float32",new Float32Array(this.embed),[1,this.embed]) + std::fill_n(inputTensors->back().GetTensorMutableData(), hidden_size, 0); + } + + for (int i = 0; i < layers; i++) { + const int64_t size[4] = {batch_size, num_heads, hidden_size / num_heads, hidden_size / num_heads}; + + auto key = std::string("statewkv" + std::to_string(i)); + // const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, const int64_t* shape, size_t shape_len + auto key2 = std::string("statewkv" + std::to_string(i) + "out"); + + + inputNames->push_back(key); + outputNames->push_back(key2); + inputTensors->push_back(Ort::Value::CreateTensor(allocator, (const int64_t*)size, size_t(4))); + // fill with zeros + std::fill_n(inputTensors->back().GetTensorMutableData(), hidden_size * hidden_size / num_heads, 0); + + } + + outputNames->push_back(outputName); + inputNames->push_back("input0"); + + const int64_t size[1] = {batch_size}; + inputTensors->push_back(Ort::Value::CreateTensor(allocator, (const int64_t*)size, size_t(1))); + + + + State* result = new State({ + .state = *inputTensors, + .keys = *inputNames, + .outputkeys = *outputNames + }); + + return result; + } + + void digest(std::vector input){ + auto runOptions = Ort::RunOptions{nullptr}; + + auto inputnames = globalState->keys; + auto outputnames = globalState->outputkeys; + + for (int i = 0; i < layers*3; i++){ + float* destT = globalState->state[i].GetTensorMutableData(); + for (int j = 0; j < input.size(); j++) { + const float* start = input[j]->state[i].GetTensorData(); + size_t size = input[j]->state[i].GetTensorTypeAndShapeInfo().GetElementCount(); + float* dest = &destT[j * size]; + std::memcpy(dest, start, size * sizeof(float)); + } + } + + // copy input0 + int32_t* destT = globalState->state[layers*3].GetTensorMutableData(); + for (int j = 0; j < input.size(); j++) { + destT[j] = input[j]->state[layers*3].GetTensorData()[0]; + } + + const char** inputNamesChar = new const char*[inputnames.size()]; + for (int i = 0; i < inputnames.size(); i++) { + inputNamesChar[i] = inputnames[i].c_str(); + } + + const char** outputNamesChar = new const char*[outputnames.size()]; + for (int i = 0; i < outputnames.size(); i++) { + outputNamesChar[i] = outputnames[i].c_str(); + } + + + std::vector outTensors = session->Run(runOptions, inputNamesChar, globalState->state.data(), layers*3 + 1, outputNamesChar, outputnames.size()); + + for (int i = 0; i < layers*3; i++) { + const float* startT = outTensors[i].GetTensorData(); + + for (int j = 0; j < input.size(); j++) { + size_t size = input[j]->state[i].GetTensorTypeAndShapeInfo().GetElementCount(); + const float* start = &startT[j * size]; + float* dest = input[j]->state[i].GetTensorMutableData(); + std::memcpy(dest, start, size * sizeof(float)); + } + } + // std::vector(outTensors.begin(), outTensors.begin() + layers*3); + // slice(0,-1) + + float* probs = outTensors[layers*3].GetTensorMutableData(); + auto samp = typical(input.size(),probs, 1.0, 1.0); + for(int i = 0; i < input.size(); i++) { + input[i]->state[layers*3].GetTensorMutableData()[0] = samp[i]; + } + } +}; + +int main( int argc, char* argv[] ) { + std::cout << "Loading ONNX model..." << std::endl; + + for (int i = 0; i < argc; i++) { + if (i > 0){ + if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + std::cout << "Usage: " << argv[0] << " [model_path]" << std::endl; + return 0; + } + } + } + // Initialize ONNX Runtime (optional, depending on the version of ONNX Runtime) + Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "ONNXRuntimeExample"); + + + try { + // Create a session with the model file + auto file = "RWKV_32_2560_32_19_QUInt8-npc-norr-ext.onnx"; + RWKV* rwkv = new RWKV(file); + + std::cout << "Creating state..." << std::endl; + State* state = rwkv->newState(); + + std::cout << "Creating token..." << std::endl; + std::cout << "What would you like me to write about?" << std::endl; + std::string story; + std::getline(std::cin, story); + auto context = worldTokenizer.encode("### Instruction:\nWrite a story about the following topics, themes, or events\n### Input:\n"+story+"\n### Response:\n"); + + state->state.back().GetTensorMutableData()[0] = context[0]; + + + std::cout << "Digesting token..." << std::endl; + std::vector input = {state}; + int i = 0; + while(1){ + rwkv->digest(input); + if(i < context.size()){ + state->state.back().GetTensorMutableData()[0] = context[i]; + i++; + } + std::cout << worldTokenizer.decode({state->state.back().GetTensorMutableData()[0]}) << std::flush; + } + + std::cout << "Done!" << std::endl; + + + } catch (const Ort::Exception& e) { + std::cerr << "Error: " << e.what() << std::endl; + return -1; + } + + return 0; +} \ No newline at end of file diff --git a/runexamples/cpp/tokenizer/bytematch.hpp b/runexamples/cpp/tokenizer/bytematch.hpp new file mode 100644 index 0000000..e4a0172 --- /dev/null +++ b/runexamples/cpp/tokenizer/bytematch.hpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include +// ostream_iterator +#include + +#define uchar unsigned char + +std::vector hexToBytes(const std::string &hexString) { + if (hexString.length() % 2 != 0) { + throw std::runtime_error("Invalid hex string length for conversion to bytes."); + } + + size_t len = hexString.length() / 2; + std::vector bytes; + bytes.reserve(len); + + for (size_t i = 0; i < len; ++i) { + std::string byteString = hexString.substr(2 * i, 2); + uchar byte = std::stoi(byteString, nullptr, 16); + bytes.push_back(byte); + } + + return bytes; +} + +std::vector findPythonByteObjects(const std::string &input) { + // Regular expression pattern to match Python byte literals b'...' + std::regex byteObjectPattern(R"(b'([^']*)')"); + + std::smatch match; + std::vector byteArray; + + std::string::const_iterator searchStart = input.cbegin(); + while (std::regex_search(searchStart, input.cend(), match, byteObjectPattern)) { + // Extract the contents of the byte literal (safe to assume ASCII - no UTF8 handling) + std::string byteString = match[1]; + + // Replace escape sequences with actual byte values + std::regex escapePattern(R"(\\x([a-fA-F0-9]{2}))"); + std::ostringstream replacedByteString; + std::regex_replace(std::ostream_iterator(replacedByteString), + byteString.begin(), byteString.end(), + escapePattern, "$1"); + + // Convert replaced byte string to byte array + byteArray = hexToBytes(replacedByteString.str()); + + // In the original function, only the first match is used - hence the break + break; + + searchStart = match.suffix().first; + } + + return byteArray; +} + +// int main() { +// std::string input = "Some text with Python byte object b'\\x61\\x62\\x63'"; + +// try { +// std::vector byteArray = findPythonByteObjects(input); +// std::cout << "Byte array: [ "; +// for (uchar byte : byteArray) { +// std::cout << std::hex << static_cast(byte) << " "; +// } +// std::cout << "]" << std::endl; +// } catch (const std::runtime_error &e) { +// std::cerr << "Error: " << e.what() << std::endl; +// } + +// return 0; +// } \ No newline at end of file diff --git a/runexamples/cpp/tokenizer/rwkv_vocab_v20230424.txt b/runexamples/cpp/tokenizer/rwkv_vocab_v20230424.txt new file mode 100644 index 0000000..b8c3f72 --- /dev/null +++ b/runexamples/cpp/tokenizer/rwkv_vocab_v20230424.txt @@ -0,0 +1,65529 @@ +1 '\x00' 1 +2 '\x01' 1 +3 '\x02' 1 +4 '\x03' 1 +5 '\x04' 1 +6 '\x05' 1 +7 '\x06' 1 +8 '\x07' 1 +9 '\x08' 1 +10 '\t' 1 +11 '\n' 1 +12 '\x0b' 1 +13 '\x0c' 1 +14 '\r' 1 +15 '\x0e' 1 +16 '\x0f' 1 +17 '\x10' 1 +18 '\x11' 1 +19 '\x12' 1 +20 '\x13' 1 +21 '\x14' 1 +22 '\x15' 1 +23 '\x16' 1 +24 '\x17' 1 +25 '\x18' 1 +26 '\x19' 1 +27 '\x1a' 1 +28 '\x1b' 1 +29 '\x1c' 1 +30 '\x1d' 1 +31 '\x1e' 1 +32 '\x1f' 1 +33 ' ' 1 +34 '!' 1 +35 '"' 1 +36 '#' 1 +37 '$' 1 +38 '%' 1 +39 '&' 1 +40 "'" 1 +41 '(' 1 +42 ')' 1 +43 '*' 1 +44 '+' 1 +45 ',' 1 +46 '-' 1 +47 '.' 1 +48 '/' 1 +49 '0' 1 +50 '1' 1 +51 '2' 1 +52 '3' 1 +53 '4' 1 +54 '5' 1 +55 '6' 1 +56 '7' 1 +57 '8' 1 +58 '9' 1 +59 ':' 1 +60 ';' 1 +61 '<' 1 +62 '=' 1 +63 '>' 1 +64 '?' 1 +65 '@' 1 +66 'A' 1 +67 'B' 1 +68 'C' 1 +69 'D' 1 +70 'E' 1 +71 'F' 1 +72 'G' 1 +73 'H' 1 +74 'I' 1 +75 'J' 1 +76 'K' 1 +77 'L' 1 +78 'M' 1 +79 'N' 1 +80 'O' 1 +81 'P' 1 +82 'Q' 1 +83 'R' 1 +84 'S' 1 +85 'T' 1 +86 'U' 1 +87 'V' 1 +88 'W' 1 +89 'X' 1 +90 'Y' 1 +91 'Z' 1 +92 '[' 1 +93 '\\' 1 +94 ']' 1 +95 '^' 1 +96 '_' 1 +97 '`' 1 +98 'a' 1 +99 'b' 1 +100 'c' 1 +101 'd' 1 +102 'e' 1 +103 'f' 1 +104 'g' 1 +105 'h' 1 +106 'i' 1 +107 'j' 1 +108 'k' 1 +109 'l' 1 +110 'm' 1 +111 'n' 1 +112 'o' 1 +113 'p' 1 +114 'q' 1 +115 'r' 1 +116 's' 1 +117 't' 1 +118 'u' 1 +119 'v' 1 +120 'w' 1 +121 'x' 1 +122 'y' 1 +123 'z' 1 +124 '{' 1 +125 '|' 1 +126 '}' 1 +127 '~' 1 +128 '\x7f' 1 +129 b'\x80' 1 +130 b'\x81' 1 +131 b'\x82' 1 +132 b'\x83' 1 +133 b'\x84' 1 +134 b'\x85' 1 +135 b'\x86' 1 +136 b'\x87' 1 +137 b'\x88' 1 +138 b'\x89' 1 +139 b'\x8a' 1 +140 b'\x8b' 1 +141 b'\x8c' 1 +142 b'\x8d' 1 +143 b'\x8e' 1 +144 b'\x8f' 1 +145 b'\x90' 1 +146 b'\x91' 1 +147 b'\x92' 1 +148 b'\x93' 1 +149 b'\x94' 1 +150 b'\x95' 1 +151 b'\x96' 1 +152 b'\x97' 1 +153 b'\x98' 1 +154 b'\x99' 1 +155 b'\x9a' 1 +156 b'\x9b' 1 +157 b'\x9c' 1 +158 b'\x9d' 1 +159 b'\x9e' 1 +160 b'\x9f' 1 +161 b'\xa0' 1 +162 b'\xa1' 1 +163 b'\xa2' 1 +164 b'\xa3' 1 +165 b'\xa4' 1 +166 b'\xa5' 1 +167 b'\xa6' 1 +168 b'\xa7' 1 +169 b'\xa8' 1 +170 b'\xa9' 1 +171 b'\xaa' 1 +172 b'\xab' 1 +173 b'\xac' 1 +174 b'\xad' 1 +175 b'\xae' 1 +176 b'\xaf' 1 +177 b'\xb0' 1 +178 b'\xb1' 1 +179 b'\xb2' 1 +180 b'\xb3' 1 +181 b'\xb4' 1 +182 b'\xb5' 1 +183 b'\xb6' 1 +184 b'\xb7' 1 +185 b'\xb8' 1 +186 b'\xb9' 1 +187 b'\xba' 1 +188 b'\xbb' 1 +189 b'\xbc' 1 +190 b'\xbd' 1 +191 b'\xbe' 1 +192 b'\xbf' 1 +193 b'\xc0' 1 +194 b'\xc1' 1 +195 b'\xc2' 1 +196 b'\xc3' 1 +197 b'\xc4' 1 +198 b'\xc5' 1 +199 b'\xc6' 1 +200 b'\xc7' 1 +201 b'\xc8' 1 +202 b'\xc9' 1 +203 b'\xca' 1 +204 b'\xcb' 1 +205 b'\xcc' 1 +206 b'\xcd' 1 +207 b'\xce' 1 +208 b'\xcf' 1 +209 b'\xd0' 1 +210 b'\xd1' 1 +211 b'\xd2' 1 +212 b'\xd3' 1 +213 b'\xd4' 1 +214 b'\xd5' 1 +215 b'\xd6' 1 +216 b'\xd7' 1 +217 b'\xd8' 1 +218 b'\xd9' 1 +219 b'\xda' 1 +220 b'\xdb' 1 +221 b'\xdc' 1 +222 b'\xdd' 1 +223 b'\xde' 1 +224 b'\xdf' 1 +225 b'\xe0' 1 +226 b'\xe1' 1 +227 b'\xe2' 1 +228 b'\xe3' 1 +229 b'\xe4' 1 +230 b'\xe5' 1 +231 b'\xe6' 1 +232 b'\xe7' 1 +233 b'\xe8' 1 +234 b'\xe9' 1 +235 b'\xea' 1 +236 b'\xeb' 1 +237 b'\xec' 1 +238 b'\xed' 1 +239 b'\xee' 1 +240 b'\xef' 1 +241 b'\xf0' 1 +242 b'\xf1' 1 +243 b'\xf2' 1 +244 b'\xf3' 1 +245 b'\xf4' 1 +246 b'\xf5' 1 +247 b'\xf6' 1 +248 b'\xf7' 1 +249 b'\xf8' 1 +250 b'\xf9' 1 +251 b'\xfa' 1 +252 b'\xfb' 1 +253 b'\xfc' 1 +254 b'\xfd' 1 +255 b'\xfe' 1 +256 b'\xff' 1 +257 '\t\t' 2 +258 '\t\n' 2 +259 '\t ' 2 +260 '\n\t' 2 +261 '\n\n' 2 +262 '\n ' 2 +263 '\r\n' 2 +264 ' \t' 2 +265 ' \n' 2 +266 ' \r' 2 +267 ' ' 2 +268 ' !' 2 +269 ' "' 2 +270 ' #' 2 +271 ' $' 2 +272 ' %' 2 +273 ' &' 2 +274 " '" 2 +275 ' (' 2 +276 ' )' 2 +277 ' *' 2 +278 ' +' 2 +279 ' ,' 2 +280 ' -' 2 +281 ' .' 2 +282 ' /' 2 +283 ' 0' 2 +284 ' 1' 2 +285 ' 2' 2 +286 ' 3' 2 +287 ' 4' 2 +288 ' 5' 2 +289 ' 6' 2 +290 ' 7' 2 +291 ' 8' 2 +292 ' 9' 2 +293 ' :' 2 +294 ' ;' 2 +295 ' <' 2 +296 ' =' 2 +297 ' >' 2 +298 ' ?' 2 +299 ' @' 2 +300 ' A' 2 +301 ' B' 2 +302 ' C' 2 +303 ' D' 2 +304 ' E' 2 +305 ' F' 2 +306 ' G' 2 +307 ' H' 2 +308 ' I' 2 +309 ' J' 2 +310 ' K' 2 +311 ' L' 2 +312 ' M' 2 +313 ' N' 2 +314 ' O' 2 +315 ' P' 2 +316 ' Q' 2 +317 ' R' 2 +318 ' S' 2 +319 ' T' 2 +320 ' U' 2 +321 ' V' 2 +322 ' W' 2 +323 ' X' 2 +324 ' Y' 2 +325 ' Z' 2 +326 ' [' 2 +327 ' \\' 2 +328 ' ]' 2 +329 ' ^' 2 +330 ' _' 2 +331 ' `' 2 +332 ' a' 2 +333 ' b' 2 +334 ' c' 2 +335 ' d' 2 +336 ' e' 2 +337 ' f' 2 +338 ' g' 2 +339 ' h' 2 +340 ' i' 2 +341 ' j' 2 +342 ' k' 2 +343 ' l' 2 +344 ' m' 2 +345 ' n' 2 +346 ' o' 2 +347 ' p' 2 +348 ' q' 2 +349 ' r' 2 +350 ' s' 2 +351 ' t' 2 +352 ' u' 2 +353 ' v' 2 +354 ' w' 2 +355 ' x' 2 +356 ' y' 2 +357 ' z' 2 +358 ' {' 2 +359 ' |' 2 +360 ' }' 2 +361 ' ~' 2 +362 '!!' 2 +363 '!"' 2 +364 "!'" 2 +365 '!(' 2 +366 '!)' 2 +367 '!,' 2 +368 '!.' 2 +369 '!/' 2 +370 '!=' 2 +371 '!?' 2 +372 '![' 2 +373 '!\\' 2 +374 '""' 2 +375 '"#' 2 +376 '"$' 2 +377 '"%' 2 +378 '"&' 2 +379 '"\'' 2 +380 '"(' 2 +381 '")' 2 +382 '"*' 2 +383 '"+' 2 +384 '",' 2 +385 '"-' 2 +386 '".' 2 +387 '"/' 2 +388 '":' 2 +389 '";' 2 +390 '"<' 2 +391 '">' 2 +392 '"?' 2 +393 '"[' 2 +394 '"\\' 2 +395 '"]' 2 +396 '"_' 2 +397 '"`' 2 +398 '"{' 2 +399 '"}' 2 +400 '#!' 2 +401 '#"' 2 +402 '##' 2 +403 "#'" 2 +404 '#,' 2 +405 '#.' 2 +406 '#:' 2 +407 '#{' 2 +408 '$"' 2 +409 '$$' 2 +410 "$'" 2 +411 '$(' 2 +412 '$,' 2 +413 '$.' 2 +414 '$/' 2 +415 '$:' 2 +416 '$;' 2 +417 '$\\' 2 +418 '$_' 2 +419 '${' 2 +420 '%"' 2 +421 '%%' 2 +422 "%'" 2 +423 '%(' 2 +424 '%)' 2 +425 '%,' 2 +426 '%-' 2 +427 '%.' 2 +428 '%;' 2 +429 '%=' 2 +430 '%\\' 2 +431 '&#' 2 +432 '&&' 2 +433 '&=' 2 +434 '&\\' 2 +435 '\'"' 2 +436 "'#" 2 +437 "'$" 2 +438 "'%" 2 +439 "''" 2 +440 "'(" 2 +441 "')" 2 +442 "'*" 2 +443 "'+" 2 +444 "'," 2 +445 "'-" 2 +446 "'." 2 +447 "'/" 2 +448 "':" 2 +449 "';" 2 +450 "'<" 2 +451 "'>" 2 +452 "'?" 2 +453 "'[" 2 +454 "'\\" 2 +455 "']" 2 +456 "'^" 2 +457 "'_" 2 +458 "'d" 2 +459 "'m" 2 +460 "'s" 2 +461 "'t" 2 +462 "'{" 2 +463 "'}" 2 +464 '(!' 2 +465 '("' 2 +466 '(#' 2 +467 '($' 2 +468 '(%' 2 +469 '(&' 2 +470 "('" 2 +471 '((' 2 +472 '()' 2 +473 '(*' 2 +474 '(+' 2 +475 '(-' 2 +476 '(.' 2 +477 '(/' 2 +478 '(:' 2 +479 '(<' 2 +480 '(?' 2 +481 '(@' 2 +482 '([' 2 +483 '(\\' 2 +484 '(_' 2 +485 '(`' 2 +486 '({' 2 +487 '(|' 2 +488 ')!' 2 +489 ')"' 2 +490 ')$' 2 +491 ')&' 2 +492 ")'" 2 +493 ')(' 2 +494 '))' 2 +495 ')*' 2 +496 ')+' 2 +497 '),' 2 +498 ')-' 2 +499 ').' 2 +500 ')/' 2 +501 '):' 2 +502 ');' 2 +503 ')<' 2 +504 ')=' 2 +505 ')>' 2 +506 ')?' 2 +507 ')[' 2 +508 ')\\' 2 +509 ')]' 2 +510 ')^' 2 +511 ')_' 2 +512 ')`' 2 +513 '){' 2 +514 ')|' 2 +515 ')}' 2 +516 '*"' 2 +517 "*'" 2 +518 '*(' 2 +519 '*)' 2 +520 '**' 2 +521 '*,' 2 +522 '*-' 2 +523 '*.' 2 +524 '*/' 2 +525 '*:' 2 +526 '*=' 2 +527 '*>' 2 +528 '*\\' 2 +529 '*_' 2 +530 '*}' 2 +531 '+"' 2 +532 '+$' 2 +533 "+'" 2 +534 '+(' 2 +535 '+)' 2 +536 '++' 2 +537 '+,' 2 +538 '+-' 2 +539 '+.' 2 +540 '+/' 2 +541 '+=' 2 +542 '+[' 2 +543 '+\\' 2 +544 ',"' 2 +545 ',#' 2 +546 ',$' 2 +547 ',%' 2 +548 ",'" 2 +549 ',(' 2 +550 ',)' 2 +551 ',*' 2 +552 ',,' 2 +553 ',-' 2 +554 ',.' 2 +555 ',[' 2 +556 ',\\' 2 +557 ',_' 2 +558 ',{' 2 +559 '-"' 2 +560 '-$' 2 +561 '-%' 2 +562 "-'" 2 +563 '-(' 2 +564 '-)' 2 +565 '-*' 2 +566 '-+' 2 +567 '-,' 2 +568 '--' 2 +569 '-.' 2 +570 '-=' 2 +571 '->' 2 +572 '-[' 2 +573 '-\\' 2 +574 '-{' 2 +575 '."' 2 +576 '.$' 2 +577 '.%' 2 +578 ".'" 2 +579 '.(' 2 +580 '.)' 2 +581 '.*' 2 +582 '.+' 2 +583 '.,' 2 +584 '.-' 2 +585 '..' 2 +586 './' 2 +587 '.:' 2 +588 '.;' 2 +589 '.<' 2 +590 '.=' 2 +591 '.?' 2 +592 '.[' 2 +593 '.\\' 2 +594 '.]' 2 +595 '._' 2 +596 '.|' 2 +597 '/"' 2 +598 '/#' 2 +599 '/$' 2 +600 '/%' 2 +601 "/'" 2 +602 '/(' 2 +603 '/)' 2 +604 '/*' 2 +605 '/+' 2 +606 '/,' 2 +607 '/-' 2 +608 '/.' 2 +609 '//' 2 +610 '/:' 2 +611 '/<' 2 +612 '/>' 2 +613 '/?' 2 +614 '/@' 2 +615 '/[' 2 +616 '/\\' 2 +617 '/_' 2 +618 '/{' 2 +619 '/~' 2 +620 '00' 2 +621 '01' 2 +622 '02' 2 +623 '03' 2 +624 '04' 2 +625 '05' 2 +626 '06' 2 +627 '07' 2 +628 '08' 2 +629 '09' 2 +630 '10' 2 +631 '11' 2 +632 '12' 2 +633 '13' 2 +634 '14' 2 +635 '15' 2 +636 '16' 2 +637 '17' 2 +638 '18' 2 +639 '19' 2 +640 '20' 2 +641 '21' 2 +642 '22' 2 +643 '23' 2 +644 '24' 2 +645 '25' 2 +646 '26' 2 +647 '27' 2 +648 '28' 2 +649 '29' 2 +650 '30' 2 +651 '31' 2 +652 '32' 2 +653 '33' 2 +654 '34' 2 +655 '35' 2 +656 '36' 2 +657 '37' 2 +658 '38' 2 +659 '39' 2 +660 '40' 2 +661 '41' 2 +662 '42' 2 +663 '43' 2 +664 '44' 2 +665 '45' 2 +666 '46' 2 +667 '47' 2 +668 '48' 2 +669 '49' 2 +670 '50' 2 +671 '51' 2 +672 '52' 2 +673 '53' 2 +674 '54' 2 +675 '55' 2 +676 '56' 2 +677 '57' 2 +678 '58' 2 +679 '59' 2 +680 '60' 2 +681 '61' 2 +682 '62' 2 +683 '63' 2 +684 '64' 2 +685 '65' 2 +686 '66' 2 +687 '67' 2 +688 '68' 2 +689 '69' 2 +690 '70' 2 +691 '71' 2 +692 '72' 2 +693 '73' 2 +694 '74' 2 +695 '75' 2 +696 '76' 2 +697 '77' 2 +698 '78' 2 +699 '79' 2 +700 '80' 2 +701 '81' 2 +702 '82' 2 +703 '83' 2 +704 '84' 2 +705 '85' 2 +706 '86' 2 +707 '87' 2 +708 '88' 2 +709 '89' 2 +710 '90' 2 +711 '91' 2 +712 '92' 2 +713 '93' 2 +714 '94' 2 +715 '95' 2 +716 '96' 2 +717 '97' 2 +718 '98' 2 +719 '99' 2 +720 ':"' 2 +721 ':#' 2 +722 ':$' 2 +723 ':%' 2 +724 ":'" 2 +725 ':(' 2 +726 ':)' 2 +727 ':*' 2 +728 ':,' 2 +729 ':-' 2 +730 ':.' 2 +731 ':/' 2 +732 '::' 2 +733 ':=' 2 +734 ':@' 2 +735 ':[' 2 +736 ':\\' 2 +737 ':]' 2 +738 ':_' 2 +739 ':`' 2 +740 ':{' 2 +741 ';"' 2 +742 ';&' 2 +743 ";'" 2 +744 ';-' 2 +745 ';/' 2 +746 ';;' 2 +747 ';<' 2 +748 ';\\' 2 +749 ';}' 2 +750 '' 2 +758 '' 2 +774 '=[' 2 +775 '=\\' 2 +776 '=_' 2 +777 '=`' 2 +778 '={' 2 +779 '>"' 2 +780 '>&' 2 +781 ">'" 2 +782 '>(' 2 +783 '>)' 2 +784 '>,' 2 +785 '>-' 2 +786 '>.' 2 +787 '>/' 2 +788 '>:' 2 +789 '>;' 2 +790 '><' 2 +791 '>=' 2 +792 '>>' 2 +793 '>[' 2 +794 '>\\' 2 +795 '>]' 2 +796 '>`' 2 +797 '>{' 2 +798 '?!' 2 +799 '?"' 2 +800 "?'" 2 +801 '?(' 2 +802 '?)' 2 +803 '?,' 2 +804 '?.' 2 +805 '?:' 2 +806 '?>' 2 +807 '??' 2 +808 '?\\' 2 +809 '@"' 2 +810 '@@' 2 +811 '@{' 2 +812 'AA' 2 +813 'AB' 2 +814 'AC' 2 +815 'AD' 2 +816 'AE' 2 +817 'AF' 2 +818 'AG' 2 +819 'AH' 2 +820 'AI' 2 +821 'AJ' 2 +822 'AK' 2 +823 'AL' 2 +824 'AM' 2 +825 'AN' 2 +826 'AO' 2 +827 'AP' 2 +828 'AQ' 2 +829 'AR' 2 +830 'AS' 2 +831 'AT' 2 +832 'AU' 2 +833 'AV' 2 +834 'AW' 2 +835 'AX' 2 +836 'AY' 2 +837 'AZ' 2 +838 'Ab' 2 +839 'Ac' 2 +840 'Ad' 2 +841 'Af' 2 +842 'Ag' 2 +843 'Ah' 2 +844 'Ai' 2 +845 'Aj' 2 +846 'Ak' 2 +847 'Al' 2 +848 'Am' 2 +849 'An' 2 +850 'Ao' 2 +851 'Ap' 2 +852 'Ar' 2 +853 'As' 2 +854 'At' 2 +855 'Au' 2 +856 'Av' 2 +857 'Aw' 2 +858 'Ax' 2 +859 'Ay' 2 +860 'Az' 2 +861 'BA' 2 +862 'BB' 2 +863 'BC' 2 +864 'BD' 2 +865 'BE' 2 +866 'BF' 2 +867 'BG' 2 +868 'BH' 2 +869 'BI' 2 +870 'BJ' 2 +871 'BK' 2 +872 'BL' 2 +873 'BM' 2 +874 'BN' 2 +875 'BO' 2 +876 'BP' 2 +877 'BR' 2 +878 'BS' 2 +879 'BT' 2 +880 'BU' 2 +881 'BV' 2 +882 'BW' 2 +883 'BY' 2 +884 'BZ' 2 +885 'Ba' 2 +886 'Be' 2 +887 'Bg' 2 +888 'Bi' 2 +889 'Bl' 2 +890 'Bo' 2 +891 'Br' 2 +892 'Bs' 2 +893 'Bu' 2 +894 'By' 2 +895 'CA' 2 +896 'CB' 2 +897 'CC' 2 +898 'CD' 2 +899 'CE' 2 +900 'CF' 2 +901 'CG' 2 +902 'CH' 2 +903 'CI' 2 +904 'CK' 2 +905 'CL' 2 +906 'CM' 2 +907 'CN' 2 +908 'CO' 2 +909 'CP' 2 +910 'CR' 2 +911 'CS' 2 +912 'CT' 2 +913 'CU' 2 +914 'CV' 2 +915 'CW' 2 +916 'CX' 2 +917 'CY' 2 +918 'Ca' 2 +919 'Cb' 2 +920 'Cd' 2 +921 'Ce' 2 +922 'Ch' 2 +923 'Ci' 2 +924 'Cl' 2 +925 'Co' 2 +926 'Cp' 2 +927 'Cr' 2 +928 'Cs' 2 +929 'Ct' 2 +930 'Cu' 2 +931 'Cy' 2 +932 'DA' 2 +933 'DB' 2 +934 'DC' 2 +935 'DD' 2 +936 'DE' 2 +937 'DF' 2 +938 'DG' 2 +939 'DH' 2 +940 'DI' 2 +941 'DJ' 2 +942 'DK' 2 +943 'DL' 2 +944 'DM' 2 +945 'DN' 2 +946 'DO' 2 +947 'DP' 2 +948 'DQ' 2 +949 'DR' 2 +950 'DS' 2 +951 'DT' 2 +952 'DU' 2 +953 'DV' 2 +954 'DW' 2 +955 'DX' 2 +956 'DY' 2 +957 'Da' 2 +958 'Db' 2 +959 'De' 2 +960 'Di' 2 +961 'Do' 2 +962 'Dr' 2 +963 'Ds' 2 +964 'Du' 2 +965 'Dy' 2 +966 'EA' 2 +967 'EB' 2 +968 'EC' 2 +969 'ED' 2 +970 'EE' 2 +971 'EF' 2 +972 'EG' 2 +973 'EH' 2 +974 'EI' 2 +975 'EK' 2 +976 'EL' 2 +977 'EM' 2 +978 'EN' 2 +979 'EO' 2 +980 'EP' 2 +981 'EQ' 2 +982 'ER' 2 +983 'ES' 2 +984 'ET' 2 +985 'EU' 2 +986 'EV' 2 +987 'EW' 2 +988 'EX' 2 +989 'EY' 2 +990 'Ec' 2 +991 'Ed' 2 +992 'Eg' 2 +993 'Eh' 2 +994 'El' 2 +995 'Em' 2 +996 'En' 2 +997 'Ep' 2 +998 'Eq' 2 +999 'Er' 2 +1000 'Es' 2 +1001 'Et' 2 +1002 'Eu' 2 +1003 'Ev' 2 +1004 'Ex' 2 +1005 'Ey' 2 +1006 'FA' 2 +1007 'FB' 2 +1008 'FC' 2 +1009 'FD' 2 +1010 'FE' 2 +1011 'FF' 2 +1012 'FG' 2 +1013 'FH' 2 +1014 'FI' 2 +1015 'FK' 2 +1016 'FL' 2 +1017 'FM' 2 +1018 'FN' 2 +1019 'FO' 2 +1020 'FP' 2 +1021 'FR' 2 +1022 'FS' 2 +1023 'FT' 2 +1024 'FU' 2 +1025 'FV' 2 +1026 'FW' 2 +1027 'FX' 2 +1028 'FY' 2 +1029 'Fa' 2 +1030 'Fc' 2 +1031 'Fe' 2 +1032 'Fi' 2 +1033 'Fl' 2 +1034 'Fn' 2 +1035 'Fo' 2 +1036 'Fr' 2 +1037 'Fs' 2 +1038 'Fu' 2 +1039 'GA' 2 +1040 'GB' 2 +1041 'GC' 2 +1042 'GD' 2 +1043 'GE' 2 +1044 'GF' 2 +1045 'GG' 2 +1046 'GH' 2 +1047 'GI' 2 +1048 'GL' 2 +1049 'GM' 2 +1050 'GN' 2 +1051 'GO' 2 +1052 'GP' 2 +1053 'GR' 2 +1054 'GS' 2 +1055 'GT' 2 +1056 'GU' 2 +1057 'GV' 2 +1058 'GW' 2 +1059 'GY' 2 +1060 'Ga' 2 +1061 'Gb' 2 +1062 'Ge' 2 +1063 'Gh' 2 +1064 'Gi' 2 +1065 'Gl' 2 +1066 'Go' 2 +1067 'Gr' 2 +1068 'Gs' 2 +1069 'Gu' 2 +1070 'Gy' 2 +1071 'HA' 2 +1072 'HB' 2 +1073 'HC' 2 +1074 'HD' 2 +1075 'HE' 2 +1076 'HF' 2 +1077 'HG' 2 +1078 'HH' 2 +1079 'HI' 2 +1080 'HK' 2 +1081 'HL' 2 +1082 'HM' 2 +1083 'HN' 2 +1084 'HO' 2 +1085 'HP' 2 +1086 'HQ' 2 +1087 'HR' 2 +1088 'HS' 2 +1089 'HT' 2 +1090 'HU' 2 +1091 'HV' 2 +1092 'HW' 2 +1093 'HY' 2 +1094 'Ha' 2 +1095 'He' 2 +1096 'Hg' 2 +1097 'Hi' 2 +1098 'Ho' 2 +1099 'Hp' 2 +1100 'Hs' 2 +1101 'Hu' 2 +1102 'Hy' 2 +1103 'Hz' 2 +1104 'IA' 2 +1105 'IB' 2 +1106 'IC' 2 +1107 'ID' 2 +1108 'IE' 2 +1109 'IF' 2 +1110 'IG' 2 +1111 'IH' 2 +1112 'II' 2 +1113 'IJ' 2 +1114 'IK' 2 +1115 'IL' 2 +1116 'IM' 2 +1117 'IN' 2 +1118 'IO' 2 +1119 'IP' 2 +1120 'IQ' 2 +1121 'IR' 2 +1122 'IS' 2 +1123 'IT' 2 +1124 'IU' 2 +1125 'IV' 2 +1126 'IW' 2 +1127 'IX' 2 +1128 'IZ' 2 +1129 'Id' 2 +1130 'If' 2 +1131 'Ig' 2 +1132 'Ii' 2 +1133 'Ik' 2 +1134 'Il' 2 +1135 'Im' 2 +1136 'In' 2 +1137 'Io' 2 +1138 'Ip' 2 +1139 'Ir' 2 +1140 'Is' 2 +1141 'It' 2 +1142 'Iz' 2 +1143 'JA' 2 +1144 'JB' 2 +1145 'JC' 2 +1146 'JD' 2 +1147 'JE' 2 +1148 'JF' 2 +1149 'JI' 2 +1150 'JJ' 2 +1151 'JK' 2 +1152 'JM' 2 +1153 'JO' 2 +1154 'JP' 2 +1155 'JR' 2 +1156 'JS' 2 +1157 'JT' 2 +1158 'JU' 2 +1159 'Ja' 2 +1160 'Je' 2 +1161 'Ji' 2 +1162 'Jo' 2 +1163 'Js' 2 +1164 'Ju' 2 +1165 'Jy' 2 +1166 'KA' 2 +1167 'KB' 2 +1168 'KC' 2 +1169 'KD' 2 +1170 'KE' 2 +1171 'KF' 2 +1172 'KG' 2 +1173 'KH' 2 +1174 'KI' 2 +1175 'KK' 2 +1176 'KL' 2 +1177 'KM' 2 +1178 'KN' 2 +1179 'KO' 2 +1180 'KP' 2 +1181 'KR' 2 +1182 'KS' 2 +1183 'KT' 2 +1184 'KV' 2 +1185 'KW' 2 +1186 'KY' 2 +1187 'Ka' 2 +1188 'Ke' 2 +1189 'Kh' 2 +1190 'Ki' 2 +1191 'Kn' 2 +1192 'Ko' 2 +1193 'Kr' 2 +1194 'Ku' 2 +1195 'Ky' 2 +1196 'LA' 2 +1197 'LB' 2 +1198 'LC' 2 +1199 'LD' 2 +1200 'LE' 2 +1201 'LF' 2 +1202 'LG' 2 +1203 'LH' 2 +1204 'LI' 2 +1205 'LL' 2 +1206 'LM' 2 +1207 'LN' 2 +1208 'LO' 2 +1209 'LP' 2 +1210 'LR' 2 +1211 'LS' 2 +1212 'LT' 2 +1213 'LU' 2 +1214 'LV' 2 +1215 'LW' 2 +1216 'LY' 2 +1217 'La' 2 +1218 'Le' 2 +1219 'Li' 2 +1220 'Ll' 2 +1221 'Ln' 2 +1222 'Lo' 2 +1223 'Lt' 2 +1224 'Lu' 2 +1225 'Ly' 2 +1226 'MA' 2 +1227 'MB' 2 +1228 'MC' 2 +1229 'MD' 2 +1230 'ME' 2 +1231 'MF' 2 +1232 'MG' 2 +1233 'MH' 2 +1234 'MI' 2 +1235 'MK' 2 +1236 'ML' 2 +1237 'MM' 2 +1238 'MN' 2 +1239 'MO' 2 +1240 'MP' 2 +1241 'MQ' 2 +1242 'MR' 2 +1243 'MS' 2 +1244 'MT' 2 +1245 'MU' 2 +1246 'MV' 2 +1247 'MW' 2 +1248 'MX' 2 +1249 'MY' 2 +1250 'Ma' 2 +1251 'Mb' 2 +1252 'Mc' 2 +1253 'Me' 2 +1254 'Mg' 2 +1255 'Mi' 2 +1256 'Mj' 2 +1257 'Mn' 2 +1258 'Mo' 2 +1259 'Mp' 2 +1260 'Mr' 2 +1261 'Ms' 2 +1262 'Mt' 2 +1263 'Mu' 2 +1264 'My' 2 +1265 'Mz' 2 +1266 'NA' 2 +1267 'NB' 2 +1268 'NC' 2 +1269 'ND' 2 +1270 'NE' 2 +1271 'NF' 2 +1272 'NG' 2 +1273 'NH' 2 +1274 'NI' 2 +1275 'NJ' 2 +1276 'NK' 2 +1277 'NL' 2 +1278 'NM' 2 +1279 'NN' 2 +1280 'NO' 2 +1281 'NP' 2 +1282 'NR' 2 +1283 'NS' 2 +1284 'NT' 2 +1285 'NU' 2 +1286 'NV' 2 +1287 'NW' 2 +1288 'NX' 2 +1289 'NY' 2 +1290 'NZ' 2 +1291 'Na' 2 +1292 'Nb' 2 +1293 'Nd' 2 +1294 'Ne' 2 +1295 'Ng' 2 +1296 'Ni' 2 +1297 'No' 2 +1298 'Nr' 2 +1299 'Ns' 2 +1300 'Nu' 2 +1301 'Nx' 2 +1302 'Ny' 2 +1303 'Nz' 2 +1304 'OA' 2 +1305 'OB' 2 +1306 'OC' 2 +1307 'OD' 2 +1308 'OE' 2 +1309 'OF' 2 +1310 'OG' 2 +1311 'OH' 2 +1312 'OI' 2 +1313 'OK' 2 +1314 'OL' 2 +1315 'OM' 2 +1316 'ON' 2 +1317 'OO' 2 +1318 'OP' 2 +1319 'OR' 2 +1320 'OS' 2 +1321 'OT' 2 +1322 'OU' 2 +1323 'OV' 2 +1324 'OW' 2 +1325 'OX' 2 +1326 'OY' 2 +1327 'Ob' 2 +1328 'Oc' 2 +1329 'Od' 2 +1330 'Of' 2 +1331 'Oh' 2 +1332 'Oi' 2 +1333 'Ok' 2 +1334 'Ol' 2 +1335 'Om' 2 +1336 'On' 2 +1337 'Op' 2 +1338 'Or' 2 +1339 'Os' 2 +1340 'Ot' 2 +1341 'Ox' 2 +1342 'PA' 2 +1343 'PB' 2 +1344 'PC' 2 +1345 'PD' 2 +1346 'PE' 2 +1347 'PF' 2 +1348 'PG' 2 +1349 'PH' 2 +1350 'PI' 2 +1351 'PK' 2 +1352 'PL' 2 +1353 'PM' 2 +1354 'PN' 2 +1355 'PO' 2 +1356 'PP' 2 +1357 'PR' 2 +1358 'PS' 2 +1359 'PT' 2 +1360 'PU' 2 +1361 'PV' 2 +1362 'PW' 2 +1363 'PY' 2 +1364 'Pa' 2 +1365 'Pb' 2 +1366 'Pe' 2 +1367 'Ph' 2 +1368 'Pi' 2 +1369 'Pl' 2 +1370 'Po' 2 +1371 'Pr' 2 +1372 'Ps' 2 +1373 'Pt' 2 +1374 'Pu' 2 +1375 'Px' 2 +1376 'Py' 2 +1377 'QA' 2 +1378 'QB' 2 +1379 'QC' 2 +1380 'QE' 2 +1381 'QI' 2 +1382 'QL' 2 +1383 'QM' 2 +1384 'QP' 2 +1385 'QQ' 2 +1386 'QR' 2 +1387 'QS' 2 +1388 'QT' 2 +1389 'QU' 2 +1390 'Qi' 2 +1391 'Qt' 2 +1392 'Qu' 2 +1393 'RA' 2 +1394 'RB' 2 +1395 'RC' 2 +1396 'RD' 2 +1397 'RE' 2 +1398 'RF' 2 +1399 'RG' 2 +1400 'RH' 2 +1401 'RI' 2 +1402 'RK' 2 +1403 'RL' 2 +1404 'RM' 2 +1405 'RN' 2 +1406 'RO' 2 +1407 'RP' 2 +1408 'RR' 2 +1409 'RS' 2 +1410 'RT' 2 +1411 'RU' 2 +1412 'RV' 2 +1413 'RW' 2 +1414 'RX' 2 +1415 'RY' 2 +1416 'Ra' 2 +1417 'Re' 2 +1418 'Rh' 2 +1419 'Ri' 2 +1420 'Ro' 2 +1421 'Rp' 2 +1422 'Rs' 2 +1423 'Ru' 2 +1424 'Rv' 2 +1425 'Rx' 2 +1426 'Ry' 2 +1427 'SA' 2 +1428 'SB' 2 +1429 'SC' 2 +1430 'SD' 2 +1431 'SE' 2 +1432 'SF' 2 +1433 'SG' 2 +1434 'SH' 2 +1435 'SI' 2 +1436 'SK' 2 +1437 'SL' 2 +1438 'SM' 2 +1439 'SN' 2 +1440 'SO' 2 +1441 'SP' 2 +1442 'SQ' 2 +1443 'SR' 2 +1444 'SS' 2 +1445 'ST' 2 +1446 'SU' 2 +1447 'SV' 2 +1448 'SW' 2 +1449 'SY' 2 +1450 'SZ' 2 +1451 'Sa' 2 +1452 'Sb' 2 +1453 'Sc' 2 +1454 'Se' 2 +1455 'Sh' 2 +1456 'Si' 2 +1457 'Sk' 2 +1458 'Sl' 2 +1459 'Sm' 2 +1460 'Sn' 2 +1461 'So' 2 +1462 'Sp' 2 +1463 'Sq' 2 +1464 'Sr' 2 +1465 'St' 2 +1466 'Su' 2 +1467 'Sw' 2 +1468 'Sy' 2 +1469 'Sz' 2 +1470 'TA' 2 +1471 'TB' 2 +1472 'TC' 2 +1473 'TD' 2 +1474 'TE' 2 +1475 'TF' 2 +1476 'TG' 2 +1477 'TH' 2 +1478 'TI' 2 +1479 'TK' 2 +1480 'TL' 2 +1481 'TM' 2 +1482 'TN' 2 +1483 'TO' 2 +1484 'TP' 2 +1485 'TR' 2 +1486 'TS' 2 +1487 'TT' 2 +1488 'TU' 2 +1489 'TV' 2 +1490 'TW' 2 +1491 'TX' 2 +1492 'TY' 2 +1493 'TZ' 2 +1494 'Ta' 2 +1495 'Tc' 2 +1496 'Te' 2 +1497 'Th' 2 +1498 'Ti' 2 +1499 'Tk' 2 +1500 'To' 2 +1501 'Tp' 2 +1502 'Tr' 2 +1503 'Ts' 2 +1504 'Tu' 2 +1505 'Tw' 2 +1506 'Tx' 2 +1507 'Ty' 2 +1508 'UA' 2 +1509 'UB' 2 +1510 'UC' 2 +1511 'UD' 2 +1512 'UE' 2 +1513 'UF' 2 +1514 'UG' 2 +1515 'UH' 2 +1516 'UI' 2 +1517 'UK' 2 +1518 'UL' 2 +1519 'UM' 2 +1520 'UN' 2 +1521 'UP' 2 +1522 'UR' 2 +1523 'US' 2 +1524 'UT' 2 +1525 'UU' 2 +1526 'UV' 2 +1527 'UX' 2 +1528 'UY' 2 +1529 'Ub' 2 +1530 'Uh' 2 +1531 'Ui' 2 +1532 'Uk' 2 +1533 'Ul' 2 +1534 'Um' 2 +1535 'Un' 2 +1536 'Up' 2 +1537 'Ur' 2 +1538 'Us' 2 +1539 'Ut' 2 +1540 'VA' 2 +1541 'VB' 2 +1542 'VC' 2 +1543 'VD' 2 +1544 'VE' 2 +1545 'VF' 2 +1546 'VG' 2 +1547 'VH' 2 +1548 'VI' 2 +1549 'VK' 2 +1550 'VL' 2 +1551 'VM' 2 +1552 'VN' 2 +1553 'VO' 2 +1554 'VP' 2 +1555 'VR' 2 +1556 'VS' 2 +1557 'VT' 2 +1558 'VV' 2 +1559 'Va' 2 +1560 'Ve' 2 +1561 'Vi' 2 +1562 'Vm' 2 +1563 'Vo' 2 +1564 'Vs' 2 +1565 'Vu' 2 +1566 'Vy' 2 +1567 'WA' 2 +1568 'WB' 2 +1569 'WC' 2 +1570 'WD' 2 +1571 'WE' 2 +1572 'WF' 2 +1573 'WG' 2 +1574 'WH' 2 +1575 'WI' 2 +1576 'WK' 2 +1577 'WL' 2 +1578 'WM' 2 +1579 'WN' 2 +1580 'WO' 2 +1581 'WP' 2 +1582 'WR' 2 +1583 'WS' 2 +1584 'WT' 2 +1585 'WV' 2 +1586 'WW' 2 +1587 'WX' 2 +1588 'Wa' 2 +1589 'We' 2 +1590 'Wh' 2 +1591 'Wi' 2 +1592 'Wo' 2 +1593 'Wr' 2 +1594 'Ws' 2 +1595 'Wy' 2 +1596 'XA' 2 +1597 'XB' 2 +1598 'XC' 2 +1599 'XD' 2 +1600 'XF' 2 +1601 'XG' 2 +1602 'XI' 2 +1603 'XL' 2 +1604 'XM' 2 +1605 'XP' 2 +1606 'XR' 2 +1607 'XS' 2 +1608 'XT' 2 +1609 'XV' 2 +1610 'XX' 2 +1611 'XY' 2 +1612 'Xi' 2 +1613 'YA' 2 +1614 'YC' 2 +1615 'YE' 2 +1616 'YL' 2 +1617 'YM' 2 +1618 'YN' 2 +1619 'YO' 2 +1620 'YP' 2 +1621 'YR' 2 +1622 'YS' 2 +1623 'YT' 2 +1624 'YW' 2 +1625 'YX' 2 +1626 'YY' 2 +1627 'Ya' 2 +1628 'Ye' 2 +1629 'Yo' 2 +1630 'Yu' 2 +1631 'ZA' 2 +1632 'ZE' 2 +1633 'ZH' 2 +1634 'ZO' 2 +1635 'ZT' 2 +1636 'ZW' 2 +1637 'ZX' 2 +1638 'ZY' 2 +1639 'ZZ' 2 +1640 'Za' 2 +1641 'Ze' 2 +1642 'Zh' 2 +1643 'Zn' 2 +1644 '["' 2 +1645 '[$' 2 +1646 "['" 2 +1647 '[(' 2 +1648 '[*' 2 +1649 '[,' 2 +1650 '[-' 2 +1651 '[/' 2 +1652 '[:' 2 +1653 '[@' 2 +1654 '[[' 2 +1655 '[\\' 2 +1656 '[]' 2 +1657 '[^' 2 +1658 '[_' 2 +1659 '[{' 2 +1660 '\\"' 2 +1661 '\\$' 2 +1662 '\\%' 2 +1663 "\\'" 2 +1664 '\\(' 2 +1665 '\\)' 2 +1666 '\\,' 2 +1667 '\\-' 2 +1668 '\\.' 2 +1669 '\\/' 2 +1670 '\\;' 2 +1671 '\\<' 2 +1672 '\\[' 2 +1673 '\\\\' 2 +1674 '\\]' 2 +1675 '\\_' 2 +1676 '\\{' 2 +1677 '\\}' 2 +1678 ']"' 2 +1679 ']$' 2 +1680 "]'" 2 +1681 '](' 2 +1682 '])' 2 +1683 ']*' 2 +1684 ']+' 2 +1685 '],' 2 +1686 ']-' 2 +1687 '].' 2 +1688 ']/' 2 +1689 ']:' 2 +1690 '];' 2 +1691 ']<' 2 +1692 ']=' 2 +1693 ']>' 2 +1694 ']?' 2 +1695 '][' 2 +1696 ']\\' 2 +1697 ']]' 2 +1698 ']_' 2 +1699 ']{' 2 +1700 ']|' 2 +1701 ']}' 2 +1702 '^(' 2 +1703 '^*' 2 +1704 '^-' 2 +1705 '^\\' 2 +1706 '^^' 2 +1707 '^{' 2 +1708 '_"' 2 +1709 '_%' 2 +1710 "_'" 2 +1711 '_(' 2 +1712 '_)' 2 +1713 '_*' 2 +1714 '_,' 2 +1715 '_-' 2 +1716 '_.' 2 +1717 '_:' 2 +1718 '_;' 2 +1719 '_<' 2 +1720 '_>' 2 +1721 '_[' 2 +1722 '_\\' 2 +1723 '_]' 2 +1724 '__' 2 +1725 '_{' 2 +1726 '`)' 2 +1727 '`,' 2 +1728 '`.' 2 +1729 '`:' 2 +1730 '`;' 2 +1731 '`\\' 2 +1732 '``' 2 +1733 'aa' 2 +1734 'ab' 2 +1735 'ac' 2 +1736 'ad' 2 +1737 'ae' 2 +1738 'af' 2 +1739 'ag' 2 +1740 'ah' 2 +1741 'ai' 2 +1742 'aj' 2 +1743 'ak' 2 +1744 'al' 2 +1745 'am' 2 +1746 'an' 2 +1747 'ao' 2 +1748 'ap' 2 +1749 'aq' 2 +1750 'ar' 2 +1751 'as' 2 +1752 'at' 2 +1753 'au' 2 +1754 'av' 2 +1755 'aw' 2 +1756 'ax' 2 +1757 'ay' 2 +1758 'az' 2 +1759 'ba' 2 +1760 'bb' 2 +1761 'bc' 2 +1762 'bd' 2 +1763 'be' 2 +1764 'bf' 2 +1765 'bg' 2 +1766 'bh' 2 +1767 'bi' 2 +1768 'bj' 2 +1769 'bk' 2 +1770 'bl' 2 +1771 'bm' 2 +1772 'bn' 2 +1773 'bo' 2 +1774 'bp' 2 +1775 'br' 2 +1776 'bs' 2 +1777 'bt' 2 +1778 'bu' 2 +1779 'bv' 2 +1780 'bw' 2 +1781 'bx' 2 +1782 'by' 2 +1783 'bz' 2 +1784 'ca' 2 +1785 'cb' 2 +1786 'cc' 2 +1787 'cd' 2 +1788 'ce' 2 +1789 'cf' 2 +1790 'cg' 2 +1791 'ch' 2 +1792 'ci' 2 +1793 'cj' 2 +1794 'ck' 2 +1795 'cl' 2 +1796 'cm' 2 +1797 'cn' 2 +1798 'co' 2 +1799 'cp' 2 +1800 'cq' 2 +1801 'cr' 2 +1802 'cs' 2 +1803 'ct' 2 +1804 'cu' 2 +1805 'cv' 2 +1806 'cw' 2 +1807 'cx' 2 +1808 'cy' 2 +1809 'cz' 2 +1810 'dB' 2 +1811 'dL' 2 +1812 'dT' 2 +1813 'dX' 2 +1814 'da' 2 +1815 'db' 2 +1816 'dc' 2 +1817 'dd' 2 +1818 'de' 2 +1819 'df' 2 +1820 'dg' 2 +1821 'dh' 2 +1822 'di' 2 +1823 'dj' 2 +1824 'dk' 2 +1825 'dl' 2 +1826 'dm' 2 +1827 'dn' 2 +1828 'do' 2 +1829 'dp' 2 +1830 'dq' 2 +1831 'dr' 2 +1832 'ds' 2 +1833 'dt' 2 +1834 'du' 2 +1835 'dv' 2 +1836 'dw' 2 +1837 'dx' 2 +1838 'dy' 2 +1839 'dz' 2 +1840 'ea' 2 +1841 'eb' 2 +1842 'ec' 2 +1843 'ed' 2 +1844 'ee' 2 +1845 'ef' 2 +1846 'eg' 2 +1847 'eh' 2 +1848 'ei' 2 +1849 'ej' 2 +1850 'ek' 2 +1851 'el' 2 +1852 'em' 2 +1853 'en' 2 +1854 'eo' 2 +1855 'ep' 2 +1856 'eq' 2 +1857 'er' 2 +1858 'es' 2 +1859 'et' 2 +1860 'eu' 2 +1861 'ev' 2 +1862 'ew' 2 +1863 'ex' 2 +1864 'ey' 2 +1865 'ez' 2 +1866 'fa' 2 +1867 'fb' 2 +1868 'fc' 2 +1869 'fd' 2 +1870 'fe' 2 +1871 'ff' 2 +1872 'fg' 2 +1873 'fh' 2 +1874 'fi' 2 +1875 'fj' 2 +1876 'fk' 2 +1877 'fl' 2 +1878 'fm' 2 +1879 'fn' 2 +1880 'fo' 2 +1881 'fp' 2 +1882 'fq' 2 +1883 'fr' 2 +1884 'fs' 2 +1885 'ft' 2 +1886 'fu' 2 +1887 'fv' 2 +1888 'fw' 2 +1889 'fx' 2 +1890 'fy' 2 +1891 'ga' 2 +1892 'gb' 2 +1893 'gc' 2 +1894 'gd' 2 +1895 'ge' 2 +1896 'gf' 2 +1897 'gg' 2 +1898 'gh' 2 +1899 'gi' 2 +1900 'gl' 2 +1901 'gm' 2 +1902 'gn' 2 +1903 'go' 2 +1904 'gp' 2 +1905 'gr' 2 +1906 'gs' 2 +1907 'gt' 2 +1908 'gu' 2 +1909 'gv' 2 +1910 'gw' 2 +1911 'gx' 2 +1912 'gy' 2 +1913 'gz' 2 +1914 'ha' 2 +1915 'hb' 2 +1916 'hc' 2 +1917 'hd' 2 +1918 'he' 2 +1919 'hf' 2 +1920 'hg' 2 +1921 'hh' 2 +1922 'hi' 2 +1923 'hj' 2 +1924 'hk' 2 +1925 'hl' 2 +1926 'hm' 2 +1927 'hn' 2 +1928 'ho' 2 +1929 'hp' 2 +1930 'hr' 2 +1931 'hs' 2 +1932 'ht' 2 +1933 'hu' 2 +1934 'hw' 2 +1935 'hy' 2 +1936 'hz' 2 +1937 'ia' 2 +1938 'ib' 2 +1939 'ic' 2 +1940 'id' 2 +1941 'ie' 2 +1942 'if' 2 +1943 'ig' 2 +1944 'ih' 2 +1945 'ii' 2 +1946 'ij' 2 +1947 'ik' 2 +1948 'il' 2 +1949 'im' 2 +1950 'in' 2 +1951 'io' 2 +1952 'ip' 2 +1953 'iq' 2 +1954 'ir' 2 +1955 'is' 2 +1956 'it' 2 +1957 'iu' 2 +1958 'iv' 2 +1959 'iw' 2 +1960 'ix' 2 +1961 'iy' 2 +1962 'iz' 2 +1963 'ja' 2 +1964 'jb' 2 +1965 'jc' 2 +1966 'jd' 2 +1967 'je' 2 +1968 'jh' 2 +1969 'ji' 2 +1970 'jj' 2 +1971 'jk' 2 +1972 'jl' 2 +1973 'jm' 2 +1974 'jn' 2 +1975 'jo' 2 +1976 'jp' 2 +1977 'jq' 2 +1978 'jr' 2 +1979 'js' 2 +1980 'jt' 2 +1981 'ju' 2 +1982 'jv' 2 +1983 'kB' 2 +1984 'ka' 2 +1985 'kb' 2 +1986 'kc' 2 +1987 'kd' 2 +1988 'ke' 2 +1989 'kg' 2 +1990 'kh' 2 +1991 'ki' 2 +1992 'kj' 2 +1993 'kk' 2 +1994 'kl' 2 +1995 'km' 2 +1996 'kn' 2 +1997 'ko' 2 +1998 'kp' 2 +1999 'kr' 2 +2000 'ks' 2 +2001 'kt' 2 +2002 'ku' 2 +2003 'kv' 2 +2004 'kw' 2 +2005 'kx' 2 +2006 'ky' 2 +2007 'la' 2 +2008 'lb' 2 +2009 'lc' 2 +2010 'ld' 2 +2011 'le' 2 +2012 'lf' 2 +2013 'lg' 2 +2014 'lh' 2 +2015 'li' 2 +2016 'lj' 2 +2017 'lk' 2 +2018 'll' 2 +2019 'lm' 2 +2020 'ln' 2 +2021 'lo' 2 +2022 'lp' 2 +2023 'lr' 2 +2024 'ls' 2 +2025 'lt' 2 +2026 'lu' 2 +2027 'lv' 2 +2028 'lw' 2 +2029 'lx' 2 +2030 'ly' 2 +2031 'lz' 2 +2032 'mL' 2 +2033 'mV' 2 +2034 'ma' 2 +2035 'mb' 2 +2036 'mc' 2 +2037 'md' 2 +2038 'me' 2 +2039 'mf' 2 +2040 'mg' 2 +2041 'mh' 2 +2042 'mi' 2 +2043 'mj' 2 +2044 'mk' 2 +2045 'ml' 2 +2046 'mm' 2 +2047 'mn' 2 +2048 'mo' 2 +2049 'mp' 2 +2050 'mq' 2 +2051 'mr' 2 +2052 'ms' 2 +2053 'mt' 2 +2054 'mu' 2 +2055 'mv' 2 +2056 'mw' 2 +2057 'mx' 2 +2058 'my' 2 +2059 'na' 2 +2060 'nb' 2 +2061 'nc' 2 +2062 'nd' 2 +2063 'ne' 2 +2064 'nf' 2 +2065 'ng' 2 +2066 'nh' 2 +2067 'ni' 2 +2068 'nj' 2 +2069 'nk' 2 +2070 'nl' 2 +2071 'nm' 2 +2072 'nn' 2 +2073 'no' 2 +2074 'np' 2 +2075 'nr' 2 +2076 'ns' 2 +2077 'nt' 2 +2078 'nu' 2 +2079 'nv' 2 +2080 'nw' 2 +2081 'nx' 2 +2082 'ny' 2 +2083 'nz' 2 +2084 'oS' 2 +2085 'oa' 2 +2086 'ob' 2 +2087 'oc' 2 +2088 'od' 2 +2089 'oe' 2 +2090 'of' 2 +2091 'og' 2 +2092 'oh' 2 +2093 'oi' 2 +2094 'oj' 2 +2095 'ok' 2 +2096 'ol' 2 +2097 'om' 2 +2098 'on' 2 +2099 'oo' 2 +2100 'op' 2 +2101 'or' 2 +2102 'os' 2 +2103 'ot' 2 +2104 'ou' 2 +2105 'ov' 2 +2106 'ow' 2 +2107 'ox' 2 +2108 'oy' 2 +2109 'oz' 2 +2110 'pH' 2 +2111 'pa' 2 +2112 'pb' 2 +2113 'pc' 2 +2114 'pd' 2 +2115 'pe' 2 +2116 'pf' 2 +2117 'pg' 2 +2118 'ph' 2 +2119 'pi' 2 +2120 'pk' 2 +2121 'pl' 2 +2122 'pm' 2 +2123 'pn' 2 +2124 'po' 2 +2125 'pp' 2 +2126 'pq' 2 +2127 'pr' 2 +2128 'ps' 2 +2129 'pt' 2 +2130 'pu' 2 +2131 'pv' 2 +2132 'pw' 2 +2133 'px' 2 +2134 'py' 2 +2135 'qa' 2 +2136 'qb' 2 +2137 'qc' 2 +2138 'qd' 2 +2139 'qh' 2 +2140 'qi' 2 +2141 'ql' 2 +2142 'qn' 2 +2143 'qp' 2 +2144 'qq' 2 +2145 'qr' 2 +2146 'qs' 2 +2147 'qt' 2 +2148 'qu' 2 +2149 'qv' 2 +2150 'qw' 2 +2151 'ra' 2 +2152 'rb' 2 +2153 'rc' 2 +2154 'rd' 2 +2155 're' 2 +2156 'rf' 2 +2157 'rg' 2 +2158 'rh' 2 +2159 'ri' 2 +2160 'rk' 2 +2161 'rl' 2 +2162 'rm' 2 +2163 'rn' 2 +2164 'ro' 2 +2165 'rp' 2 +2166 'rq' 2 +2167 'rr' 2 +2168 'rs' 2 +2169 'rt' 2 +2170 'ru' 2 +2171 'rv' 2 +2172 'rw' 2 +2173 'rx' 2 +2174 'ry' 2 +2175 'rz' 2 +2176 'sa' 2 +2177 'sb' 2 +2178 'sc' 2 +2179 'sd' 2 +2180 'se' 2 +2181 'sf' 2 +2182 'sg' 2 +2183 'sh' 2 +2184 'si' 2 +2185 'sj' 2 +2186 'sk' 2 +2187 'sl' 2 +2188 'sm' 2 +2189 'sn' 2 +2190 'so' 2 +2191 'sp' 2 +2192 'sq' 2 +2193 'sr' 2 +2194 'ss' 2 +2195 'st' 2 +2196 'su' 2 +2197 'sv' 2 +2198 'sw' 2 +2199 'sx' 2 +2200 'sy' 2 +2201 'sz' 2 +2202 'ta' 2 +2203 'tb' 2 +2204 'tc' 2 +2205 'td' 2 +2206 'te' 2 +2207 'tf' 2 +2208 'tg' 2 +2209 'th' 2 +2210 'ti' 2 +2211 'tk' 2 +2212 'tl' 2 +2213 'tm' 2 +2214 'tn' 2 +2215 'to' 2 +2216 'tp' 2 +2217 'tr' 2 +2218 'ts' 2 +2219 'tt' 2 +2220 'tu' 2 +2221 'tv' 2 +2222 'tw' 2 +2223 'tx' 2 +2224 'ty' 2 +2225 'tz' 2 +2226 'ua' 2 +2227 'ub' 2 +2228 'uc' 2 +2229 'ud' 2 +2230 'ue' 2 +2231 'uf' 2 +2232 'ug' 2 +2233 'uh' 2 +2234 'ui' 2 +2235 'uj' 2 +2236 'uk' 2 +2237 'ul' 2 +2238 'um' 2 +2239 'un' 2 +2240 'uo' 2 +2241 'up' 2 +2242 'ur' 2 +2243 'us' 2 +2244 'ut' 2 +2245 'uu' 2 +2246 'uv' 2 +2247 'uw' 2 +2248 'ux' 2 +2249 'uy' 2 +2250 'uz' 2 +2251 'va' 2 +2252 'vb' 2 +2253 'vc' 2 +2254 'vd' 2 +2255 've' 2 +2256 'vf' 2 +2257 'vg' 2 +2258 'vh' 2 +2259 'vi' 2 +2260 'vk' 2 +2261 'vl' 2 +2262 'vm' 2 +2263 'vn' 2 +2264 'vo' 2 +2265 'vp' 2 +2266 'vr' 2 +2267 'vs' 2 +2268 'vt' 2 +2269 'vu' 2 +2270 'vv' 2 +2271 'vw' 2 +2272 'vx' 2 +2273 'vy' 2 +2274 'wa' 2 +2275 'wb' 2 +2276 'wc' 2 +2277 'wd' 2 +2278 'we' 2 +2279 'wf' 2 +2280 'wg' 2 +2281 'wh' 2 +2282 'wi' 2 +2283 'wk' 2 +2284 'wl' 2 +2285 'wm' 2 +2286 'wn' 2 +2287 'wo' 2 +2288 'wp' 2 +2289 'wr' 2 +2290 'ws' 2 +2291 'wt' 2 +2292 'wu' 2 +2293 'ww' 2 +2294 'wx' 2 +2295 'wy' 2 +2296 'xA' 2 +2297 'xB' 2 +2298 'xC' 2 +2299 'xD' 2 +2300 'xE' 2 +2301 'xF' 2 +2302 'xa' 2 +2303 'xb' 2 +2304 'xc' 2 +2305 'xd' 2 +2306 'xe' 2 +2307 'xf' 2 +2308 'xg' 2 +2309 'xh' 2 +2310 'xi' 2 +2311 'xl' 2 +2312 'xm' 2 +2313 'xn' 2 +2314 'xo' 2 +2315 'xp' 2 +2316 'xr' 2 +2317 'xs' 2 +2318 'xt' 2 +2319 'xu' 2 +2320 'xx' 2 +2321 'xy' 2 +2322 'xz' 2 +2323 'ya' 2 +2324 'yb' 2 +2325 'yc' 2 +2326 'yd' 2 +2327 'ye' 2 +2328 'yg' 2 +2329 'yi' 2 +2330 'yk' 2 +2331 'yl' 2 +2332 'ym' 2 +2333 'yn' 2 +2334 'yo' 2 +2335 'yp' 2 +2336 'yr' 2 +2337 'ys' 2 +2338 'yt' 2 +2339 'yu' 2 +2340 'yw' 2 +2341 'yx' 2 +2342 'yy' 2 +2343 'yz' 2 +2344 'zA' 2 +2345 'za' 2 +2346 'zb' 2 +2347 'zc' 2 +2348 'zd' 2 +2349 'ze' 2 +2350 'zh' 2 +2351 'zi' 2 +2352 'zk' 2 +2353 'zl' 2 +2354 'zm' 2 +2355 'zn' 2 +2356 'zo' 2 +2357 'zr' 2 +2358 'zs' 2 +2359 'zt' 2 +2360 'zu' 2 +2361 'zw' 2 +2362 'zy' 2 +2363 'zz' 2 +2364 '{"' 2 +2365 '{$' 2 +2366 '{%' 2 +2367 "{'" 2 +2368 '{(' 2 +2369 '{-' 2 +2370 '{:' 2 +2371 '{@' 2 +2372 '{\\' 2 +2373 '{{' 2 +2374 '{|' 2 +2375 '{}' 2 +2376 '|$' 2 +2377 '|(' 2 +2378 '|-' 2 +2379 '|.' 2 +2380 '|\\' 2 +2381 '|^' 2 +2382 '||' 2 +2383 '}"' 2 +2384 '}$' 2 +2385 '}%' 2 +2386 '}&' 2 +2387 "}'" 2 +2388 '}(' 2 +2389 '})' 2 +2390 '}+' 2 +2391 '},' 2 +2392 '}-' 2 +2393 '}.' 2 +2394 '}/' 2 +2395 '}:' 2 +2396 '};' 2 +2397 '}<' 2 +2398 '}=' 2 +2399 '}>' 2 +2400 '}?' 2 +2401 '}[' 2 +2402 '}\\' 2 +2403 '}]' 2 +2404 '}_' 2 +2405 '}`' 2 +2406 '}{' 2 +2407 '}|' 2 +2408 '}}' 2 +2409 '~/' 2 +2410 '~\\' 2 +2411 '~~' 2 +2412 b'\x82\xac' 2 +2413 b'\x83\xbd' 2 +2414 b'\x86\x92' 2 +2415 b'\x88\x98' 2 +2416 b'\x8c\x80' 2 +2417 b'\x99\x82' 2 +2418 b'\x9d\xbc' 2 +2419 b'\xa3\xbc' 2 +2420 b'\xa6\x82' 2 +2421 b'\xb7\xb8' 2 +2422 b'\xbf\xbd' 2 +2423 '\x80' 2 +2424 '\x81' 2 +2425 '\x91' 2 +2426 '\x92' 2 +2427 '\x93' 2 +2428 '\x94' 2 +2429 '\x97' 2 +2430 '\xa0' 2 +2431 '¡' 2 +2432 '¢' 2 +2433 '£' 2 +2434 '¤' 2 +2435 '¥' 2 +2436 '¦' 2 +2437 '§' 2 +2438 '¨' 2 +2439 '©' 2 +2440 'ª' 2 +2441 '«' 2 +2442 '¬' 2 +2443 '\xad' 2 +2444 '®' 2 +2445 '¯' 2 +2446 '°' 2 +2447 '±' 2 +2448 '²' 2 +2449 '³' 2 +2450 '´' 2 +2451 'µ' 2 +2452 '¶' 2 +2453 '·' 2 +2454 '¸' 2 +2455 '¹' 2 +2456 'º' 2 +2457 '»' 2 +2458 '¼' 2 +2459 '½' 2 +2460 '¾' 2 +2461 '¿' 2 +2462 'À' 2 +2463 'Á' 2 +2464 'Â' 2 +2465 'Ã' 2 +2466 'Ä' 2 +2467 'Å' 2 +2468 'Æ' 2 +2469 'Ç' 2 +2470 'È' 2 +2471 'É' 2 +2472 'Ê' 2 +2473 'Ë' 2 +2474 'Ì' 2 +2475 'Í' 2 +2476 'Î' 2 +2477 'Ï' 2 +2478 'Ð' 2 +2479 'Ñ' 2 +2480 'Ò' 2 +2481 'Ó' 2 +2482 'Ô' 2 +2483 'Õ' 2 +2484 'Ö' 2 +2485 '×' 2 +2486 'Ø' 2 +2487 'Ù' 2 +2488 'Ú' 2 +2489 'Û' 2 +2490 'Ü' 2 +2491 'Ý' 2 +2492 'Þ' 2 +2493 'ß' 2 +2494 'à' 2 +2495 'á' 2 +2496 'â' 2 +2497 'ã' 2 +2498 'ä' 2 +2499 'å' 2 +2500 'æ' 2 +2501 'ç' 2 +2502 'è' 2 +2503 'é' 2 +2504 'ê' 2 +2505 'ë' 2 +2506 'ì' 2 +2507 'í' 2 +2508 'î' 2 +2509 'ï' 2 +2510 'ð' 2 +2511 'ñ' 2 +2512 'ò' 2 +2513 'ó' 2 +2514 'ô' 2 +2515 'õ' 2 +2516 'ö' 2 +2517 '÷' 2 +2518 'ø' 2 +2519 'ù' 2 +2520 'ú' 2 +2521 'û' 2 +2522 'ü' 2 +2523 'ý' 2 +2524 'þ' 2 +2525 'ÿ' 2 +2526 'Ā' 2 +2527 'ā' 2 +2528 'Ă' 2 +2529 'ă' 2 +2530 'ą' 2 +2531 'Ć' 2 +2532 'ć' 2 +2533 'ĉ' 2 +2534 'ċ' 2 +2535 'Č' 2 +2536 'č' 2 +2537 'Ď' 2 +2538 'ď' 2 +2539 'Đ' 2 +2540 'đ' 2 +2541 'Ē' 2 +2542 'ē' 2 +2543 'ĕ' 2 +2544 'Ė' 2 +2545 'ė' 2 +2546 'ę' 2 +2547 'Ě' 2 +2548 'ě' 2 +2549 'ĝ' 2 +2550 'ğ' 2 +2551 'Ġ' 2 +2552 'ġ' 2 +2553 'Ħ' 2 +2554 'ħ' 2 +2555 'ĩ' 2 +2556 'Ī' 2 +2557 'ī' 2 +2558 'ĭ' 2 +2559 'į' 2 +2560 'İ' 2 +2561 'ı' 2 +2562 'ķ' 2 +2563 'ļ' 2 +2564 'Ľ' 2 +2565 'ľ' 2 +2566 'Ł' 2 +2567 'ł' 2 +2568 'ń' 2 +2569 'ņ' 2 +2570 'ň' 2 +2571 'ŋ' 2 +2572 'Ō' 2 +2573 'ō' 2 +2574 'ŏ' 2 +2575 'Ő' 2 +2576 'ő' 2 +2577 'Œ' 2 +2578 'œ' 2 +2579 'Ř' 2 +2580 'ř' 2 +2581 'Ś' 2 +2582 'ś' 2 +2583 'ŝ' 2 +2584 'Ş' 2 +2585 'ş' 2 +2586 'Š' 2 +2587 'š' 2 +2588 'Ţ' 2 +2589 'ţ' 2 +2590 'Ť' 2 +2591 'ť' 2 +2592 'ũ' 2 +2593 'ū' 2 +2594 'ŭ' 2 +2595 'ů' 2 +2596 'Ű' 2 +2597 'ű' 2 +2598 'ų' 2 +2599 'Ÿ' 2 +2600 'Ź' 2 +2601 'ź' 2 +2602 'Ż' 2 +2603 'ż' 2 +2604 'Ž' 2 +2605 'ž' 2 +2606 'ſ' 2 +2607 'Ə' 2 +2608 'ƒ' 2 +2609 'ơ' 2 +2610 'ư' 2 +2611 'ǎ' 2 +2612 'ǐ' 2 +2613 'ǒ' 2 +2614 'ǔ' 2 +2615 'ǚ' 2 +2616 'ǧ' 2 +2617 'ǫ' 2 +2618 'Ș' 2 +2619 'ș' 2 +2620 'Ț' 2 +2621 'ț' 2 +2622 'ɐ' 2 +2623 'ɑ' 2 +2624 'ɒ' 2 +2625 'ɔ' 2 +2626 'ɕ' 2 +2627 'ə' 2 +2628 'ɛ' 2 +2629 'ɡ' 2 +2630 'ɣ' 2 +2631 'ɨ' 2 +2632 'ɪ' 2 +2633 'ɫ' 2 +2634 'ɯ' 2 +2635 'ɲ' 2 +2636 'ɵ' 2 +2637 'ɹ' 2 +2638 'ɾ' 2 +2639 'ʀ' 2 +2640 'ʁ' 2 +2641 'ʂ' 2 +2642 'ʃ' 2 +2643 'ʊ' 2 +2644 'ʋ' 2 +2645 'ʌ' 2 +2646 'ʎ' 2 +2647 'ʐ' 2 +2648 'ʑ' 2 +2649 'ʒ' 2 +2650 'ʔ' 2 +2651 'ʰ' 2 +2652 'ʲ' 2 +2653 'ʷ' 2 +2654 'ʹ' 2 +2655 'ʻ' 2 +2656 'ʼ' 2 +2657 'ʾ' 2 +2658 'ʿ' 2 +2659 'ˆ' 2 +2660 'ˇ' 2 +2661 'ˈ' 2 +2662 'ˉ' 2 +2663 'ˊ' 2 +2664 'ˋ' 2 +2665 'ˌ' 2 +2666 'ː' 2 +2667 '˙' 2 +2668 '˚' 2 +2669 '˜' 2 +2670 'ˠ' 2 +2671 '̀' 2 +2672 '́' 2 +2673 '̂' 2 +2674 '̃' 2 +2675 '̄' 2 +2676 '̈' 2 +2677 '̌' 2 +2678 '̍' 2 +2679 '̣' 2 +2680 '̥' 2 +2681 '̩' 2 +2682 '̪' 2 +2683 '̯' 2 +2684 '̱' 2 +2685 '̲' 2 +2686 '̶' 2 +2687 '͒' 2 +2688 '͓' 2 +2689 '͘' 2 +2690 '͡' 2 +2691 'Ά' 2 +2692 'Έ' 2 +2693 'Α' 2 +2694 'Β' 2 +2695 'Γ' 2 +2696 'Δ' 2 +2697 'Ε' 2 +2698 'Ζ' 2 +2699 'Η' 2 +2700 'Θ' 2 +2701 'Ι' 2 +2702 'Κ' 2 +2703 'Λ' 2 +2704 'Μ' 2 +2705 'Ν' 2 +2706 'Ξ' 2 +2707 'Ο' 2 +2708 'Π' 2 +2709 'Ρ' 2 +2710 'Σ' 2 +2711 'Τ' 2 +2712 'Υ' 2 +2713 'Φ' 2 +2714 'Χ' 2 +2715 'Ψ' 2 +2716 'Ω' 2 +2717 'ά' 2 +2718 'έ' 2 +2719 'ή' 2 +2720 'ί' 2 +2721 'α' 2 +2722 'β' 2 +2723 'γ' 2 +2724 'δ' 2 +2725 'ε' 2 +2726 'ζ' 2 +2727 'η' 2 +2728 'θ' 2 +2729 'ι' 2 +2730 'κ' 2 +2731 'λ' 2 +2732 'μ' 2 +2733 'ν' 2 +2734 'ξ' 2 +2735 'ο' 2 +2736 'π' 2 +2737 'ρ' 2 +2738 'ς' 2 +2739 'σ' 2 +2740 'τ' 2 +2741 'υ' 2 +2742 'φ' 2 +2743 'χ' 2 +2744 'ψ' 2 +2745 'ω' 2 +2746 'ϊ' 2 +2747 'ό' 2 +2748 'ύ' 2 +2749 'ώ' 2 +2750 'ϕ' 2 +2751 'ϵ' 2 +2752 'Ё' 2 +2753 'Ђ' 2 +2754 'Є' 2 +2755 'І' 2 +2756 'Ї' 2 +2757 'Ј' 2 +2758 'Љ' 2 +2759 'Њ' 2 +2760 'Ћ' 2 +2761 'Џ' 2 +2762 'А' 2 +2763 'Б' 2 +2764 'В' 2 +2765 'Г' 2 +2766 'Д' 2 +2767 'Е' 2 +2768 'Ж' 2 +2769 'З' 2 +2770 'И' 2 +2771 'Й' 2 +2772 'К' 2 +2773 'Л' 2 +2774 'М' 2 +2775 'Н' 2 +2776 'О' 2 +2777 'П' 2 +2778 'Р' 2 +2779 'С' 2 +2780 'Т' 2 +2781 'У' 2 +2782 'Ф' 2 +2783 'Х' 2 +2784 'Ц' 2 +2785 'Ч' 2 +2786 'Ш' 2 +2787 'Щ' 2 +2788 'Ъ' 2 +2789 'Ы' 2 +2790 'Ь' 2 +2791 'Э' 2 +2792 'Ю' 2 +2793 'Я' 2 +2794 'а' 2 +2795 'б' 2 +2796 'в' 2 +2797 'г' 2 +2798 'д' 2 +2799 'е' 2 +2800 'ж' 2 +2801 'з' 2 +2802 'и' 2 +2803 'й' 2 +2804 'к' 2 +2805 'л' 2 +2806 'м' 2 +2807 'н' 2 +2808 'о' 2 +2809 'п' 2 +2810 'р' 2 +2811 'с' 2 +2812 'т' 2 +2813 'у' 2 +2814 'ф' 2 +2815 'х' 2 +2816 'ц' 2 +2817 'ч' 2 +2818 'ш' 2 +2819 'щ' 2 +2820 'ъ' 2 +2821 'ы' 2 +2822 'ь' 2 +2823 'э' 2 +2824 'ю' 2 +2825 'я' 2 +2826 'ѐ' 2 +2827 'ё' 2 +2828 'ђ' 2 +2829 'є' 2 +2830 'і' 2 +2831 'ї' 2 +2832 'ј' 2 +2833 'љ' 2 +2834 'њ' 2 +2835 'ћ' 2 +2836 'ѝ' 2 +2837 'ў' 2 +2838 'џ' 2 +2839 'ѣ' 2 +2840 'ѫ' 2 +2841 'Ґ' 2 +2842 'ґ' 2 +2843 'ғ' 2 +2844 'Қ' 2 +2845 'қ' 2 +2846 'ҡ' 2 +2847 'ң' 2 +2848 'ү' 2 +2849 'ұ' 2 +2850 'ӏ' 2 +2851 'ә' 2 +2852 'ө' 2 +2853 'Ա' 2 +2854 'Հ' 2 +2855 'Մ' 2 +2856 'Ս' 2 +2857 'ա' 2 +2858 'բ' 2 +2859 'գ' 2 +2860 'դ' 2 +2861 'ե' 2 +2862 'զ' 2 +2863 'թ' 2 +2864 'ի' 2 +2865 'լ' 2 +2866 'կ' 2 +2867 'հ' 2 +2868 'ղ' 2 +2869 'մ' 2 +2870 'յ' 2 +2871 'ն' 2 +2872 'շ' 2 +2873 'ո' 2 +2874 'պ' 2 +2875 'ս' 2 +2876 'վ' 2 +2877 'տ' 2 +2878 'ր' 2 +2879 'ց' 2 +2880 'ւ' 2 +2881 'ք' 2 +2882 'ְ' 2 +2883 'ִ' 2 +2884 'ֵ' 2 +2885 'ֶ' 2 +2886 'ַ' 2 +2887 'ָ' 2 +2888 'ֹ' 2 +2889 'ּ' 2 +2890 'ׁ' 2 +2891 'א' 2 +2892 'ב' 2 +2893 'ג' 2 +2894 'ד' 2 +2895 'ה' 2 +2896 'ו' 2 +2897 'ז' 2 +2898 'ח' 2 +2899 'ט' 2 +2900 'י' 2 +2901 'ך' 2 +2902 'כ' 2 +2903 'ל' 2 +2904 'ם' 2 +2905 'מ' 2 +2906 'ן' 2 +2907 'נ' 2 +2908 'ס' 2 +2909 'ע' 2 +2910 'ף' 2 +2911 'פ' 2 +2912 'ץ' 2 +2913 'צ' 2 +2914 'ק' 2 +2915 'ר' 2 +2916 'ש' 2 +2917 'ת' 2 +2918 '،' 2 +2919 'ء' 2 +2920 'آ' 2 +2921 'أ' 2 +2922 'إ' 2 +2923 'ئ' 2 +2924 'ا' 2 +2925 'ب' 2 +2926 'ة' 2 +2927 'ت' 2 +2928 'ث' 2 +2929 'ج' 2 +2930 'ح' 2 +2931 'خ' 2 +2932 'د' 2 +2933 'ذ' 2 +2934 'ر' 2 +2935 'ز' 2 +2936 'س' 2 +2937 'ش' 2 +2938 'ص' 2 +2939 'ض' 2 +2940 'ط' 2 +2941 'ظ' 2 +2942 'ع' 2 +2943 'غ' 2 +2944 'ـ' 2 +2945 'ف' 2 +2946 'ق' 2 +2947 'ك' 2 +2948 'ل' 2 +2949 'م' 2 +2950 'ن' 2 +2951 'ه' 2 +2952 'و' 2 +2953 'ى' 2 +2954 'ي' 2 +2955 'ً' 2 +2956 'َ' 2 +2957 'ُ' 2 +2958 'ِ' 2 +2959 'ّ' 2 +2960 'ْ' 2 +2961 'پ' 2 +2962 'چ' 2 +2963 'ک' 2 +2964 'گ' 2 +2965 'ھ' 2 +2966 'ہ' 2 +2967 'ی' 2 +2968 'ے' 2 +2969 'ە' 2 +2970 'ܐ' 2 +2971 'ܝ' 2 +2972 '߬' 2 +2973 b'\xe0\xa4' 2 +2974 b'\xe0\xa5' 2 +2975 b'\xe0\xa6' 2 +2976 b'\xe0\xa7' 2 +2977 b'\xe0\xa8' 2 +2978 b'\xe0\xa9' 2 +2979 b'\xe0\xaa' 2 +2980 b'\xe0\xab' 2 +2981 b'\xe0\xac' 2 +2982 b'\xe0\xae' 2 +2983 b'\xe0\xaf' 2 +2984 b'\xe0\xb0' 2 +2985 b'\xe0\xb1' 2 +2986 b'\xe0\xb2' 2 +2987 b'\xe0\xb3' 2 +2988 b'\xe0\xb4' 2 +2989 b'\xe0\xb5' 2 +2990 b'\xe0\xb6' 2 +2991 b'\xe0\xb7' 2 +2992 b'\xe0\xb8' 2 +2993 b'\xe0\xb9' 2 +2994 b'\xe0\xba' 2 +2995 b'\xe0\xbc' 2 +2996 b'\xe0\xbd' 2 +2997 b'\xe1\x80' 2 +2998 b'\xe1\x83' 2 +2999 b'\xe1\x9e' 2 +3000 b'\xe1\x9f' 2 +3001 b'\xe1\xb8' 2 +3002 b'\xe1\xb9' 2 +3003 b'\xe1\xba' 2 +3004 b'\xe1\xbb' 2 +3005 b'\xe1\xbd' 2 +3006 b'\xe2\x80' 2 +3007 b'\xe2\x81' 2 +3008 b'\xe2\x82' 2 +3009 b'\xe2\x84' 2 +3010 b'\xe2\x86' 2 +3011 b'\xe2\x88' 2 +3012 b'\xe2\x89' 2 +3013 b'\xe2\x94' 2 +3014 b'\xe2\x95' 2 +3015 b'\xe2\x96' 2 +3016 b'\xe2\x97' 2 +3017 b'\xe2\x98' 2 +3018 b'\xe2\x99' 2 +3019 b'\xe2\x9c' 2 +3020 b'\xe2\x9d' 2 +3021 b'\xe3\x80' 2 +3022 b'\xe3\x81' 2 +3023 b'\xe3\x82' 2 +3024 b'\xe3\x83' 2 +3025 b'\xe4\xb8' 2 +3026 b'\xe4\xb9' 2 +3027 b'\xe4\xba' 2 +3028 b'\xe4\xbb' 2 +3029 b'\xe4\xbc' 2 +3030 b'\xe4\xbd' 2 +3031 b'\xe4\xbe' 2 +3032 b'\xe4\xbf' 2 +3033 b'\xe5\x80' 2 +3034 b'\xe5\x81' 2 +3035 b'\xe5\x82' 2 +3036 b'\xe5\x83' 2 +3037 b'\xe5\x84' 2 +3038 b'\xe5\x85' 2 +3039 b'\xe5\x86' 2 +3040 b'\xe5\x87' 2 +3041 b'\xe5\x88' 2 +3042 b'\xe5\x89' 2 +3043 b'\xe5\x8a' 2 +3044 b'\xe5\x8b' 2 +3045 b'\xe5\x8c' 2 +3046 b'\xe5\x8d' 2 +3047 b'\xe5\x8e' 2 +3048 b'\xe5\x8f' 2 +3049 b'\xe5\x90' 2 +3050 b'\xe5\x91' 2 +3051 b'\xe5\x92' 2 +3052 b'\xe5\x93' 2 +3053 b'\xe5\x94' 2 +3054 b'\xe5\x95' 2 +3055 b'\xe5\x96' 2 +3056 b'\xe5\x99' 2 +3057 b'\xe5\x9b' 2 +3058 b'\xe5\x9c' 2 +3059 b'\xe5\x9d' 2 +3060 b'\xe5\x9e' 2 +3061 b'\xe5\x9f' 2 +3062 b'\xe5\xa0' 2 +3063 b'\xe5\xa1' 2 +3064 b'\xe5\xa2' 2 +3065 b'\xe5\xa3' 2 +3066 b'\xe5\xa4' 2 +3067 b'\xe5\xa5' 2 +3068 b'\xe5\xa6' 2 +3069 b'\xe5\xa7' 2 +3070 b'\xe5\xad' 2 +3071 b'\xe5\xae' 2 +3072 b'\xe5\xaf' 2 +3073 b'\xe5\xb0' 2 +3074 b'\xe5\xb1' 2 +3075 b'\xe5\xb2' 2 +3076 b'\xe5\xb7' 2 +3077 b'\xe5\xb8' 2 +3078 b'\xe5\xb9' 2 +3079 b'\xe5\xba' 2 +3080 b'\xe5\xbb' 2 +3081 b'\xe5\xbc' 2 +3082 b'\xe5\xbd' 2 +3083 b'\xe5\xbe' 2 +3084 b'\xe5\xbf' 2 +3085 b'\xe6\x80' 2 +3086 b'\xe6\x81' 2 +3087 b'\xe6\x82' 2 +3088 b'\xe6\x83' 2 +3089 b'\xe6\x84' 2 +3090 b'\xe6\x85' 2 +3091 b'\xe6\x88' 2 +3092 b'\xe6\x89' 2 +3093 b'\xe6\x8a' 2 +3094 b'\xe6\x8b' 2 +3095 b'\xe6\x8c' 2 +3096 b'\xe6\x8d' 2 +3097 b'\xe6\x8e' 2 +3098 b'\xe6\x8f' 2 +3099 b'\xe6\x91' 2 +3100 b'\xe6\x92' 2 +3101 b'\xe6\x93' 2 +3102 b'\xe6\x94' 2 +3103 b'\xe6\x95' 2 +3104 b'\xe6\x96' 2 +3105 b'\xe6\x97' 2 +3106 b'\xe6\x98' 2 +3107 b'\xe6\x99' 2 +3108 b'\xe6\x9a' 2 +3109 b'\xe6\x9b' 2 +3110 b'\xe6\x9c' 2 +3111 b'\xe6\x9d' 2 +3112 b'\xe6\x9e' 2 +3113 b'\xe6\x9f' 2 +3114 b'\xe6\xa0' 2 +3115 b'\xe6\xa1' 2 +3116 b'\xe6\xa2' 2 +3117 b'\xe6\xa3' 2 +3118 b'\xe6\xa5' 2 +3119 b'\xe6\xa7' 2 +3120 b'\xe6\xa8' 2 +3121 b'\xe6\xa9' 2 +3122 b'\xe6\xac' 2 +3123 b'\xe6\xad' 2 +3124 b'\xe6\xae' 2 +3125 b'\xe6\xaf' 2 +3126 b'\xe6\xb0' 2 +3127 b'\xe6\xb1' 2 +3128 b'\xe6\xb2' 2 +3129 b'\xe6\xb3' 2 +3130 b'\xe6\xb4' 2 +3131 b'\xe6\xb5' 2 +3132 b'\xe6\xb6' 2 +3133 b'\xe6\xb7' 2 +3134 b'\xe6\xb8' 2 +3135 b'\xe6\xb9' 2 +3136 b'\xe6\xba' 2 +3137 b'\xe6\xbb' 2 +3138 b'\xe6\xbc' 2 +3139 b'\xe7\x81' 2 +3140 b'\xe7\x82' 2 +3141 b'\xe7\x84' 2 +3142 b'\xe7\x88' 2 +3143 b'\xe7\x89' 2 +3144 b'\xe7\x8a' 2 +3145 b'\xe7\x8e' 2 +3146 b'\xe7\x8f' 2 +3147 b'\xe7\x90' 2 +3148 b'\xe7\x94' 2 +3149 b'\xe7\x95' 2 +3150 b'\xe7\x97' 2 +3151 b'\xe7\x99' 2 +3152 b'\xe7\x9a' 2 +3153 b'\xe7\x9b' 2 +3154 b'\xe7\x9c' 2 +3155 b'\xe7\x9d' 2 +3156 b'\xe7\x9f' 2 +3157 b'\xe7\xa0' 2 +3158 b'\xe7\xa1' 2 +3159 b'\xe7\xa2' 2 +3160 b'\xe7\xa4' 2 +3161 b'\xe7\xa5' 2 +3162 b'\xe7\xa6' 2 +3163 b'\xe7\xa7' 2 +3164 b'\xe7\xa8' 2 +3165 b'\xe7\xa9' 2 +3166 b'\xe7\xaa' 2 +3167 b'\xe7\xab' 2 +3168 b'\xe7\xac' 2 +3169 b'\xe7\xad' 2 +3170 b'\xe7\xae' 2 +3171 b'\xe7\xaf' 2 +3172 b'\xe7\xb1' 2 +3173 b'\xe7\xb2' 2 +3174 b'\xe7\xb3' 2 +3175 b'\xe7\xb4' 2 +3176 b'\xe7\xb5' 2 +3177 b'\xe7\xb6' 2 +3178 b'\xe7\xb7' 2 +3179 b'\xe7\xba' 2 +3180 b'\xe7\xbb' 2 +3181 b'\xe7\xbc' 2 +3182 b'\xe7\xbd' 2 +3183 b'\xe7\xbe' 2 +3184 b'\xe7\xbf' 2 +3185 b'\xe8\x80' 2 +3186 b'\xe8\x81' 2 +3187 b'\xe8\x82' 2 +3188 b'\xe8\x83' 2 +3189 b'\xe8\x84' 2 +3190 b'\xe8\x87' 2 +3191 b'\xe8\x88' 2 +3192 b'\xe8\x89' 2 +3193 b'\xe8\x8a' 2 +3194 b'\xe8\x8b' 2 +3195 b'\xe8\x8c' 2 +3196 b'\xe8\x8d' 2 +3197 b'\xe8\x8e' 2 +3198 b'\xe8\x90' 2 +3199 b'\xe8\x99' 2 +3200 b'\xe8\xa1' 2 +3201 b'\xe8\xa2' 2 +3202 b'\xe8\xa3' 2 +3203 b'\xe8\xa6' 2 +3204 b'\xe8\xa7' 2 +3205 b'\xe8\xa8' 2 +3206 b'\xe8\xa9' 2 +3207 b'\xe8\xaa' 2 +3208 b'\xe8\xab' 2 +3209 b'\xe8\xad' 2 +3210 b'\xe8\xae' 2 +3211 b'\xe8\xaf' 2 +3212 b'\xe8\xb0' 2 +3213 b'\xe8\xb1' 2 +3214 b'\xe8\xb2' 2 +3215 b'\xe8\xb3' 2 +3216 b'\xe8\xb4' 2 +3217 b'\xe8\xb5' 2 +3218 b'\xe8\xb6' 2 +3219 b'\xe8\xb7' 2 +3220 b'\xe8\xba' 2 +3221 b'\xe8\xbb' 2 +3222 b'\xe8\xbc' 2 +3223 b'\xe8\xbd' 2 +3224 b'\xe8\xbe' 2 +3225 b'\xe8\xbf' 2 +3226 b'\xe9\x80' 2 +3227 b'\xe9\x81' 2 +3228 b'\xe9\x82' 2 +3229 b'\xe9\x83' 2 +3230 b'\xe9\x85' 2 +3231 b'\xe9\x87' 2 +3232 b'\xe9\x8c' 2 +3233 b'\xe9\x92' 2 +3234 b'\xe9\x93' 2 +3235 b'\xe9\x94' 2 +3236 b'\xe9\x95' 2 +3237 b'\xe9\x96' 2 +3238 b'\xe9\x97' 2 +3239 b'\xe9\x98' 2 +3240 b'\xe9\x99' 2 +3241 b'\xe9\x9a' 2 +3242 b'\xe9\x9b' 2 +3243 b'\xe9\x9c' 2 +3244 b'\xe9\x9d' 2 +3245 b'\xe9\x9f' 2 +3246 b'\xe9\xa0' 2 +3247 b'\xe9\xa1' 2 +3248 b'\xe9\xa2' 2 +3249 b'\xe9\xa3' 2 +3250 b'\xe9\xa6' 2 +3251 b'\xe9\xa9' 2 +3252 b'\xe9\xaa' 2 +3253 b'\xe9\xab' 2 +3254 b'\xe9\xbb' 2 +3255 b'\xe9\xbe' 2 +3256 b'\xea\xb0' 2 +3257 b'\xea\xb1' 2 +3258 b'\xea\xb2' 2 +3259 b'\xea\xb3' 2 +3260 b'\xea\xb5' 2 +3261 b'\xea\xb7' 2 +3262 b'\xea\xb8' 2 +3263 b'\xea\xb9' 2 +3264 b'\xeb\x82' 2 +3265 b'\xeb\x84' 2 +3266 b'\xeb\x85' 2 +3267 b'\xeb\x8a' 2 +3268 b'\xeb\x8b' 2 +3269 b'\xeb\x8d' 2 +3270 b'\xeb\x8f' 2 +3271 b'\xeb\x90' 2 +3272 b'\xeb\x93' 2 +3273 b'\xeb\x9e' 2 +3274 b'\xeb\x9f' 2 +3275 b'\xeb\xa0' 2 +3276 b'\xeb\xa1' 2 +3277 b'\xeb\xa3' 2 +3278 b'\xeb\xa5' 2 +3279 b'\xeb\xa6' 2 +3280 b'\xeb\xa7' 2 +3281 b'\xeb\xa9' 2 +3282 b'\xeb\xaa' 2 +3283 b'\xeb\xb0' 2 +3284 b'\xeb\xb2' 2 +3285 b'\xeb\xb3' 2 +3286 b'\xeb\xb6' 2 +3287 b'\xec\x83' 2 +3288 b'\xec\x84' 2 +3289 b'\xec\x85' 2 +3290 b'\xec\x86' 2 +3291 b'\xec\x8a' 2 +3292 b'\xec\x8b' 2 +3293 b'\xec\x95' 2 +3294 b'\xec\x96' 2 +3295 b'\xec\x97' 2 +3296 b'\xec\x98' 2 +3297 b'\xec\x99' 2 +3298 b'\xec\x9a' 2 +3299 b'\xec\x9b' 2 +3300 b'\xec\x9c' 2 +3301 b'\xec\x9d' 2 +3302 b'\xec\x9e' 2 +3303 b'\xec\xa0' 2 +3304 b'\xec\xa7' 2 +3305 b'\xec\xb0' 2 +3306 b'\xec\xb2' 2 +3307 b'\xec\xb9' 2 +3308 b'\xed\x83' 2 +3309 b'\xed\x8a' 2 +3310 b'\xed\x8c' 2 +3311 b'\xed\x95' 2 +3312 b'\xed\x98' 2 +3313 b'\xed\x99' 2 +3314 b'\xef\xb8' 2 +3315 b'\xef\xbc' 2 +3316 b'\xef\xbd' 2 +3317 b'\xef\xbf' 2 +3318 b'\xf0\x9d' 2 +3319 b'\xf0\x9f' 2 +3320 '\t\t\t' 3 +3321 '\t\t\n' 3 +3322 '\t\t ' 3 +3323 '\t ' 3 +3324 '\n\t\t' 3 +3325 '\n\t\n' 3 +3326 '\n\t ' 3 +3327 '\n\n\t' 3 +3328 '\n\n\n' 3 +3329 '\n\n ' 3 +3330 '\n \n' 3 +3331 '\n ' 3 +3332 '\r\n\t' 3 +3333 '\r\n ' 3 +3334 ' \t\t' 3 +3335 ' \n\t' 3 +3336 ' \n\n' 3 +3337 ' \n ' 3 +3338 ' \r\n' 3 +3339 ' \n' 3 +3340 ' ' 3 +3341 ' !!' 3 +3342 ' !(' 3 +3343 ' !=' 3 +3344 ' ""' 3 +3345 ' "#' 3 +3346 ' "$' 3 +3347 ' "%' 3 +3348 ' "&' 3 +3349 ' "\'' 3 +3350 ' "(' 3 +3351 ' ")' 3 +3352 ' "*' 3 +3353 ' "+' 3 +3354 ' ",' 3 +3355 ' "-' 3 +3356 ' ".' 3 +3357 ' "/' 3 +3358 ' ":' 3 +3359 ' ";' 3 +3360 ' "<' 3 +3361 ' ">' 3 +3362 ' "@' 3 +3363 ' "[' 3 +3364 ' "\\' 3 +3365 ' "]' 3 +3366 ' "^' 3 +3367 ' "_' 3 +3368 ' "`' 3 +3369 ' "{' 3 +3370 ' "~' 3 +3371 ' #"' 3 +3372 ' ##' 3 +3373 ' #(' 3 +3374 ' #:' 3 +3375 ' #[' 3 +3376 ' #{' 3 +3377 ' $$' 3 +3378 ' $(' 3 +3379 ' $,' 3 +3380 ' $.' 3 +3381 ' $\\' 3 +3382 ' $_' 3 +3383 ' ${' 3 +3384 ' %%' 3 +3385 ' %.' 3 +3386 ' %>' 3 +3387 ' %{' 3 +3388 ' %}' 3 +3389 ' &#' 3 +3390 ' &$' 3 +3391 ' &&' 3 +3392 ' &=' 3 +3393 ' \'"' 3 +3394 " '#" 3 +3395 " '$" 3 +3396 " '%" 3 +3397 " '&" 3 +3398 " ''" 3 +3399 " ')" 3 +3400 " '*" 3 +3401 " '+" 3 +3402 " '," 3 +3403 " '-" 3 +3404 " '." 3 +3405 " '/" 3 +3406 " ':" 3 +3407 " ';" 3 +3408 " '<" 3 +3409 " '@" 3 +3410 " '[" 3 +3411 " '\\" 3 +3412 " '_" 3 +3413 " '{" 3 +3414 ' (!' 3 +3415 ' ("' 3 +3416 ' (#' 3 +3417 ' ($' 3 +3418 ' (%' 3 +3419 ' (&' 3 +3420 " ('" 3 +3421 ' ((' 3 +3422 ' ()' 3 +3423 ' (*' 3 +3424 ' (+' 3 +3425 ' (-' 3 +3426 ' (.' 3 +3427 ' (/' 3 +3428 ' (:' 3 +3429 ' (;' 3 +3430 ' (<' 3 +3431 ' (=' 3 +3432 ' (>' 3 +3433 ' (?' 3 +3434 ' (@' 3 +3435 ' ([' 3 +3436 ' (\\' 3 +3437 ' (_' 3 +3438 ' (`' 3 +3439 ' ({' 3 +3440 ' ))' 3 +3441 ' ),' 3 +3442 ' ).' 3 +3443 ' ):' 3 +3444 ' );' 3 +3445 ' ){' 3 +3446 ' *(' 3 +3447 ' *)' 3 +3448 ' **' 3 +3449 ' *,' 3 +3450 ' *.' 3 +3451 ' */' 3 +3452 ' *=' 3 +3453 ' *[' 3 +3454 ' +"' 3 +3455 ' ++' 3 +3456 ' +=' 3 +3457 ' +\\' 3 +3458 ' ,"' 3 +3459 ' -(' 3 +3460 ' --' 3 +3461 ' -.' 3 +3462 ' -=' 3 +3463 ' ->' 3 +3464 ' ."' 3 +3465 ' ..' 3 +3466 ' ./' 3 +3467 ' .=' 3 +3468 ' /*' 3 +3469 ' //' 3 +3470 ' /=' 3 +3471 ' />' 3 +3472 ' /\\' 3 +3473 ' 00' 3 +3474 ' 01' 3 +3475 ' 02' 3 +3476 ' 03' 3 +3477 ' 04' 3 +3478 ' 05' 3 +3479 ' 06' 3 +3480 ' 07' 3 +3481 ' 08' 3 +3482 ' 09' 3 +3483 ' 10' 3 +3484 ' 11' 3 +3485 ' 12' 3 +3486 ' 13' 3 +3487 ' 14' 3 +3488 ' 15' 3 +3489 ' 16' 3 +3490 ' 17' 3 +3491 ' 18' 3 +3492 ' 19' 3 +3493 ' 20' 3 +3494 ' 21' 3 +3495 ' 22' 3 +3496 ' 23' 3 +3497 ' 24' 3 +3498 ' 25' 3 +3499 ' 26' 3 +3500 ' 27' 3 +3501 ' 28' 3 +3502 ' 29' 3 +3503 ' 30' 3 +3504 ' 31' 3 +3505 ' 32' 3 +3506 ' 33' 3 +3507 ' 34' 3 +3508 ' 35' 3 +3509 ' 36' 3 +3510 ' 37' 3 +3511 ' 38' 3 +3512 ' 39' 3 +3513 ' 40' 3 +3514 ' 41' 3 +3515 ' 42' 3 +3516 ' 43' 3 +3517 ' 44' 3 +3518 ' 45' 3 +3519 ' 46' 3 +3520 ' 47' 3 +3521 ' 48' 3 +3522 ' 49' 3 +3523 ' 50' 3 +3524 ' 51' 3 +3525 ' 52' 3 +3526 ' 53' 3 +3527 ' 54' 3 +3528 ' 55' 3 +3529 ' 56' 3 +3530 ' 57' 3 +3531 ' 58' 3 +3532 ' 59' 3 +3533 ' 60' 3 +3534 ' 61' 3 +3535 ' 62' 3 +3536 ' 63' 3 +3537 ' 64' 3 +3538 ' 65' 3 +3539 ' 66' 3 +3540 ' 67' 3 +3541 ' 68' 3 +3542 ' 69' 3 +3543 ' 70' 3 +3544 ' 71' 3 +3545 ' 72' 3 +3546 ' 73' 3 +3547 ' 74' 3 +3548 ' 75' 3 +3549 ' 76' 3 +3550 ' 77' 3 +3551 ' 78' 3 +3552 ' 79' 3 +3553 ' 80' 3 +3554 ' 81' 3 +3555 ' 82' 3 +3556 ' 83' 3 +3557 ' 84' 3 +3558 ' 85' 3 +3559 ' 86' 3 +3560 ' 87' 3 +3561 ' 88' 3 +3562 ' 89' 3 +3563 ' 90' 3 +3564 ' 91' 3 +3565 ' 92' 3 +3566 ' 93' 3 +3567 ' 94' 3 +3568 ' 95' 3 +3569 ' 96' 3 +3570 ' 97' 3 +3571 ' 98' 3 +3572 ' 99' 3 +3573 ' :"' 3 +3574 ' :(' 3 +3575 ' :)' 3 +3576 ' :-' 3 +3577 ' ::' 3 +3578 ' :=' 3 +3579 ' ;)' 3 +3580 ' ;;' 3 +3581 ' ' 3 +3588 ' ' 3 +3592 ' =\\' 3 +3593 ' =~' 3 +3594 ' >=' 3 +3595 ' >>' 3 +3596 ' ?,' 3 +3597 ' ?>' 3 +3598 ' ??' 3 +3599 ' @"' 3 +3600 ' @@' 3 +3601 ' AA' 3 +3602 ' AB' 3 +3603 ' AC' 3 +3604 ' AD' 3 +3605 ' AE' 3 +3606 ' AF' 3 +3607 ' AG' 3 +3608 ' AH' 3 +3609 ' AI' 3 +3610 ' AJ' 3 +3611 ' AK' 3 +3612 ' AL' 3 +3613 ' AM' 3 +3614 ' AN' 3 +3615 ' AO' 3 +3616 ' AP' 3 +3617 ' AQ' 3 +3618 ' AR' 3 +3619 ' AS' 3 +3620 ' AT' 3 +3621 ' AU' 3 +3622 ' AV' 3 +3623 ' AW' 3 +3624 ' AX' 3 +3625 ' AZ' 3 +3626 ' Ab' 3 +3627 ' Ac' 3 +3628 ' Ad' 3 +3629 ' Af' 3 +3630 ' Ag' 3 +3631 ' Ah' 3 +3632 ' Ai' 3 +3633 ' Aj' 3 +3634 ' Ak' 3 +3635 ' Al' 3 +3636 ' Am' 3 +3637 ' An' 3 +3638 ' Ao' 3 +3639 ' Ap' 3 +3640 ' Ar' 3 +3641 ' As' 3 +3642 ' At' 3 +3643 ' Au' 3 +3644 ' Av' 3 +3645 ' Aw' 3 +3646 ' Ax' 3 +3647 ' Ay' 3 +3648 ' Az' 3 +3649 ' BA' 3 +3650 ' BB' 3 +3651 ' BC' 3 +3652 ' BD' 3 +3653 ' BE' 3 +3654 ' BF' 3 +3655 ' BG' 3 +3656 ' BH' 3 +3657 ' BI' 3 +3658 ' BJ' 3 +3659 ' BL' 3 +3660 ' BM' 3 +3661 ' BN' 3 +3662 ' BO' 3 +3663 ' BP' 3 +3664 ' BR' 3 +3665 ' BS' 3 +3666 ' BT' 3 +3667 ' BU' 3 +3668 ' BV' 3 +3669 ' BW' 3 +3670 ' BY' 3 +3671 ' Ba' 3 +3672 ' Bd' 3 +3673 ' Be' 3 +3674 ' Bh' 3 +3675 ' Bi' 3 +3676 ' Bj' 3 +3677 ' Bl' 3 +3678 ' Bo' 3 +3679 ' Br' 3 +3680 ' Bu' 3 +3681 ' By' 3 +3682 ' CA' 3 +3683 ' CB' 3 +3684 ' CC' 3 +3685 ' CD' 3 +3686 ' CE' 3 +3687 ' CF' 3 +3688 ' CG' 3 +3689 ' CH' 3 +3690 ' CI' 3 +3691 ' CJ' 3 +3692 ' CK' 3 +3693 ' CL' 3 +3694 ' CM' 3 +3695 ' CN' 3 +3696 ' CO' 3 +3697 ' CP' 3 +3698 ' CR' 3 +3699 ' CS' 3 +3700 ' CT' 3 +3701 ' CU' 3 +3702 ' CV' 3 +3703 ' CW' 3 +3704 ' CX' 3 +3705 ' CY' 3 +3706 ' Ca' 3 +3707 ' Cd' 3 +3708 ' Ce' 3 +3709 ' Cf' 3 +3710 ' Ch' 3 +3711 ' Ci' 3 +3712 ' Cl' 3 +3713 ' Co' 3 +3714 ' Cp' 3 +3715 ' Cr' 3 +3716 ' Cs' 3 +3717 ' Ct' 3 +3718 ' Cu' 3 +3719 ' Cy' 3 +3720 ' Cz' 3 +3721 ' DA' 3 +3722 ' DB' 3 +3723 ' DC' 3 +3724 ' DD' 3 +3725 ' DE' 3 +3726 ' DF' 3 +3727 ' DG' 3 +3728 ' DH' 3 +3729 ' DI' 3 +3730 ' DJ' 3 +3731 ' DK' 3 +3732 ' DL' 3 +3733 ' DM' 3 +3734 ' DN' 3 +3735 ' DO' 3 +3736 ' DP' 3 +3737 ' DR' 3 +3738 ' DS' 3 +3739 ' DT' 3 +3740 ' DU' 3 +3741 ' DV' 3 +3742 ' DW' 3 +3743 ' DX' 3 +3744 ' Da' 3 +3745 ' Db' 3 +3746 ' De' 3 +3747 ' Dh' 3 +3748 ' Di' 3 +3749 ' Dj' 3 +3750 ' Do' 3 +3751 ' Dr' 3 +3752 ' Du' 3 +3753 ' Dw' 3 +3754 ' Dy' 3 +3755 ' EA' 3 +3756 ' EB' 3 +3757 ' EC' 3 +3758 ' ED' 3 +3759 ' EE' 3 +3760 ' EF' 3 +3761 ' EG' 3 +3762 ' EH' 3 +3763 ' EL' 3 +3764 ' EM' 3 +3765 ' EN' 3 +3766 ' EO' 3 +3767 ' EP' 3 +3768 ' EQ' 3 +3769 ' ER' 3 +3770 ' ES' 3 +3771 ' ET' 3 +3772 ' EU' 3 +3773 ' EV' 3 +3774 ' EW' 3 +3775 ' EX' 3 +3776 ' Eb' 3 +3777 ' Ec' 3 +3778 ' Ed' 3 +3779 ' Eg' 3 +3780 ' Eh' 3 +3781 ' Ej' 3 +3782 ' Ek' 3 +3783 ' El' 3 +3784 ' Em' 3 +3785 ' En' 3 +3786 ' Ep' 3 +3787 ' Eq' 3 +3788 ' Er' 3 +3789 ' Es' 3 +3790 ' Et' 3 +3791 ' Eu' 3 +3792 ' Ev' 3 +3793 ' Ex' 3 +3794 ' Ey' 3 +3795 ' Ez' 3 +3796 ' FA' 3 +3797 ' FB' 3 +3798 ' FC' 3 +3799 ' FD' 3 +3800 ' FE' 3 +3801 ' FF' 3 +3802 ' FG' 3 +3803 ' FH' 3 +3804 ' FI' 3 +3805 ' FK' 3 +3806 ' FL' 3 +3807 ' FM' 3 +3808 ' FN' 3 +3809 ' FO' 3 +3810 ' FP' 3 +3811 ' FR' 3 +3812 ' FS' 3 +3813 ' FT' 3 +3814 ' FW' 3 +3815 ' FX' 3 +3816 ' FY' 3 +3817 ' Fa' 3 +3818 ' Fe' 3 +3819 ' Fi' 3 +3820 ' Fl' 3 +3821 ' Fo' 3 +3822 ' Fr' 3 +3823 ' Ft' 3 +3824 ' Fu' 3 +3825 ' GA' 3 +3826 ' GB' 3 +3827 ' GC' 3 +3828 ' GD' 3 +3829 ' GE' 3 +3830 ' GF' 3 +3831 ' GG' 3 +3832 ' GH' 3 +3833 ' GI' 3 +3834 ' GL' 3 +3835 ' GM' 3 +3836 ' GN' 3 +3837 ' GO' 3 +3838 ' GP' 3 +3839 ' GR' 3 +3840 ' GS' 3 +3841 ' GT' 3 +3842 ' GU' 3 +3843 ' GV' 3 +3844 ' GW' 3 +3845 ' Ga' 3 +3846 ' Ge' 3 +3847 ' Gh' 3 +3848 ' Gi' 3 +3849 ' Gl' 3 +3850 ' Gn' 3 +3851 ' Go' 3 +3852 ' Gr' 3 +3853 ' Gu' 3 +3854 ' Gy' 3 +3855 ' HA' 3 +3856 ' HB' 3 +3857 ' HC' 3 +3858 ' HD' 3 +3859 ' HE' 3 +3860 ' HF' 3 +3861 ' HG' 3 +3862 ' HH' 3 +3863 ' HI' 3 +3864 ' HK' 3 +3865 ' HL' 3 +3866 ' HM' 3 +3867 ' HO' 3 +3868 ' HP' 3 +3869 ' HQ' 3 +3870 ' HR' 3 +3871 ' HS' 3 +3872 ' HT' 3 +3873 ' HU' 3 +3874 ' HV' 3 +3875 ' HW' 3 +3876 ' HY' 3 +3877 ' Ha' 3 +3878 ' He' 3 +3879 ' Hg' 3 +3880 ' Hi' 3 +3881 ' Ho' 3 +3882 ' Hu' 3 +3883 ' Hy' 3 +3884 ' Hz' 3 +3885 ' IA' 3 +3886 ' IB' 3 +3887 ' IC' 3 +3888 ' ID' 3 +3889 ' IE' 3 +3890 ' IF' 3 +3891 ' IG' 3 +3892 ' II' 3 +3893 ' IK' 3 +3894 ' IL' 3 +3895 ' IM' 3 +3896 ' IN' 3 +3897 ' IO' 3 +3898 ' IP' 3 +3899 ' IQ' 3 +3900 ' IR' 3 +3901 ' IS' 3 +3902 ' IT' 3 +3903 ' IU' 3 +3904 ' IV' 3 +3905 ' IX' 3 +3906 ' Ib' 3 +3907 ' Id' 3 +3908 ' If' 3 +3909 ' Ig' 3 +3910 ' Ik' 3 +3911 ' Il' 3 +3912 ' Im' 3 +3913 ' In' 3 +3914 ' Io' 3 +3915 ' Ip' 3 +3916 ' Ir' 3 +3917 ' Is' 3 +3918 ' It' 3 +3919 ' Iv' 3 +3920 ' Iz' 3 +3921 ' JA' 3 +3922 ' JC' 3 +3923 ' JD' 3 +3924 ' JE' 3 +3925 ' JJ' 3 +3926 ' JM' 3 +3927 ' JO' 3 +3928 ' JP' 3 +3929 ' JR' 3 +3930 ' JS' 3 +3931 ' JU' 3 +3932 ' Ja' 3 +3933 ' Je' 3 +3934 ' Ji' 3 +3935 ' Jo' 3 +3936 ' Jr' 3 +3937 ' Ju' 3 +3938 ' KA' 3 +3939 ' KB' 3 +3940 ' KC' 3 +3941 ' KD' 3 +3942 ' KE' 3 +3943 ' KG' 3 +3944 ' KH' 3 +3945 ' KK' 3 +3946 ' KL' 3 +3947 ' KM' 3 +3948 ' KN' 3 +3949 ' KO' 3 +3950 ' KP' 3 +3951 ' KR' 3 +3952 ' KS' 3 +3953 ' KT' 3 +3954 ' KY' 3 +3955 ' Ka' 3 +3956 ' Ke' 3 +3957 ' Kh' 3 +3958 ' Ki' 3 +3959 ' Kl' 3 +3960 ' Kn' 3 +3961 ' Ko' 3 +3962 ' Kr' 3 +3963 ' Ku' 3 +3964 ' Kw' 3 +3965 ' Ky' 3 +3966 ' LA' 3 +3967 ' LB' 3 +3968 ' LC' 3 +3969 ' LD' 3 +3970 ' LE' 3 +3971 ' LF' 3 +3972 ' LG' 3 +3973 ' LH' 3 +3974 ' LI' 3 +3975 ' LL' 3 +3976 ' LM' 3 +3977 ' LN' 3 +3978 ' LO' 3 +3979 ' LP' 3 +3980 ' LR' 3 +3981 ' LS' 3 +3982 ' LT' 3 +3983 ' LU' 3 +3984 ' LV' 3 +3985 ' LW' 3 +3986 ' LX' 3 +3987 ' La' 3 +3988 ' Le' 3 +3989 ' Li' 3 +3990 ' Ll' 3 +3991 ' Lo' 3 +3992 ' Lt' 3 +3993 ' Lu' 3 +3994 ' Lv' 3 +3995 ' Ly' 3 +3996 ' MA' 3 +3997 ' MB' 3 +3998 ' MC' 3 +3999 ' MD' 3 +4000 ' ME' 3 +4001 ' MF' 3 +4002 ' MG' 3 +4003 ' MH' 3 +4004 ' MI' 3 +4005 ' MJ' 3 +4006 ' MK' 3 +4007 ' ML' 3 +4008 ' MM' 3 +4009 ' MN' 3 +4010 ' MO' 3 +4011 ' MP' 3 +4012 ' MQ' 3 +4013 ' MR' 3 +4014 ' MS' 3 +4015 ' MT' 3 +4016 ' MU' 3 +4017 ' MV' 3 +4018 ' MW' 3 +4019 ' MX' 3 +4020 ' MY' 3 +4021 ' Ma' 3 +4022 ' Mb' 3 +4023 ' Mc' 3 +4024 ' Md' 3 +4025 ' Me' 3 +4026 ' Mg' 3 +4027 ' Mi' 3 +4028 ' Mk' 3 +4029 ' Mn' 3 +4030 ' Mo' 3 +4031 ' Mr' 3 +4032 ' Ms' 3 +4033 ' Mt' 3 +4034 ' Mu' 3 +4035 ' My' 3 +4036 ' NA' 3 +4037 ' NB' 3 +4038 ' NC' 3 +4039 ' ND' 3 +4040 ' NE' 3 +4041 ' NF' 3 +4042 ' NG' 3 +4043 ' NH' 3 +4044 ' NI' 3 +4045 ' NJ' 3 +4046 ' NK' 3 +4047 ' NL' 3 +4048 ' NM' 3 +4049 ' NN' 3 +4050 ' NO' 3 +4051 ' NP' 3 +4052 ' NR' 3 +4053 ' NS' 3 +4054 ' NT' 3 +4055 ' NU' 3 +4056 ' NV' 3 +4057 ' NW' 3 +4058 ' NY' 3 +4059 ' NZ' 3 +4060 ' Na' 3 +4061 ' Nb' 3 +4062 ' Nd' 3 +4063 ' Ne' 3 +4064 ' Ng' 3 +4065 ' Ni' 3 +4066 ' No' 3 +4067 ' Nr' 3 +4068 ' Nu' 3 +4069 ' Ny' 3 +4070 ' OA' 3 +4071 ' OB' 3 +4072 ' OC' 3 +4073 ' OD' 3 +4074 ' OF' 3 +4075 ' OH' 3 +4076 ' OK' 3 +4077 ' OL' 3 +4078 ' OM' 3 +4079 ' ON' 3 +4080 ' OP' 3 +4081 ' OR' 3 +4082 ' OS' 3 +4083 ' OT' 3 +4084 ' OU' 3 +4085 ' OV' 3 +4086 ' Ob' 3 +4087 ' Oc' 3 +4088 ' Od' 3 +4089 ' Of' 3 +4090 ' Og' 3 +4091 ' Oh' 3 +4092 ' Ok' 3 +4093 ' Ol' 3 +4094 ' Om' 3 +4095 ' On' 3 +4096 ' Op' 3 +4097 ' Or' 3 +4098 ' Os' 3 +4099 ' Ot' 3 +4100 ' Ou' 3 +4101 ' Ow' 3 +4102 ' Ox' 3 +4103 ' Oz' 3 +4104 ' PA' 3 +4105 ' PB' 3 +4106 ' PC' 3 +4107 ' PD' 3 +4108 ' PE' 3 +4109 ' PF' 3 +4110 ' PG' 3 +4111 ' PH' 3 +4112 ' PI' 3 +4113 ' PJ' 3 +4114 ' PK' 3 +4115 ' PL' 3 +4116 ' PM' 3 +4117 ' PN' 3 +4118 ' PO' 3 +4119 ' PP' 3 +4120 ' PR' 3 +4121 ' PS' 3 +4122 ' PT' 3 +4123 ' PU' 3 +4124 ' PV' 3 +4125 ' PW' 3 +4126 ' PY' 3 +4127 ' Pa' 3 +4128 ' Pb' 3 +4129 ' Pe' 3 +4130 ' Pf' 3 +4131 ' Ph' 3 +4132 ' Pi' 3 +4133 ' Pl' 3 +4134 ' Po' 3 +4135 ' Pr' 3 +4136 ' Ps' 3 +4137 ' Pt' 3 +4138 ' Pu' 3 +4139 ' Py' 3 +4140 ' QA' 3 +4141 ' QB' 3 +4142 ' QC' 3 +4143 ' QQ' 3 +4144 ' QR' 3 +4145 ' QS' 3 +4146 ' QT' 3 +4147 ' QU' 3 +4148 ' Qi' 3 +4149 ' Qt' 3 +4150 ' Qu' 3 +4151 ' RA' 3 +4152 ' RB' 3 +4153 ' RC' 3 +4154 ' RD' 3 +4155 ' RE' 3 +4156 ' RF' 3 +4157 ' RG' 3 +4158 ' RH' 3 +4159 ' RI' 3 +4160 ' RJ' 3 +4161 ' RL' 3 +4162 ' RM' 3 +4163 ' RN' 3 +4164 ' RO' 3 +4165 ' RP' 3 +4166 ' RR' 3 +4167 ' RS' 3 +4168 ' RT' 3 +4169 ' RU' 3 +4170 ' RV' 3 +4171 ' RW' 3 +4172 ' RX' 3 +4173 ' Ra' 3 +4174 ' Rd' 3 +4175 ' Re' 3 +4176 ' Rh' 3 +4177 ' Ri' 3 +4178 ' Ro' 3 +4179 ' Rs' 3 +4180 ' Ru' 3 +4181 ' Rx' 3 +4182 ' Ry' 3 +4183 ' SA' 3 +4184 ' SB' 3 +4185 ' SC' 3 +4186 ' SD' 3 +4187 ' SE' 3 +4188 ' SF' 3 +4189 ' SG' 3 +4190 ' SH' 3 +4191 ' SI' 3 +4192 ' SJ' 3 +4193 ' SK' 3 +4194 ' SL' 3 +4195 ' SM' 3 +4196 ' SN' 3 +4197 ' SO' 3 +4198 ' SP' 3 +4199 ' SQ' 3 +4200 ' SR' 3 +4201 ' SS' 3 +4202 ' ST' 3 +4203 ' SU' 3 +4204 ' SV' 3 +4205 ' SW' 3 +4206 ' SY' 3 +4207 ' SZ' 3 +4208 ' Sa' 3 +4209 ' Sc' 3 +4210 ' Se' 3 +4211 ' Sh' 3 +4212 ' Si' 3 +4213 ' Sk' 3 +4214 ' Sl' 3 +4215 ' Sm' 3 +4216 ' Sn' 3 +4217 ' So' 3 +4218 ' Sp' 3 +4219 ' Sr' 3 +4220 ' St' 3 +4221 ' Su' 3 +4222 ' Sv' 3 +4223 ' Sw' 3 +4224 ' Sy' 3 +4225 ' Sz' 3 +4226 ' TA' 3 +4227 ' TB' 3 +4228 ' TC' 3 +4229 ' TD' 3 +4230 ' TE' 3 +4231 ' TF' 3 +4232 ' TG' 3 +4233 ' TH' 3 +4234 ' TI' 3 +4235 ' TK' 3 +4236 ' TL' 3 +4237 ' TM' 3 +4238 ' TN' 3 +4239 ' TO' 3 +4240 ' TP' 3 +4241 ' TR' 3 +4242 ' TS' 3 +4243 ' TT' 3 +4244 ' TU' 3 +4245 ' TV' 3 +4246 ' TW' 3 +4247 ' TX' 3 +4248 ' TY' 3 +4249 ' Ta' 3 +4250 ' Tb' 3 +4251 ' Te' 3 +4252 ' Th' 3 +4253 ' Ti' 3 +4254 ' Tk' 3 +4255 ' To' 3 +4256 ' Tr' 3 +4257 ' Ts' 3 +4258 ' Tu' 3 +4259 ' Tw' 3 +4260 ' Tx' 3 +4261 ' Ty' 3 +4262 ' UA' 3 +4263 ' UC' 3 +4264 ' UD' 3 +4265 ' UE' 3 +4266 ' UI' 3 +4267 ' UK' 3 +4268 ' UL' 3 +4269 ' UM' 3 +4270 ' UN' 3 +4271 ' UP' 3 +4272 ' UR' 3 +4273 ' US' 3 +4274 ' UT' 3 +4275 ' UV' 3 +4276 ' UW' 3 +4277 ' UX' 3 +4278 ' Ub' 3 +4279 ' Ud' 3 +4280 ' Ug' 3 +4281 ' Uh' 3 +4282 ' Ui' 3 +4283 ' Uk' 3 +4284 ' Ul' 3 +4285 ' Um' 3 +4286 ' Un' 3 +4287 ' Up' 3 +4288 ' Ur' 3 +4289 ' Us' 3 +4290 ' Ut' 3 +4291 ' VA' 3 +4292 ' VB' 3 +4293 ' VC' 3 +4294 ' VE' 3 +4295 ' VG' 3 +4296 ' VI' 3 +4297 ' VK' 3 +4298 ' VL' 3 +4299 ' VM' 3 +4300 ' VO' 3 +4301 ' VP' 3 +4302 ' VR' 3 +4303 ' VS' 3 +4304 ' VT' 3 +4305 ' VW' 3 +4306 ' Va' 3 +4307 ' Ve' 3 +4308 ' Vi' 3 +4309 ' Vo' 3 +4310 ' Vs' 3 +4311 ' Vu' 3 +4312 ' Vy' 3 +4313 ' WA' 3 +4314 ' WB' 3 +4315 ' WC' 3 +4316 ' WD' 3 +4317 ' WE' 3 +4318 ' WF' 3 +4319 ' WG' 3 +4320 ' WH' 3 +4321 ' WI' 3 +4322 ' WL' 3 +4323 ' WM' 3 +4324 ' WO' 3 +4325 ' WP' 3 +4326 ' WR' 3 +4327 ' WS' 3 +4328 ' WT' 3 +4329 ' WW' 3 +4330 ' Wa' 3 +4331 ' We' 3 +4332 ' Wh' 3 +4333 ' Wi' 3 +4334 ' Wo' 3 +4335 ' Wr' 3 +4336 ' Wu' 3 +4337 ' Wy' 3 +4338 ' XI' 3 +4339 ' XL' 3 +4340 ' XP' 3 +4341 ' XS' 3 +4342 ' XV' 3 +4343 ' XX' 3 +4344 ' XY' 3 +4345 ' Xi' 3 +4346 ' Xu' 3 +4347 ' YA' 3 +4348 ' YE' 3 +4349 ' Ya' 3 +4350 ' Ye' 3 +4351 ' Yi' 3 +4352 ' Yo' 3 +4353 ' Yu' 3 +4354 ' ZZ' 3 +4355 ' Za' 3 +4356 ' Ze' 3 +4357 ' Zh' 3 +4358 ' Zi' 3 +4359 ' Zn' 3 +4360 ' Zo' 3 +4361 ' Zu' 3 +4362 ' Zw' 3 +4363 ' ["' 3 +4364 ' [$' 3 +4365 " ['" 3 +4366 ' [(' 3 +4367 ' [*' 3 +4368 ' [-' 3 +4369 ' [:' 3 +4370 ' [<' 3 +4371 ' [[' 3 +4372 ' [\\' 3 +4373 ' []' 3 +4374 ' [_' 3 +4375 ' [`' 3 +4376 ' [{' 3 +4377 ' \\"' 3 +4378 ' \\$' 3 +4379 " \\'" 3 +4380 ' \\(' 3 +4381 ' \\;' 3 +4382 ' \\<' 3 +4383 ' \\\\' 3 +4384 ' \\{' 3 +4385 ' \\|' 3 +4386 ' ],' 3 +4387 ' ];' 3 +4388 ' ]]' 3 +4389 ' ^{' 3 +4390 ' _(' 3 +4391 ' _)' 3 +4392 ' _,' 3 +4393 ' _.' 3 +4394 ' __' 3 +4395 ' _{' 3 +4396 ' `%' 3 +4397 " `'" 3 +4398 ' `(' 3 +4399 ' `-' 3 +4400 ' `.' 3 +4401 ' `[' 3 +4402 ' `\\' 3 +4403 ' `_' 3 +4404 ' ``' 3 +4405 ' `{' 3 +4406 ' aa' 3 +4407 ' ab' 3 +4408 ' ac' 3 +4409 ' ad' 3 +4410 ' ae' 3 +4411 ' af' 3 +4412 ' ag' 3 +4413 ' ah' 3 +4414 ' ai' 3 +4415 ' aj' 3 +4416 ' ak' 3 +4417 ' al' 3 +4418 ' am' 3 +4419 ' an' 3 +4420 ' ao' 3 +4421 ' ap' 3 +4422 ' ar' 3 +4423 ' as' 3 +4424 ' at' 3 +4425 ' au' 3 +4426 ' av' 3 +4427 ' aw' 3 +4428 ' ax' 3 +4429 ' ay' 3 +4430 ' az' 3 +4431 ' ba' 3 +4432 ' bb' 3 +4433 ' bc' 3 +4434 ' bd' 3 +4435 ' be' 3 +4436 ' bf' 3 +4437 ' bg' 3 +4438 ' bh' 3 +4439 ' bi' 3 +4440 ' bl' 3 +4441 ' bm' 3 +4442 ' bn' 3 +4443 ' bo' 3 +4444 ' bp' 3 +4445 ' br' 3 +4446 ' bs' 3 +4447 ' bt' 3 +4448 ' bu' 3 +4449 ' bw' 3 +4450 ' by' 3 +4451 ' bz' 3 +4452 ' ca' 3 +4453 ' cb' 3 +4454 ' cc' 3 +4455 ' cd' 3 +4456 ' ce' 3 +4457 ' cf' 3 +4458 ' cg' 3 +4459 ' ch' 3 +4460 ' ci' 3 +4461 ' ck' 3 +4462 ' cl' 3 +4463 ' cm' 3 +4464 ' cn' 3 +4465 ' co' 3 +4466 ' cp' 3 +4467 ' cr' 3 +4468 ' cs' 3 +4469 ' ct' 3 +4470 ' cu' 3 +4471 ' cv' 3 +4472 ' cw' 3 +4473 ' cx' 3 +4474 ' cy' 3 +4475 ' cz' 3 +4476 ' dB' 3 +4477 ' da' 3 +4478 ' db' 3 +4479 ' dc' 3 +4480 ' dd' 3 +4481 ' de' 3 +4482 ' df' 3 +4483 ' dg' 3 +4484 ' dh' 3 +4485 ' di' 3 +4486 ' dj' 3 +4487 ' dk' 3 +4488 ' dl' 3 +4489 ' dm' 3 +4490 ' dn' 3 +4491 ' do' 3 +4492 ' dp' 3 +4493 ' dq' 3 +4494 ' dr' 3 +4495 ' ds' 3 +4496 ' dt' 3 +4497 ' du' 3 +4498 ' dv' 3 +4499 ' dw' 3 +4500 ' dx' 3 +4501 ' dy' 3 +4502 ' dz' 3 +4503 ' eV' 3 +4504 ' ea' 3 +4505 ' eb' 3 +4506 ' ec' 3 +4507 ' ed' 3 +4508 ' ee' 3 +4509 ' ef' 3 +4510 ' eg' 3 +4511 ' eh' 3 +4512 ' ei' 3 +4513 ' ej' 3 +4514 ' ek' 3 +4515 ' el' 3 +4516 ' em' 3 +4517 ' en' 3 +4518 ' ep' 3 +4519 ' eq' 3 +4520 ' er' 3 +4521 ' es' 3 +4522 ' et' 3 +4523 ' eu' 3 +4524 ' ev' 3 +4525 ' ew' 3 +4526 ' ex' 3 +4527 ' ey' 3 +4528 ' ez' 3 +4529 ' fa' 3 +4530 ' fb' 3 +4531 ' fc' 3 +4532 ' fd' 3 +4533 ' fe' 3 +4534 ' ff' 3 +4535 ' fi' 3 +4536 ' fj' 3 +4537 ' fl' 3 +4538 ' fm' 3 +4539 ' fn' 3 +4540 ' fo' 3 +4541 ' fp' 3 +4542 ' fr' 3 +4543 ' fs' 3 +4544 ' ft' 3 +4545 ' fu' 3 +4546 ' fx' 3 +4547 ' fy' 3 +4548 ' ga' 3 +4549 ' gb' 3 +4550 ' gc' 3 +4551 ' ge' 3 +4552 ' gg' 3 +4553 ' gh' 3 +4554 ' gi' 3 +4555 ' gj' 3 +4556 ' gl' 3 +4557 ' gm' 3 +4558 ' gn' 3 +4559 ' go' 3 +4560 ' gp' 3 +4561 ' gr' 3 +4562 ' gs' 3 +4563 ' gt' 3 +4564 ' gu' 3 +4565 ' gw' 3 +4566 ' gy' 3 +4567 ' ha' 3 +4568 ' hd' 3 +4569 ' he' 3 +4570 ' hf' 3 +4571 ' hi' 3 +4572 ' hl' 3 +4573 ' ho' 3 +4574 ' hp' 3 +4575 ' hr' 3 +4576 ' hs' 3 +4577 ' ht' 3 +4578 ' hu' 3 +4579 ' hv' 3 +4580 ' hw' 3 +4581 ' hy' 3 +4582 ' iT' 3 +4583 ' ia' 3 +4584 ' ib' 3 +4585 ' ic' 3 +4586 ' id' 3 +4587 ' ie' 3 +4588 ' if' 3 +4589 ' ig' 3 +4590 ' ih' 3 +4591 ' ii' 3 +4592 ' ij' 3 +4593 ' ik' 3 +4594 ' il' 3 +4595 ' im' 3 +4596 ' in' 3 +4597 ' io' 3 +4598 ' ip' 3 +4599 ' ir' 3 +4600 ' is' 3 +4601 ' it' 3 +4602 ' iv' 3 +4603 ' ix' 3 +4604 ' iy' 3 +4605 ' iz' 3 +4606 ' ja' 3 +4607 ' je' 3 +4608 ' ji' 3 +4609 ' jj' 3 +4610 ' jo' 3 +4611 ' js' 3 +4612 ' ju' 3 +4613 ' kB' 3 +4614 ' kW' 3 +4615 ' ka' 3 +4616 ' kb' 3 +4617 ' ke' 3 +4618 ' kg' 3 +4619 ' kh' 3 +4620 ' ki' 3 +4621 ' kj' 3 +4622 ' kk' 3 +4623 ' kl' 3 +4624 ' km' 3 +4625 ' kn' 3 +4626 ' ko' 3 +4627 ' kp' 3 +4628 ' kr' 3 +4629 ' ks' 3 +4630 ' kt' 3 +4631 ' ku' 3 +4632 ' kv' 3 +4633 ' kw' 3 +4634 ' ky' 3 +4635 ' la' 3 +4636 ' lb' 3 +4637 ' lc' 3 +4638 ' ld' 3 +4639 ' le' 3 +4640 ' lg' 3 +4641 ' li' 3 +4642 ' ll' 3 +4643 ' lm' 3 +4644 ' ln' 3 +4645 ' lo' 3 +4646 ' lp' 3 +4647 ' lr' 3 +4648 ' ls' 3 +4649 ' lt' 3 +4650 ' lu' 3 +4651 ' lv' 3 +4652 ' lw' 3 +4653 ' ly' 3 +4654 ' mL' 3 +4655 ' mM' 3 +4656 ' ma' 3 +4657 ' mb' 3 +4658 ' mc' 3 +4659 ' md' 3 +4660 ' me' 3 +4661 ' mf' 3 +4662 ' mg' 3 +4663 ' mi' 3 +4664 ' mk' 3 +4665 ' ml' 3 +4666 ' mm' 3 +4667 ' mn' 3 +4668 ' mo' 3 +4669 ' mp' 3 +4670 ' mr' 3 +4671 ' ms' 3 +4672 ' mt' 3 +4673 ' mu' 3 +4674 ' mv' 3 +4675 ' mw' 3 +4676 ' mx' 3 +4677 ' my' 3 +4678 ' na' 3 +4679 ' nb' 3 +4680 ' nc' 3 +4681 ' nd' 3 +4682 ' ne' 3 +4683 ' nf' 3 +4684 ' ng' 3 +4685 ' nh' 3 +4686 ' ni' 3 +4687 ' nj' 3 +4688 ' nk' 3 +4689 ' nl' 3 +4690 ' nm' 3 +4691 ' nn' 3 +4692 ' no' 3 +4693 ' np' 3 +4694 ' nr' 3 +4695 ' ns' 3 +4696 ' nt' 3 +4697 ' nu' 3 +4698 ' nv' 3 +4699 ' nw' 3 +4700 ' nx' 3 +4701 ' ny' 3 +4702 ' nz' 3 +4703 ' ob' 3 +4704 ' oc' 3 +4705 ' od' 3 +4706 ' of' 3 +4707 ' og' 3 +4708 ' oh' 3 +4709 ' ok' 3 +4710 ' ol' 3 +4711 ' om' 3 +4712 ' on' 3 +4713 ' oo' 3 +4714 ' op' 3 +4715 ' or' 3 +4716 ' os' 3 +4717 ' ot' 3 +4718 ' ou' 3 +4719 ' ov' 3 +4720 ' ow' 3 +4721 ' ox' 3 +4722 ' oy' 3 +4723 ' oz' 3 +4724 ' pH' 3 +4725 ' pa' 3 +4726 ' pb' 3 +4727 ' pc' 3 +4728 ' pd' 3 +4729 ' pe' 3 +4730 ' pf' 3 +4731 ' pg' 3 +4732 ' ph' 3 +4733 ' pi' 3 +4734 ' pk' 3 +4735 ' pl' 3 +4736 ' pm' 3 +4737 ' pn' 3 +4738 ' po' 3 +4739 ' pp' 3 +4740 ' pq' 3 +4741 ' pr' 3 +4742 ' ps' 3 +4743 ' pt' 3 +4744 ' pu' 3 +4745 ' pv' 3 +4746 ' pw' 3 +4747 ' px' 3 +4748 ' py' 3 +4749 ' qi' 3 +4750 ' qq' 3 +4751 ' qt' 3 +4752 ' qu' 3 +4753 ' ra' 3 +4754 ' rb' 3 +4755 ' rc' 3 +4756 ' rd' 3 +4757 ' re' 3 +4758 ' rf' 3 +4759 ' rg' 3 +4760 ' rh' 3 +4761 ' ri' 3 +4762 ' rm' 3 +4763 ' rn' 3 +4764 ' ro' 3 +4765 ' rp' 3 +4766 ' rr' 3 +4767 ' rs' 3 +4768 ' rt' 3 +4769 ' ru' 3 +4770 ' rv' 3 +4771 ' rw' 3 +4772 ' rx' 3 +4773 ' ry' 3 +4774 ' sa' 3 +4775 ' sb' 3 +4776 ' sc' 3 +4777 ' sd' 3 +4778 ' se' 3 +4779 ' sf' 3 +4780 ' sg' 3 +4781 ' sh' 3 +4782 ' si' 3 +4783 ' sj' 3 +4784 ' sk' 3 +4785 ' sl' 3 +4786 ' sm' 3 +4787 ' sn' 3 +4788 ' so' 3 +4789 ' sp' 3 +4790 ' sq' 3 +4791 ' sr' 3 +4792 ' ss' 3 +4793 ' st' 3 +4794 ' su' 3 +4795 ' sv' 3 +4796 ' sw' 3 +4797 ' sy' 3 +4798 ' sz' 3 +4799 ' ta' 3 +4800 ' tb' 3 +4801 ' tc' 3 +4802 ' td' 3 +4803 ' te' 3 +4804 ' tf' 3 +4805 ' th' 3 +4806 ' ti' 3 +4807 ' tk' 3 +4808 ' tl' 3 +4809 ' tm' 3 +4810 ' tn' 3 +4811 ' to' 3 +4812 ' tp' 3 +4813 ' tr' 3 +4814 ' ts' 3 +4815 ' tt' 3 +4816 ' tu' 3 +4817 ' tv' 3 +4818 ' tw' 3 +4819 ' tx' 3 +4820 ' ty' 3 +4821 ' tz' 3 +4822 ' ua' 3 +4823 ' ub' 3 +4824 ' uc' 3 +4825 ' ud' 3 +4826 ' ug' 3 +4827 ' uh' 3 +4828 ' ui' 3 +4829 ' uk' 3 +4830 ' ul' 3 +4831 ' um' 3 +4832 ' un' 3 +4833 ' up' 3 +4834 ' ur' 3 +4835 ' us' 3 +4836 ' ut' 3 +4837 ' uv' 3 +4838 ' uw' 3 +4839 ' uz' 3 +4840 ' va' 3 +4841 ' vb' 3 +4842 ' vc' 3 +4843 ' ve' 3 +4844 ' vi' 3 +4845 ' vl' 3 +4846 ' vm' 3 +4847 ' vn' 3 +4848 ' vo' 3 +4849 ' vp' 3 +4850 ' vr' 3 +4851 ' vs' 3 +4852 ' vt' 3 +4853 ' vu' 3 +4854 ' vy' 3 +4855 ' wa' 3 +4856 ' wb' 3 +4857 ' wc' 3 +4858 ' we' 3 +4859 ' wf' 3 +4860 ' wh' 3 +4861 ' wi' 3 +4862 ' wk' 3 +4863 ' wo' 3 +4864 ' wp' 3 +4865 ' wr' 3 +4866 ' ws' 3 +4867 ' wt' 3 +4868 ' ww' 3 +4869 ' wx' 3 +4870 ' wy' 3 +4871 ' xe' 3 +4872 ' xi' 3 +4873 ' xl' 3 +4874 ' xs' 3 +4875 ' xt' 3 +4876 ' xx' 3 +4877 ' xy' 3 +4878 ' ya' 3 +4879 ' ye' 3 +4880 ' yi' 3 +4881 ' yo' 3 +4882 ' yr' 3 +4883 ' ys' 3 +4884 ' yy' 3 +4885 ' za' 3 +4886 ' ze' 3 +4887 ' zh' 3 +4888 ' zi' 3 +4889 ' zo' 3 +4890 ' zu' 3 +4891 ' zw' 3 +4892 ' zz' 3 +4893 ' {"' 3 +4894 ' {$' 3 +4895 ' {%' 3 +4896 " {'" 3 +4897 ' {(' 3 +4898 ' {-' 3 +4899 ' {:' 3 +4900 ' {@' 3 +4901 ' {\\' 3 +4902 ' {{' 3 +4903 ' {}' 3 +4904 ' |=' 3 +4905 ' |\\' 3 +4906 ' ||' 3 +4907 ' })' 3 +4908 ' },' 3 +4909 ' };' 3 +4910 ' }\\' 3 +4911 ' }]' 3 +4912 ' }{' 3 +4913 ' }}' 3 +4914 ' ~/' 3 +4915 ' \xa0' 3 +4916 ' ¡' 3 +4917 ' ¢' 3 +4918 ' £' 3 +4919 ' ¤' 3 +4920 ' ¥' 3 +4921 ' ¦' 3 +4922 ' §' 3 +4923 ' ©' 3 +4924 ' «' 3 +4925 ' ¬' 3 +4926 ' \xad' 3 +4927 ' ®' 3 +4928 ' °' 3 +4929 ' ±' 3 +4930 ' µ' 3 +4931 ' ¶' 3 +4932 ' ·' 3 +4933 ' »' 3 +4934 ' ¼' 3 +4935 ' ½' 3 +4936 ' ¿' 3 +4937 ' À' 3 +4938 ' Á' 3 +4939 ' Â' 3 +4940 ' Ã' 3 +4941 ' Ä' 3 +4942 ' Å' 3 +4943 ' Ç' 3 +4944 ' È' 3 +4945 ' É' 3 +4946 ' Ê' 3 +4947 ' Í' 3 +4948 ' Î' 3 +4949 ' Ð' 3 +4950 ' Ñ' 3 +4951 ' Ò' 3 +4952 ' Ó' 3 +4953 ' Ô' 3 +4954 ' Ö' 3 +4955 ' ×' 3 +4956 ' Ø' 3 +4957 ' Ú' 3 +4958 ' Ü' 3 +4959 ' Þ' 3 +4960 ' ß' 3 +4961 ' à' 3 +4962 ' á' 3 +4963 ' â' 3 +4964 ' ã' 3 +4965 ' ä' 3 +4966 ' å' 3 +4967 ' æ' 3 +4968 ' ç' 3 +4969 ' è' 3 +4970 ' é' 3 +4971 ' ê' 3 +4972 ' ë' 3 +4973 ' ì' 3 +4974 ' í' 3 +4975 ' î' 3 +4976 ' ð' 3 +4977 ' ñ' 3 +4978 ' ó' 3 +4979 ' ô' 3 +4980 ' ö' 3 +4981 ' ÷' 3 +4982 ' ø' 3 +4983 ' ú' 3 +4984 ' ü' 3 +4985 ' þ' 3 +4986 ' Ā' 3 +4987 ' ā' 3 +4988 ' ĉ' 3 +4989 ' Č' 3 +4990 ' č' 3 +4991 ' Đ' 3 +4992 ' đ' 3 +4993 ' İ' 3 +4994 ' Ł' 3 +4995 ' ł' 3 +4996 ' ő' 3 +4997 ' œ' 3 +4998 ' ř' 3 +4999 ' Ś' 3 +5000 ' ś' 3 +5001 ' ŝ' 3 +5002 ' Ş' 3 +5003 ' ş' 3 +5004 ' Š' 3 +5005 ' š' 3 +5006 ' ū' 3 +5007 ' Ż' 3 +5008 ' ż' 3 +5009 ' Ž' 3 +5010 ' ž' 3 +5011 ' ǫ' 3 +5012 ' ́' 3 +5013 ' ̃' 3 +5014 ' ̄' 3 +5015 ' ̇' 3 +5016 ' ̈' 3 +5017 ' ̊' 3 +5018 ' ̧' 3 +5019 ' Α' 3 +5020 ' Γ' 3 +5021 ' Δ' 3 +5022 ' Ε' 3 +5023 ' Θ' 3 +5024 ' Κ' 3 +5025 ' Λ' 3 +5026 ' Μ' 3 +5027 ' Π' 3 +5028 ' Σ' 3 +5029 ' Τ' 3 +5030 ' Φ' 3 +5031 ' Ψ' 3 +5032 ' Ω' 3 +5033 ' έ' 3 +5034 ' α' 3 +5035 ' β' 3 +5036 ' γ' 3 +5037 ' δ' 3 +5038 ' ε' 3 +5039 ' ζ' 3 +5040 ' η' 3 +5041 ' θ' 3 +5042 ' ι' 3 +5043 ' κ' 3 +5044 ' λ' 3 +5045 ' μ' 3 +5046 ' ν' 3 +5047 ' ξ' 3 +5048 ' ο' 3 +5049 ' π' 3 +5050 ' ρ' 3 +5051 ' σ' 3 +5052 ' τ' 3 +5053 ' υ' 3 +5054 ' φ' 3 +5055 ' χ' 3 +5056 ' ψ' 3 +5057 ' ω' 3 +5058 ' ό' 3 +5059 ' Є' 3 +5060 ' І' 3 +5061 ' Ј' 3 +5062 ' А' 3 +5063 ' Б' 3 +5064 ' В' 3 +5065 ' Г' 3 +5066 ' Д' 3 +5067 ' Е' 3 +5068 ' Ж' 3 +5069 ' З' 3 +5070 ' И' 3 +5071 ' Й' 3 +5072 ' К' 3 +5073 ' Л' 3 +5074 ' М' 3 +5075 ' Н' 3 +5076 ' О' 3 +5077 ' П' 3 +5078 ' Р' 3 +5079 ' С' 3 +5080 ' Т' 3 +5081 ' У' 3 +5082 ' Ф' 3 +5083 ' Х' 3 +5084 ' Ц' 3 +5085 ' Ч' 3 +5086 ' Ш' 3 +5087 ' Щ' 3 +5088 ' Э' 3 +5089 ' Ю' 3 +5090 ' Я' 3 +5091 ' а' 3 +5092 ' б' 3 +5093 ' в' 3 +5094 ' г' 3 +5095 ' д' 3 +5096 ' е' 3 +5097 ' ж' 3 +5098 ' з' 3 +5099 ' и' 3 +5100 ' й' 3 +5101 ' к' 3 +5102 ' л' 3 +5103 ' м' 3 +5104 ' н' 3 +5105 ' о' 3 +5106 ' п' 3 +5107 ' р' 3 +5108 ' с' 3 +5109 ' т' 3 +5110 ' у' 3 +5111 ' ф' 3 +5112 ' х' 3 +5113 ' ц' 3 +5114 ' ч' 3 +5115 ' ш' 3 +5116 ' щ' 3 +5117 ' э' 3 +5118 ' ю' 3 +5119 ' я' 3 +5120 ' є' 3 +5121 ' і' 3 +5122 ' ї' 3 +5123 ' ј' 3 +5124 ' א' 3 +5125 ' ב' 3 +5126 ' ה' 3 +5127 ' ו' 3 +5128 ' י' 3 +5129 ' כ' 3 +5130 ' ל' 3 +5131 ' מ' 3 +5132 ' נ' 3 +5133 ' ע' 3 +5134 ' ש' 3 +5135 ' آ' 3 +5136 ' أ' 3 +5137 ' إ' 3 +5138 ' ا' 3 +5139 ' ب' 3 +5140 ' ت' 3 +5141 ' ج' 3 +5142 ' ح' 3 +5143 ' خ' 3 +5144 ' د' 3 +5145 ' ر' 3 +5146 ' س' 3 +5147 ' ش' 3 +5148 ' ص' 3 +5149 ' ع' 3 +5150 ' ف' 3 +5151 ' ق' 3 +5152 ' ك' 3 +5153 ' ل' 3 +5154 ' م' 3 +5155 ' ن' 3 +5156 ' ه' 3 +5157 ' و' 3 +5158 ' ي' 3 +5159 ' پ' 3 +5160 ' ک' 3 +5161 ' گ' 3 +5162 ' ی' 3 +5163 '!!!' 3 +5164 '!")' 3 +5165 '!",' 3 +5166 "!'," 3 +5167 '!),' 3 +5168 '!).' 3 +5169 '!--' 3 +5170 '"""' 3 +5171 '"",' 3 +5172 '"))' 3 +5173 '"),' 3 +5174 '").' 3 +5175 '"):' 3 +5176 '");' 3 +5177 '")]' 3 +5178 '","' 3 +5179 '"--' 3 +5180 '"/>' 3 +5181 '":"' 3 +5182 '":[' 3 +5183 '":{' 3 +5184 '"' 3 +5186 '">&' 3 +5187 '">\'' 3 +5188 '"><' 3 +5189 '"?>' 3 +5190 '"])' 3 +5191 '"],' 3 +5192 '"].' 3 +5193 '"]:' 3 +5194 '"];' 3 +5195 '"][' 3 +5196 '"]]' 3 +5197 '"]}' 3 +5198 '"})' 3 +5199 '"},' 3 +5200 '"}}' 3 +5201 '###' 3 +5202 '%),' 3 +5203 '%).' 3 +5204 '\'",' 3 +5205 "'''" 3 +5206 "')(" 3 +5207 "'))" 3 +5208 "')," 3 +5209 "')." 3 +5210 "'):" 3 +5211 "');" 3 +5212 "')[" 3 +5213 "')]" 3 +5214 "','" 3 +5215 "':'" 3 +5216 "'" 3 +5218 "'><" 3 +5219 "'])" 3 +5220 "']*" 3 +5221 "']," 3 +5222 "']." 3 +5223 "']:" 3 +5224 "'];" 3 +5225 "']=" 3 +5226 "'][" 3 +5227 "']]" 3 +5228 "']}" 3 +5229 "'ll" 3 +5230 "'re" 3 +5231 "'ve" 3 +5232 "'})" 3 +5233 "'}," 3 +5234 '(""' 3 +5235 '("#' 3 +5236 '("%' 3 +5237 '("+' 3 +5238 '(",' 3 +5239 '("-' 3 +5240 '(".' 3 +5241 '("/' 3 +5242 '(":' 3 +5243 '("<' 3 +5244 '("@' 3 +5245 '("\\' 3 +5246 '($_' 3 +5247 "('#" 3 +5248 "('$" 3 +5249 "('," 3 +5250 "('-" 3 +5251 "('." 3 +5252 "('/" 3 +5253 "(':" 3 +5254 "('<" 3 +5255 "('@" 3 +5256 "('[" 3 +5257 "('\\" 3 +5258 "('^" 3 +5259 "('_" 3 +5260 "(('" 3 +5261 '(((' 3 +5262 '(()' 3 +5263 '()"' 3 +5264 '()(' 3 +5265 '())' 3 +5266 '(),' 3 +5267 '().' 3 +5268 '():' 3 +5269 '();' 3 +5270 '()[' 3 +5271 '()]' 3 +5272 '()`' 3 +5273 '(){' 3 +5274 '()}' 3 +5275 '(*)' 3 +5276 '(**' 3 +5277 '(?:' 3 +5278 '(@"' 3 +5279 '(["' 3 +5280 "(['" 3 +5281 '([[' 3 +5282 '([\\' 3 +5283 '([^' 3 +5284 '(__' 3 +5285 "({'" 3 +5286 ')")' 3 +5287 ')",' 3 +5288 ')".' 3 +5289 ')">' 3 +5290 ")'," 3 +5291 ')(?' 3 +5292 ')))' 3 +5293 '))*' 3 +5294 ')),' 3 +5295 ')).' 3 +5296 '))/' 3 +5297 ')):' 3 +5298 '));' 3 +5299 '))?' 3 +5300 '))\\' 3 +5301 '))]' 3 +5302 ')){' 3 +5303 ')*(' 3 +5304 ')**' 3 +5305 ')+(' 3 +5306 '),(' 3 +5307 '),\\' 3 +5308 ')--' 3 +5309 ')->' 3 +5310 ')."' 3 +5311 ')..' 3 +5312 ').[' 3 +5313 ').\\' 3 +5314 ')/(' 3 +5315 ');\\' 3 +5316 ')' 3 +5349 '->_' 3 +5350 '.""' 3 +5351 '.")' 3 +5352 '.",' 3 +5353 '."[' 3 +5354 '.$$' 3 +5355 '.\'"' 3 +5356 ".''" 3 +5357 ".')" 3 +5358 ".'," 3 +5359 '.),' 3 +5360 '.).' 3 +5361 '.--' 3 +5362 '...' 3 +5363 '../' 3 +5364 '.' 3 +5371 "/')" 3 +5372 "/'," 3 +5373 '/*!' 3 +5374 '/**' 3 +5375 '/*.' 3 +5376 '///' 3 +5377 '/>.' 3 +5378 '/__' 3 +5379 ':")' 3 +5380 ':",' 3 +5381 ":')" 3 +5382 ":'," 3 +5383 ':**' 3 +5384 ':--' 3 +5385 '://' 3 +5386 ':' 3 +5393 ';")' 3 +5431 '>",' 3 +5432 '>";' 3 +5433 ">')" 3 +5434 ">'," 3 +5435 ">';" 3 +5436 '>()' 3 +5437 '>).' 3 +5438 '>::' 3 +5439 '>>>' 3 +5441 '>{{' 3 +5442 '?",' 3 +5443 "?'," 3 +5444 '?),' 3 +5445 '?).' 3 +5446 '???' 3 +5447 'AAA' 3 +5448 'ABA' 3 +5449 'ABC' 3 +5450 'ABI' 3 +5451 'ABS' 3 +5452 'ACA' 3 +5453 'ACC' 3 +5454 'ACE' 3 +5455 'ACH' 3 +5456 'ACK' 3 +5457 'ACP' 3 +5458 'ACS' 3 +5459 'ACT' 3 +5460 'ADA' 3 +5461 'ADC' 3 +5462 'ADD' 3 +5463 'ADE' 3 +5464 'ADO' 3 +5465 'ADS' 3 +5466 'AES' 3 +5467 'AFF' 3 +5468 'AFP' 3 +5469 'AGE' 3 +5470 'AGG' 3 +5471 'AIL' 3 +5472 'AIN' 3 +5473 'AIR' 3 +5474 'ALA' 3 +5475 'ALE' 3 +5476 'ALK' 3 +5477 'ALL' 3 +5478 'ALS' 3 +5479 'ALT' 3 +5480 'AMA' 3 +5481 'AMB' 3 +5482 'AMD' 3 +5483 'AME' 3 +5484 'AMI' 3 +5485 'AML' 3 +5486 'AMP' 3 +5487 'AMS' 3 +5488 'ANA' 3 +5489 'ANC' 3 +5490 'AND' 3 +5491 'ANE' 3 +5492 'ANG' 3 +5493 'ANI' 3 +5494 'ANK' 3 +5495 'ANN' 3 +5496 'ANO' 3 +5497 'ANS' 3 +5498 'ANT' 3 +5499 'ANY' 3 +5500 'APE' 3 +5501 'APH' 3 +5502 'API' 3 +5503 'APP' 3 +5504 'APS' 3 +5505 'ARA' 3 +5506 'ARB' 3 +5507 'ARC' 3 +5508 'ARD' 3 +5509 'ARE' 3 +5510 'ARG' 3 +5511 'ARI' 3 +5512 'ARK' 3 +5513 'ARM' 3 +5514 'ARN' 3 +5515 'ARP' 3 +5516 'ARR' 3 +5517 'ARS' 3 +5518 'ART' 3 +5519 'ARY' 3 +5520 'ASA' 3 +5521 'ASC' 3 +5522 'ASE' 3 +5523 'ASH' 3 +5524 'ASK' 3 +5525 'ASM' 3 +5526 'ASP' 3 +5527 'ASS' 3 +5528 'AST' 3 +5529 'ASY' 3 +5530 'ATA' 3 +5531 'ATE' 3 +5532 'ATH' 3 +5533 'ATI' 3 +5534 'ATO' 3 +5535 'ATS' 3 +5536 'ATT' 3 +5537 'AUD' 3 +5538 'AUT' 3 +5539 'AVA' 3 +5540 'AVE' 3 +5541 'AWS' 3 +5542 'Abs' 3 +5543 'Acc' 3 +5544 'Ack' 3 +5545 'Act' 3 +5546 'Ada' 3 +5547 'Add' 3 +5548 'Adj' 3 +5549 'Adv' 3 +5550 'Aff' 3 +5551 'Age' 3 +5552 'Agg' 3 +5553 'Air' 3 +5554 'Akt' 3 +5555 'Ald' 3 +5556 'Ale' 3 +5557 'Alg' 3 +5558 'Ali' 3 +5559 'All' 3 +5560 'Alt' 3 +5561 'Amb' 3 +5562 'Amy' 3 +5563 'And' 3 +5564 'Ang' 3 +5565 'Ann' 3 +5566 'Ans' 3 +5567 'Ant' 3 +5568 'Any' 3 +5569 'Api' 3 +5570 'App' 3 +5571 'Apr' 3 +5572 'Aqu' 3 +5573 'Arc' 3 +5574 'Are' 3 +5575 'Arg' 3 +5576 'Ari' 3 +5577 'Arm' 3 +5578 'Arn' 3 +5579 'Arr' 3 +5580 'Art' 3 +5581 'Asc' 3 +5582 'Ash' 3 +5583 'Ask' 3 +5584 'Asp' 3 +5585 'Ass' 3 +5586 'Ast' 3 +5587 'Ath' 3 +5588 'Atl' 3 +5589 'Att' 3 +5590 'Aud' 3 +5591 'Aug' 3 +5592 'Aut' 3 +5593 'Aux' 3 +5594 'Avg' 3 +5595 'Aws' 3 +5596 'BAD' 3 +5597 'BAL' 3 +5598 'BAR' 3 +5599 'BAS' 3 +5600 'BAT' 3 +5601 'BBC' 3 +5602 'BER' 3 +5603 'BIG' 3 +5604 'BIN' 3 +5605 'BIT' 3 +5606 'BLE' 3 +5607 'BMI' 3 +5608 'BOT' 3 +5609 'BOX' 3 +5610 'BRE' 3 +5611 'BSD' 3 +5612 'BUF' 3 +5613 'BUG' 3 +5614 'BUR' 3 +5615 'BUS' 3 +5616 'Bab' 3 +5617 'Bad' 3 +5618 'Bag' 3 +5619 'Bah' 3 +5620 'Bal' 3 +5621 'Ban' 3 +5622 'Bar' 3 +5623 'Bas' 3 +5624 'Bat' 3 +5625 'Bay' 3 +5626 'Bbb' 3 +5627 'Bed' 3 +5628 'Bel' 3 +5629 'Ben' 3 +5630 'Ber' 3 +5631 'Bes' 3 +5632 'Bet' 3 +5633 'Bib' 3 +5634 'Bid' 3 +5635 'Big' 3 +5636 'Bin' 3 +5637 'Bio' 3 +5638 'Bir' 3 +5639 'Bit' 3 +5640 'Blo' 3 +5641 'Bob' 3 +5642 'Bol' 3 +5643 'Bon' 3 +5644 'Bor' 3 +5645 'Bot' 3 +5646 'Bow' 3 +5647 'Box' 3 +5648 'Boy' 3 +5649 'Bra' 3 +5650 'Bre' 3 +5651 'Bro' 3 +5652 'Btn' 3 +5653 'Buf' 3 +5654 'Bug' 3 +5655 'Bul' 3 +5656 'Bur' 3 +5657 'Bus' 3 +5658 'But' 3 +5659 'Buy' 3 +5660 'CAC' 3 +5661 'CAD' 3 +5662 'CAL' 3 +5663 'CAM' 3 +5664 'CAN' 3 +5665 'CAP' 3 +5666 'CAR' 3 +5667 'CAS' 3 +5668 'CAT' 3 +5669 'CBC' 3 +5670 'CBS' 3 +5671 'CCA' 3 +5672 'CCC' 3 +5673 'CDC' 3 +5674 'CDF' 3 +5675 'CEL' 3 +5676 'CEO' 3 +5677 'CEP' 3 +5678 'CER' 3 +5679 'CES' 3 +5680 'CFG' 3 +5681 'CHA' 3 +5682 'CHE' 3 +5683 'CHO' 3 +5684 'CHR' 3 +5685 'CID' 3 +5686 'CLA' 3 +5687 'CLC' 3 +5688 'CLE' 3 +5689 'CLI' 3 +5690 'CLK' 3 +5691 'CLS' 3 +5692 'CLU' 3 +5693 'CMD' 3 +5694 'CMS' 3 +5695 'CNN' 3 +5696 'CNT' 3 +5697 'COD' 3 +5698 'COL' 3 +5699 'COM' 3 +5700 'CON' 3 +5701 'COR' 3 +5702 'COS' 3 +5703 'CPP' 3 +5704 'CPU' 3 +5705 'CRC' 3 +5706 'CRE' 3 +5707 'CSI' 3 +5708 'CSS' 3 +5709 'CSV' 3 +5710 'CTC' 3 +5711 'CTL' 3 +5712 'CTT' 3 +5713 'CTX' 3 +5714 'CUR' 3 +5715 'Cab' 3 +5716 'Cad' 3 +5717 'Cal' 3 +5718 'Cam' 3 +5719 'Can' 3 +5720 'Cap' 3 +5721 'Car' 3 +5722 'Cas' 3 +5723 'Cat' 3 +5724 'Cel' 3 +5725 'Cfg' 3 +5726 'Cha' 3 +5727 'Che' 3 +5728 'Chi' 3 +5729 'Cho' 3 +5730 'Cir' 3 +5731 'Cit' 3 +5732 'Cla' 3 +5733 'Cle' 3 +5734 'Cli' 3 +5735 'Clo' 3 +5736 'Cmd' 3 +5737 'Cnt' 3 +5738 'CoV' 3 +5739 'Cod' 3 +5740 'Cog' 3 +5741 'Col' 3 +5742 'Com' 3 +5743 'Con' 3 +5744 'Cop' 3 +5745 'Cor' 3 +5746 'Cos' 3 +5747 'Cov' 3 +5748 'Cre' 3 +5749 'Cro' 3 +5750 'Css' 3 +5751 'Csv' 3 +5752 'Ctr' 3 +5753 'Ctx' 3 +5754 'Cur' 3 +5755 'Cut' 3 +5756 'DAC' 3 +5757 'DAG' 3 +5758 'DAO' 3 +5759 'DAT' 3 +5760 'DAY' 3 +5761 'DBC' 3 +5762 'DEC' 3 +5763 'DED' 3 +5764 'DEF' 3 +5765 'DEL' 3 +5766 'DEM' 3 +5767 'DEN' 3 +5768 'DEP' 3 +5769 'DER' 3 +5770 'DES' 3 +5771 'DET' 3 +5772 'DEV' 3 +5773 'DEX' 3 +5774 'DIC' 3 +5775 'DIG' 3 +5776 'DIM' 3 +5777 'DIR' 3 +5778 'DIS' 3 +5779 'DIV' 3 +5780 'DLL' 3 +5781 'DNA' 3 +5782 'DNS' 3 +5783 'DOC' 3 +5784 'DOM' 3 +5785 'DON' 3 +5786 'DOT' 3 +5787 'DTD' 3 +5788 'DVD' 3 +5789 'Dal' 3 +5790 'Dam' 3 +5791 'Dan' 3 +5792 'Dao' 3 +5793 'Dar' 3 +5794 'Das' 3 +5795 'Dat' 3 +5796 'Dav' 3 +5797 'Day' 3 +5798 'Deb' 3 +5799 'Dec' 3 +5800 'Def' 3 +5801 'Deg' 3 +5802 'Del' 3 +5803 'Dem' 3 +5804 'Den' 3 +5805 'Dep' 3 +5806 'Der' 3 +5807 'Des' 3 +5808 'Det' 3 +5809 'Dev' 3 +5810 'Dic' 3 +5811 'Did' 3 +5812 'Die' 3 +5813 'Dig' 3 +5814 'Dim' 3 +5815 'Dir' 3 +5816 'Dis' 3 +5817 'Div' 3 +5818 'Dlg' 3 +5819 'Doc' 3 +5820 'Dog' 3 +5821 'Dom' 3 +5822 'Don' 3 +5823 'Dot' 3 +5824 'Dou' 3 +5825 'Dry' 3 +5826 'Dub' 3 +5827 'Due' 3 +5828 'Dup' 3 +5829 'Dur' 3 +5830 'Dyn' 3 +5831 'Dé' 3 +5832 'EAR' 3 +5833 'ECD' 3 +5834 'ECK' 3 +5835 'ECT' 3 +5836 'EEE' 3 +5837 'EEK' 3 +5838 'EFF' 3 +5839 'ELD' 3 +5840 'ELE' 3 +5841 'ELL' 3 +5842 'ELS' 3 +5843 'ELY' 3 +5844 'EMA' 3 +5845 'EMP' 3 +5846 'ENA' 3 +5847 'ENC' 3 +5848 'END' 3 +5849 'ENE' 3 +5850 'ENG' 3 +5851 'ENO' 3 +5852 'ENS' 3 +5853 'ENT' 3 +5854 'ENV' 3 +5855 'EOF' 3 +5856 'EPS' 3 +5857 'ERA' 3 +5858 'ERC' 3 +5859 'ERE' 3 +5860 'ERN' 3 +5861 'ERO' 3 +5862 'ERR' 3 +5863 'ERS' 3 +5864 'ERT' 3 +5865 'ERV' 3 +5866 'ERY' 3 +5867 'ESA' 3 +5868 'ESC' 3 +5869 'ESH' 3 +5870 'ESP' 3 +5871 'ESS' 3 +5872 'EST' 3 +5873 'ETA' 3 +5874 'ETH' 3 +5875 'ETS' 3 +5876 'EUR' 3 +5877 'EXP' 3 +5878 'EXT' 3 +5879 'Ear' 3 +5880 'Eff' 3 +5881 'Ele' 3 +5882 'Ell' 3 +5883 'Emb' 3 +5884 'Emp' 3 +5885 'Enc' 3 +5886 'End' 3 +5887 'Eng' 3 +5888 'Enh' 3 +5889 'Ent' 3 +5890 'Env' 3 +5891 'Equ' 3 +5892 'Err' 3 +5893 'Esc' 3 +5894 'Esp' 3 +5895 'Ess' 3 +5896 'Est' 3 +5897 'Eth' 3 +5898 'Exc' 3 +5899 'Exp' 3 +5900 'Ext' 3 +5901 'Eye' 3 +5902 'FER' 3 +5903 'FET' 3 +5904 'FFF' 3 +5905 'FFT' 3 +5906 'FIG' 3 +5907 'FIL' 3 +5908 'FIN' 3 +5909 'FIR' 3 +5910 'FIT' 3 +5911 'FIX' 3 +5912 'FLO' 3 +5913 'FOR' 3 +5914 'FUN' 3 +5915 'Fab' 3 +5916 'Fac' 3 +5917 'Fal' 3 +5918 'Fan' 3 +5919 'Far' 3 +5920 'Fat' 3 +5921 'Feb' 3 +5922 'Fed' 3 +5923 'Fel' 3 +5924 'Fer' 3 +5925 'Few' 3 +5926 'Fig' 3 +5927 'Fil' 3 +5928 'Fin' 3 +5929 'Fit' 3 +5930 'Fix' 3 +5931 'Flo' 3 +5932 'Flu' 3 +5933 'Fly' 3 +5934 'Fmt' 3 +5935 'Foo' 3 +5936 'For' 3 +5937 'Fox' 3 +5938 'Fra' 3 +5939 'Fre' 3 +5940 'Fri' 3 +5941 'Fun' 3 +5942 'GAL' 3 +5943 'GAN' 3 +5944 'GAT' 3 +5945 'GBT' 3 +5946 'GCC' 3 +5947 'GEN' 3 +5948 'GER' 3 +5949 'GES' 3 +5950 'GET' 3 +5951 'GHz' 3 +5952 'GIN' 3 +5953 'GIS' 3 +5954 'GIT' 3 +5955 'GLE' 3 +5956 'GMT' 3 +5957 'GNU' 3 +5958 'GPL' 3 +5959 'GPS' 3 +5960 'GPU' 3 +5961 'GRA' 3 +5962 'GRE' 3 +5963 'GRO' 3 +5964 'GRP' 3 +5965 'GUI' 3 +5966 'Gab' 3 +5967 'Gal' 3 +5968 'Gap' 3 +5969 'Gar' 3 +5970 'Gas' 3 +5971 'GeV' 3 +5972 'Gem' 3 +5973 'Gen' 3 +5974 'Geo' 3 +5975 'Ger' 3 +5976 'Get' 3 +5977 'Gib' 3 +5978 'Gil' 3 +5979 'Git' 3 +5980 'God' 3 +5981 'Got' 3 +5982 'Gra' 3 +5983 'Gre' 3 +5984 'Gro' 3 +5985 'Gui' 3 +5986 'Gun' 3 +5987 'Guy' 3 +5988 'HAL' 3 +5989 'HAS' 3 +5990 'HEL' 3 +5991 'HER' 3 +5992 'HIV' 3 +5993 'HOW' 3 +5994 'Had' 3 +5995 'Hal' 3 +5996 'Ham' 3 +5997 'Han' 3 +5998 'Har' 3 +5999 'Has' 3 +6000 'Haw' 3 +6001 'Hay' 3 +6002 'Haz' 3 +6003 'Hel' 3 +6004 'Hen' 3 +6005 'Her' 3 +6006 'Hex' 3 +6007 'Hey' 3 +6008 'Hig' 3 +6009 'Hip' 3 +6010 'His' 3 +6011 'Hit' 3 +6012 'Hol' 3 +6013 'Hom' 3 +6014 'Hon' 3 +6015 'Hop' 3 +6016 'Hor' 3 +6017 'Hot' 3 +6018 'How' 3 +6019 'Hub' 3 +6020 'Hum' 3 +6021 'IAL' 3 +6022 'IAN' 3 +6023 'IAS' 3 +6024 'IBM' 3 +6025 'ICA' 3 +6026 'ICC' 3 +6027 'ICE' 3 +6028 'ICH' 3 +6029 'ICI' 3 +6030 'ICK' 3 +6031 'ICO' 3 +6032 'ICS' 3 +6033 'ICT' 3 +6034 'IDA' 3 +6035 'IDD' 3 +6036 'IDE' 3 +6037 'IDI' 3 +6038 'IDS' 3 +6039 'IDs' 3 +6040 'IED' 3 +6041 'IER' 3 +6042 'IES' 3 +6043 'IEW' 3 +6044 'IFE' 3 +6045 'IFF' 3 +6046 'IFI' 3 +6047 'IFT' 3 +6048 'IFY' 3 +6049 'IGH' 3 +6050 'IGN' 3 +6051 'III' 3 +6052 'ILD' 3 +6053 'ILE' 3 +6054 'ILL' 3 +6055 'ILS' 3 +6056 'ILY' 3 +6057 'IMA' 3 +6058 'IME' 3 +6059 'IMG' 3 +6060 'IMO' 3 +6061 'IMP' 3 +6062 'IMS' 3 +6063 'INA' 3 +6064 'INC' 3 +6065 'IND' 3 +6066 'INE' 3 +6067 'INF' 3 +6068 'ING' 3 +6069 'INI' 3 +6070 'INK' 3 +6071 'INO' 3 +6072 'INS' 3 +6073 'INT' 3 +6074 'ION' 3 +6075 'IOR' 3 +6076 'IOS' 3 +6077 'IPA' 3 +6078 'IPP' 3 +6079 'IPS' 3 +6080 'IPT' 3 +6081 'IPV' 3 +6082 'IPv' 3 +6083 'IRA' 3 +6084 'IRC' 3 +6085 'IRD' 3 +6086 'IRE' 3 +6087 'IRS' 3 +6088 'IRT' 3 +6089 'ISA' 3 +6090 'ISC' 3 +6091 'ISE' 3 +6092 'ISH' 3 +6093 'ISM' 3 +6094 'ISO' 3 +6095 'ISP' 3 +6096 'ISS' 3 +6097 'IST' 3 +6098 'ITA' 3 +6099 'ITE' 3 +6100 'ITH' 3 +6101 'ITS' 3 +6102 'ITT' 3 +6103 'ITY' 3 +6104 'IUM' 3 +6105 'IVE' 3 +6106 'IZE' 3 +6107 'Ice' 3 +6108 'Ich' 3 +6109 'Ide' 3 +6110 'Ids' 3 +6111 'Idx' 3 +6112 'Ign' 3 +6113 'Ill' 3 +6114 'Img' 3 +6115 'Imm' 3 +6116 'Imp' 3 +6117 'Inc' 3 +6118 'Ind' 3 +6119 'Inf' 3 +6120 'Ing' 3 +6121 'Ini' 3 +6122 'Ins' 3 +6123 'Int' 3 +6124 'Inv' 3 +6125 'Ion' 3 +6126 'Isa' 3 +6127 'Isn' 3 +6128 'Iso' 3 +6129 'Iss' 3 +6130 'Its' 3 +6131 'JOB' 3 +6132 'JPG' 3 +6133 'Jac' 3 +6134 'Jam' 3 +6135 'Jan' 3 +6136 'Jar' 3 +6137 'Jay' 3 +6138 'Jen' 3 +6139 'Jer' 3 +6140 'Jet' 3 +6141 'Jim' 3 +6142 'Job' 3 +6143 'Joe' 3 +6144 'Joh' 3 +6145 'Jon' 3 +6146 'Jos' 3 +6147 'Joy' 3 +6148 'Jud' 3 +6149 'Jul' 3 +6150 'Jun' 3 +6151 'KEN' 3 +6152 'KER' 3 +6153 'KEY' 3 +6154 'Kal' 3 +6155 'Kam' 3 +6156 'Kar' 3 +6157 'Kat' 3 +6158 'Kay' 3 +6159 'Ken' 3 +6160 'Ker' 3 +6161 'Key' 3 +6162 'Kim' 3 +6163 'Kin' 3 +6164 'Kir' 3 +6165 'Kit' 3 +6166 'Kon' 3 +6167 'LAB' 3 +6168 'LAN' 3 +6169 'LAR' 3 +6170 'LAS' 3 +6171 'LAT' 3 +6172 'LAY' 3 +6173 'LED' 3 +6174 'LEN' 3 +6175 'LER' 3 +6176 'LES' 3 +6177 'LET' 3 +6178 'LEV' 3 +6179 'LEX' 3 +6180 'LEY' 3 +6181 'LIB' 3 +6182 'LIN' 3 +6183 'LOB' 3 +6184 'LOC' 3 +6185 'LOG' 3 +6186 'LOS' 3 +6187 'LOW' 3 +6188 'Lab' 3 +6189 'Lag' 3 +6190 'Lam' 3 +6191 'Lap' 3 +6192 'Lar' 3 +6193 'Las' 3 +6194 'Lat' 3 +6195 'Law' 3 +6196 'Lay' 3 +6197 'Lbl' 3 +6198 'Lee' 3 +6199 'Leg' 3 +6200 'Len' 3 +6201 'Les' 3 +6202 'Let' 3 +6203 'Lev' 3 +6204 'Lew' 3 +6205 'Lex' 3 +6206 'Lib' 3 +6207 'Lic' 3 +6208 'Lie' 3 +6209 'Lif' 3 +6210 'Lik' 3 +6211 'Lim' 3 +6212 'Lin' 3 +6213 'Lip' 3 +6214 'Lit' 3 +6215 'Lng' 3 +6216 'Loc' 3 +6217 'Log' 3 +6218 'Lon' 3 +6219 'Los' 3 +6220 'Lot' 3 +6221 'Lou' 3 +6222 'Low' 3 +6223 'Lua' 3 +6224 'Luc' 3 +6225 'Lux' 3 +6226 'MAC' 3 +6227 'MAG' 3 +6228 'MAL' 3 +6229 'MAN' 3 +6230 'MAP' 3 +6231 'MAR' 3 +6232 'MAS' 3 +6233 'MAT' 3 +6234 'MAX' 3 +6235 'MED' 3 +6236 'MEM' 3 +6237 'MEN' 3 +6238 'MER' 3 +6239 'MES' 3 +6240 'MET' 3 +6241 'MHz' 3 +6242 'MIC' 3 +6243 'MIN' 3 +6244 'MIS' 3 +6245 'MIT' 3 +6246 'MIX' 3 +6247 'MLE' 3 +6248 'MLP' 3 +6249 'MOD' 3 +6250 'MON' 3 +6251 'MOS' 3 +6252 'MOV' 3 +6253 'MPI' 3 +6254 'MPL' 3 +6255 'MRI' 3 +6256 'MSC' 3 +6257 'MSE' 3 +6258 'MSG' 3 +6259 'Mac' 3 +6260 'Mad' 3 +6261 'Mag' 3 +6262 'Mah' 3 +6263 'Mal' 3 +6264 'Man' 3 +6265 'Map' 3 +6266 'Mar' 3 +6267 'Mas' 3 +6268 'Mat' 3 +6269 'Max' 3 +6270 'May' 3 +6271 'McC' 3 +6272 'Med' 3 +6273 'Meg' 3 +6274 'Mel' 3 +6275 'Mem' 3 +6276 'Men' 3 +6277 'Mer' 3 +6278 'Mes' 3 +6279 'Met' 3 +6280 'Mex' 3 +6281 'Mgr' 3 +6282 'Mic' 3 +6283 'Mid' 3 +6284 'Mil' 3 +6285 'Min' 3 +6286 'Mir' 3 +6287 'Mis' 3 +6288 'Mit' 3 +6289 'Mix' 3 +6290 'Mob' 3 +6291 'Mod' 3 +6292 'Moh' 3 +6293 'Mol' 3 +6294 'Mom' 3 +6295 'Mon' 3 +6296 'Mor' 3 +6297 'Mot' 3 +6298 'Mov' 3 +6299 'Mrs' 3 +6300 'Msg' 3 +6301 'Mul' 3 +6302 'Mur' 3 +6303 'Mus' 3 +6304 'Mut' 3 +6305 'Mvc' 3 +6306 'NAL' 3 +6307 'NAM' 3 +6308 'NAS' 3 +6309 'NAT' 3 +6310 'NBC' 3 +6311 'NEL' 3 +6312 'NER' 3 +6313 'NES' 3 +6314 'NET' 3 +6315 'NEW' 3 +6316 'NON' 3 +6317 'NOR' 3 +6318 'NOT' 3 +6319 'NOW' 3 +6320 'NPC' 3 +6321 'NUM' 3 +6322 'NaN' 3 +6323 'Nam' 3 +6324 'Nan' 3 +6325 'Nat' 3 +6326 'Nav' 3 +6327 'Neg' 3 +6328 'Net' 3 +6329 'New' 3 +6330 'Nic' 3 +6331 'Nik' 3 +6332 'Nil' 3 +6333 'Nit' 3 +6334 'Nom' 3 +6335 'Non' 3 +6336 'Nor' 3 +6337 'Nos' 3 +6338 'Not' 3 +6339 'Nov' 3 +6340 'Now' 3 +6341 'Num' 3 +6342 'OBJ' 3 +6343 'OCI' 3 +6344 'OCK' 3 +6345 'OCT' 3 +6346 'ODE' 3 +6347 'ODO' 3 +6348 'ODY' 3 +6349 'OFF' 3 +6350 'OID' 3 +6351 'OLD' 3 +6352 'OME' 3 +6353 'ONA' 3 +6354 'OND' 3 +6355 'ONE' 3 +6356 'ONG' 3 +6357 'ONS' 3 +6358 'ONT' 3 +6359 'OPS' 3 +6360 'OPT' 3 +6361 'ORA' 3 +6362 'ORD' 3 +6363 'ORE' 3 +6364 'ORG' 3 +6365 'ORK' 3 +6366 'ORM' 3 +6367 'ORN' 3 +6368 'ORS' 3 +6369 'ORT' 3 +6370 'ORY' 3 +6371 'OSE' 3 +6372 'OSS' 3 +6373 'OST' 3 +6374 'OTA' 3 +6375 'OTE' 3 +6376 'OTH' 3 +6377 'OTO' 3 +6378 'OTP' 3 +6379 'OTS' 3 +6380 'OTT' 3 +6381 'OUR' 3 +6382 'OUS' 3 +6383 'OUT' 3 +6384 'OVA' 3 +6385 'OVE' 3 +6386 'OWN' 3 +6387 'Obj' 3 +6388 'Obs' 3 +6389 'Occ' 3 +6390 'Oct' 3 +6391 'Off' 3 +6392 'Old' 3 +6393 'One' 3 +6394 'Ont' 3 +6395 'Opp' 3 +6396 'Ops' 3 +6397 'Opt' 3 +6398 'Ord' 3 +6399 'Org' 3 +6400 'Ori' 3 +6401 'Our' 3 +6402 'Out' 3 +6403 'Own' 3 +6404 'PAD' 3 +6405 'PAN' 3 +6406 'PAR' 3 +6407 'PAS' 3 +6408 'PAT' 3 +6409 'PBS' 3 +6410 'PCA' 3 +6411 'PCI' 3 +6412 'PCM' 3 +6413 'PCR' 3 +6414 'PDF' 3 +6415 'PED' 3 +6416 'PEG' 3 +6417 'PER' 3 +6418 'PET' 3 +6419 'PHA' 3 +6420 'PHP' 3 +6421 'PIC' 3 +6422 'PID' 3 +6423 'PIN' 3 +6424 'PIO' 3 +6425 'PIP' 3 +6426 'PLA' 3 +6427 'PLC' 3 +6428 'PLE' 3 +6429 'PNG' 3 +6430 'POL' 3 +6431 'POP' 3 +6432 'POR' 3 +6433 'POS' 3 +6434 'PRE' 3 +6435 'PRI' 3 +6436 'PRO' 3 +6437 'PTR' 3 +6438 'PUT' 3 +6439 'PWM' 3 +6440 'Pac' 3 +6441 'Pad' 3 +6442 'Pag' 3 +6443 'Pak' 3 +6444 'Pal' 3 +6445 'Pan' 3 +6446 'Pap' 3 +6447 'Par' 3 +6448 'Pas' 3 +6449 'Pat' 3 +6450 'Pay' 3 +6451 'Pdf' 3 +6452 'Ped' 3 +6453 'Pen' 3 +6454 'Per' 3 +6455 'Pet' 3 +6456 'Phi' 3 +6457 'Pic' 3 +6458 'Pie' 3 +6459 'Pin' 3 +6460 'Pix' 3 +6461 'Pod' 3 +6462 'Pol' 3 +6463 'Pop' 3 +6464 'Por' 3 +6465 'Pos' 3 +6466 'Pot' 3 +6467 'Pow' 3 +6468 'Pre' 3 +6469 'Pri' 3 +6470 'Pro' 3 +6471 'Psi' 3 +6472 'Ptr' 3 +6473 'Pub' 3 +6474 'Pur' 3 +6475 'Put' 3 +6476 'QUE' 3 +6477 'Qty' 3 +6478 'Que' 3 +6479 'Qui' 3 +6480 'RAD' 3 +6481 'RAL' 3 +6482 'RAM' 3 +6483 'RAN' 3 +6484 'RAW' 3 +6485 'RAY' 3 +6486 'REC' 3 +6487 'RED' 3 +6488 'REE' 3 +6489 'REF' 3 +6490 'REG' 3 +6491 'REL' 3 +6492 'REM' 3 +6493 'REN' 3 +6494 'REP' 3 +6495 'REQ' 3 +6496 'RES' 3 +6497 'RET' 3 +6498 'RFC' 3 +6499 'RGB' 3 +6500 'RIC' 3 +6501 'RIX' 3 +6502 'RMS' 3 +6503 'RNA' 3 +6504 'RNN' 3 +6505 'ROC' 3 +6506 'ROI' 3 +6507 'ROL' 3 +6508 'ROM' 3 +6509 'RON' 3 +6510 'ROP' 3 +6511 'ROS' 3 +6512 'ROT' 3 +6513 'ROW' 3 +6514 'RPC' 3 +6515 'RSA' 3 +6516 'RSS' 3 +6517 'RTC' 3 +6518 'RUN' 3 +6519 'Rab' 3 +6520 'Rad' 3 +6521 'Ram' 3 +6522 'Rat' 3 +6523 'Raw' 3 +6524 'Ray' 3 +6525 'Rec' 3 +6526 'Red' 3 +6527 'Ref' 3 +6528 'Reg' 3 +6529 'Rel' 3 +6530 'Rem' 3 +6531 'Ren' 3 +6532 'Rep' 3 +6533 'Req' 3 +6534 'Res' 3 +6535 'Ret' 3 +6536 'Rev' 3 +6537 'Rew' 3 +6538 'Ric' 3 +6539 'Rob' 3 +6540 'Rod' 3 +6541 'Rol' 3 +6542 'Rom' 3 +6543 'Ron' 3 +6544 'Ros' 3 +6545 'Rot' 3 +6546 'Row' 3 +6547 'Roy' 3 +6548 'Rub' 3 +6549 'Run' 3 +6550 'Ré' 3 +6551 'SAM' 3 +6552 'SAN' 3 +6553 'SAT' 3 +6554 'SCH' 3 +6555 'SCI' 3 +6556 'SCO' 3 +6557 'SCR' 3 +6558 'SDK' 3 +6559 'SDL' 3 +6560 'SEC' 3 +6561 'SED' 3 +6562 'SEE' 3 +6563 'SEG' 3 +6564 'SEL' 3 +6565 'SEM' 3 +6566 'SEP' 3 +6567 'SEQ' 3 +6568 'SER' 3 +6569 'SET' 3 +6570 'SHA' 3 +6571 'SID' 3 +6572 'SIG' 3 +6573 'SIM' 3 +6574 'SMS' 3 +6575 'SNP' 3 +6576 'SOC' 3 +6577 'SOL' 3 +6578 'SON' 3 +6579 'SPE' 3 +6580 'SPI' 3 +6581 'SQL' 3 +6582 'SRC' 3 +6583 'SSH' 3 +6584 'SSL' 3 +6585 'STA' 3 +6586 'STD' 3 +6587 'STE' 3 +6588 'STM' 3 +6589 'STR' 3 +6590 'STS' 3 +6591 'SUB' 3 +6592 'SUM' 3 +6593 'SUP' 3 +6594 'SUR' 3 +6595 'SVG' 3 +6596 'SYS' 3 +6597 'Sab' 3 +6598 'Sac' 3 +6599 'Sad' 3 +6600 'Saf' 3 +6601 'Sal' 3 +6602 'Sam' 3 +6603 'San' 3 +6604 'Sar' 3 +6605 'Sat' 3 +6606 'Sav' 3 +6607 'Say' 3 +6608 'Sch' 3 +6609 'Sci' 3 +6610 'Sdk' 3 +6611 'Sea' 3 +6612 'Sec' 3 +6613 'See' 3 +6614 'Seg' 3 +6615 'Sel' 3 +6616 'Sem' 3 +6617 'Sen' 3 +6618 'Sep' 3 +6619 'Seq' 3 +6620 'Ser' 3 +6621 'Set' 3 +6622 'Sex' 3 +6623 'Sha' 3 +6624 'She' 3 +6625 'Sid' 3 +6626 'Sig' 3 +6627 'Sil' 3 +6628 'Sim' 3 +6629 'Sin' 3 +6630 'Sir' 3 +6631 'Sit' 3 +6632 'Six' 3 +6633 'Sky' 3 +6634 'Soc' 3 +6635 'Sol' 3 +6636 'Son' 3 +6637 'Sou' 3 +6638 'Spe' 3 +6639 'Spl' 3 +6640 'Spr' 3 +6641 'Spy' 3 +6642 'Sql' 3 +6643 'Squ' 3 +6644 'Src' 3 +6645 'Sta' 3 +6646 'Std' 3 +6647 'Ste' 3 +6648 'Sto' 3 +6649 'Str' 3 +6650 'Sty' 3 +6651 'Sub' 3 +6652 'Suc' 3 +6653 'Sud' 3 +6654 'Sum' 3 +6655 'Sun' 3 +6656 'Sup' 3 +6657 'Sur' 3 +6658 'Sus' 3 +6659 'Sym' 3 +6660 'Syn' 3 +6661 'Sys' 3 +6662 'TAB' 3 +6663 'TAG' 3 +6664 'TCP' 3 +6665 'TED' 3 +6666 'TEM' 3 +6667 'TER' 3 +6668 'TES' 3 +6669 'TEX' 3 +6670 'THE' 3 +6671 'TIM' 3 +6672 'TLS' 3 +6673 'TMP' 3 +6674 'TON' 3 +6675 'TOP' 3 +6676 'TOR' 3 +6677 'TRA' 3 +6678 'TRY' 3 +6679 'Tab' 3 +6680 'Tag' 3 +6681 'Tai' 3 +6682 'Tak' 3 +6683 'Tal' 3 +6684 'Tam' 3 +6685 'Tan' 3 +6686 'Tap' 3 +6687 'Tar' 3 +6688 'Tax' 3 +6689 'TeV' 3 +6690 'TeX' 3 +6691 'Ted' 3 +6692 'Tek' 3 +6693 'Tel' 3 +6694 'Tem' 3 +6695 'Ten' 3 +6696 'Ter' 3 +6697 'Tes' 3 +6698 'Tex' 3 +6699 'The' 3 +6700 'Thu' 3 +6701 'Tim' 3 +6702 'Tip' 3 +6703 'Tit' 3 +6704 'Tmp' 3 +6705 'Tok' 3 +6706 'Tom' 3 +6707 'Ton' 3 +6708 'Too' 3 +6709 'Top' 3 +6710 'Tor' 3 +6711 'Tot' 3 +6712 'Toy' 3 +6713 'Tra' 3 +6714 'Tre' 3 +6715 'Tri' 3 +6716 'Tro' 3 +6717 'Try' 3 +6718 'Tue' 3 +6719 'Tur' 3 +6720 'Two' 3 +6721 'Txt' 3 +6722 'Typ' 3 +6723 'UAL' 3 +6724 'UCK' 3 +6725 'UCT' 3 +6726 'UDP' 3 +6727 'UES' 3 +6728 'UFF' 3 +6729 'UGH' 3 +6730 'UID' 3 +6731 'UIT' 3 +6732 'ULD' 3 +6733 'ULE' 3 +6734 'ULL' 3 +6735 'ULT' 3 +6736 'UME' 3 +6737 'UMN' 3 +6738 'UMP' 3 +6739 'UNC' 3 +6740 'UND' 3 +6741 'UNE' 3 +6742 'UNK' 3 +6743 'UNT' 3 +6744 'URA' 3 +6745 'URE' 3 +6746 'URI' 3 +6747 'URL' 3 +6748 'URN' 3 +6749 'URS' 3 +6750 'USA' 3 +6751 'USB' 3 +6752 'USD' 3 +6753 'USE' 3 +6754 'USH' 3 +6755 'USS' 3 +6756 'UST' 3 +6757 'UTC' 3 +6758 'UTE' 3 +6759 'UTF' 3 +6760 'UTH' 3 +6761 'Uid' 3 +6762 'Ult' 3 +6763 'Und' 3 +6764 'Uni' 3 +6765 'Uns' 3 +6766 'Uri' 3 +6767 'Url' 3 +6768 'Use' 3 +6769 'Usu' 3 +6770 'VAL' 3 +6771 'VAR' 3 +6772 'VED' 3 +6773 'VEL' 3 +6774 'VEN' 3 +6775 'VER' 3 +6776 'VES' 3 +6777 'VIC' 3 +6778 'VID' 3 +6779 'VIE' 3 +6780 'VII' 3 +6781 'VIS' 3 +6782 'VOL' 3 +6783 'VPN' 3 +6784 'Vac' 3 +6785 'Val' 3 +6786 'Van' 3 +6787 'Var' 3 +6788 'Vec' 3 +6789 'Vel' 3 +6790 'Ven' 3 +6791 'Ver' 3 +6792 'Via' 3 +6793 'Vin' 3 +6794 'Vir' 3 +6795 'Vis' 3 +6796 'Vol' 3 +6797 'WAR' 3 +6798 'WAY' 3 +6799 'WEB' 3 +6800 'WER' 3 +6801 'WHO' 3 +6802 'WID' 3 +6803 'WIN' 3 +6804 'WOR' 3 +6805 'Wal' 3 +6806 'War' 3 +6807 'Was' 3 +6808 'Wat' 3 +6809 'Way' 3 +6810 'Web' 3 +6811 'Wed' 3 +6812 'Wel' 3 +6813 'Who' 3 +6814 'Why' 3 +6815 'Wik' 3 +6816 'Wil' 3 +6817 'Win' 3 +6818 'Wol' 3 +6819 'Won' 3 +6820 'Wow' 3 +6821 'XML' 3 +6822 'XXX' 3 +6823 'XYZ' 3 +6824 'Xiv' 3 +6825 'Xml' 3 +6826 'YES' 3 +6827 'YLE' 3 +6828 'YOU' 3 +6829 'YPE' 3 +6830 'YYY' 3 +6831 'Yes' 3 +6832 'Yet' 3 +6833 'You' 3 +6834 'ZIP' 3 +6835 'Zen' 3 +6836 'Zip' 3 +6837 "['_" 3 +6838 '[:,' 3 +6839 '[:-' 3 +6840 '[:]' 3 +6841 "[['" 3 +6842 '[])' 3 +6843 '[],' 3 +6844 '[]{' 3 +6845 '\\""' 3 +6846 '\\",' 3 +6847 '\\":' 3 +6848 '\\">' 3 +6849 '\\\\\\' 3 +6850 '\\}$' 3 +6851 ']")' 3 +6852 ']",' 3 +6853 "]'," 3 +6854 '](#' 3 +6855 ']))' 3 +6856 ']),' 3 +6857 ']).' 3 +6858 ']):' 3 +6859 ']);' 3 +6860 '],[' 3 +6861 ']->' 3 +6862 '].[' 3 +6863 ']="' 3 +6864 ']["' 3 +6865 "]['" 3 +6866 ']\\\\' 3 +6867 ']])' 3 +6868 ']],' 3 +6869 ']];' 3 +6870 ']},' 3 +6871 '^{+' 3 +6872 '^{-' 3 +6873 '^{\\' 3 +6874 '_("' 3 +6875 "_('" 3 +6876 '_->' 3 +6877 '__(' 3 +6878 '__)' 3 +6879 '__,' 3 +6880 '__.' 3 +6881 '___' 3 +6882 '_{\\' 3 +6883 '`).' 3 +6884 '```' 3 +6885 'aaa' 3 +6886 'aab' 3 +6887 'aan' 3 +6888 'aar' 3 +6889 'aba' 3 +6890 'abb' 3 +6891 'abc' 3 +6892 'abd' 3 +6893 'abe' 3 +6894 'abi' 3 +6895 'abl' 3 +6896 'abo' 3 +6897 'abr' 3 +6898 'abs' 3 +6899 'aby' 3 +6900 'aca' 3 +6901 'acc' 3 +6902 'ace' 3 +6903 'ach' 3 +6904 'aci' 3 +6905 'ack' 3 +6906 'acl' 3 +6907 'aco' 3 +6908 'acs' 3 +6909 'act' 3 +6910 'acy' 3 +6911 'ada' 3 +6912 'adb' 3 +6913 'add' 3 +6914 'ade' 3 +6915 'adh' 3 +6916 'adi' 3 +6917 'adj' 3 +6918 'adm' 3 +6919 'ado' 3 +6920 'adr' 3 +6921 'ads' 3 +6922 'adt' 3 +6923 'adu' 3 +6924 'adv' 3 +6925 'ady' 3 +6926 'aea' 3 +6927 'ael' 3 +6928 'aes' 3 +6929 'afa' 3 +6930 'afe' 3 +6931 'aff' 3 +6932 'afi' 3 +6933 'aft' 3 +6934 'aga' 3 +6935 'age' 3 +6936 'agg' 3 +6937 'agh' 3 +6938 'agi' 3 +6939 'agn' 3 +6940 'ago' 3 +6941 'agr' 3 +6942 'ags' 3 +6943 'agt' 3 +6944 'agu' 3 +6945 'agy' 3 +6946 'aha' 3 +6947 'ahi' 3 +6948 'ahl' 3 +6949 'ahn' 3 +6950 'aho' 3 +6951 'ahr' 3 +6952 'ahu' 3 +6953 'aic' 3 +6954 'aid' 3 +6955 'ail' 3 +6956 'aim' 3 +6957 'ain' 3 +6958 'air' 3 +6959 'ais' 3 +6960 'ait' 3 +6961 'aja' 3 +6962 'aje' 3 +6963 'aji' 3 +6964 'ajo' 3 +6965 'aju' 3 +6966 'aka' 3 +6967 'ake' 3 +6968 'akh' 3 +6969 'aki' 3 +6970 'akk' 3 +6971 'ako' 3 +6972 'aks' 3 +6973 'akt' 3 +6974 'aku' 3 +6975 'aky' 3 +6976 'ala' 3 +6977 'alc' 3 +6978 'ald' 3 +6979 'ale' 3 +6980 'alf' 3 +6981 'alg' 3 +6982 'ali' 3 +6983 'alk' 3 +6984 'all' 3 +6985 'alm' 3 +6986 'alo' 3 +6987 'als' 3 +6988 'alt' 3 +6989 'alu' 3 +6990 'aly' 3 +6991 'ama' 3 +6992 'amb' 3 +6993 'amd' 3 +6994 'ame' 3 +6995 'ami' 3 +6996 'aml' 3 +6997 'amm' 3 +6998 'amo' 3 +6999 'amp' 3 +7000 'ams' 3 +7001 'amt' 3 +7002 'amy' 3 +7003 'ana' 3 +7004 'anc' 3 +7005 'and' 3 +7006 'ane' 3 +7007 'ang' 3 +7008 'anh' 3 +7009 'ani' 3 +7010 'anj' 3 +7011 'ank' 3 +7012 'ann' 3 +7013 'ano' 3 +7014 'ans' 3 +7015 'ant' 3 +7016 'anu' 3 +7017 'any' 3 +7018 'anz' 3 +7019 'aos' 3 +7020 'apa' 3 +7021 'ape' 3 +7022 'aph' 3 +7023 'api' 3 +7024 'apk' 3 +7025 'apo' 3 +7026 'app' 3 +7027 'apr' 3 +7028 'aps' 3 +7029 'apt' 3 +7030 'apy' 3 +7031 'aqu' 3 +7032 'ara' 3 +7033 'arb' 3 +7034 'arc' 3 +7035 'ard' 3 +7036 'are' 3 +7037 'arf' 3 +7038 'arg' 3 +7039 'ari' 3 +7040 'ark' 3 +7041 'arl' 3 +7042 'arm' 3 +7043 'arn' 3 +7044 'aro' 3 +7045 'arp' 3 +7046 'arr' 3 +7047 'ars' 3 +7048 'art' 3 +7049 'aru' 3 +7050 'ary' 3 +7051 'asa' 3 +7052 'asc' 3 +7053 'ase' 3 +7054 'ash' 3 +7055 'asi' 3 +7056 'ask' 3 +7057 'asm' 3 +7058 'aso' 3 +7059 'asp' 3 +7060 'ass' 3 +7061 'ast' 3 +7062 'asu' 3 +7063 'asy' 3 +7064 'asz' 3 +7065 'ata' 3 +7066 'ate' 3 +7067 'ath' 3 +7068 'ati' 3 +7069 'atl' 3 +7070 'ato' 3 +7071 'atr' 3 +7072 'ats' 3 +7073 'att' 3 +7074 'atu' 3 +7075 'aty' 3 +7076 'atz' 3 +7077 'auc' 3 +7078 'aud' 3 +7079 'auf' 3 +7080 'aug' 3 +7081 'aul' 3 +7082 'aur' 3 +7083 'aus' 3 +7084 'aut' 3 +7085 'aux' 3 +7086 'ava' 3 +7087 'ave' 3 +7088 'avg' 3 +7089 'avi' 3 +7090 'avo' 3 +7091 'avy' 3 +7092 'awa' 3 +7093 'awi' 3 +7094 'awk' 3 +7095 'awn' 3 +7096 'aws' 3 +7097 'awt' 3 +7098 'axe' 3 +7099 'axy' 3 +7100 'aya' 3 +7101 'aye' 3 +7102 'ays' 3 +7103 'aza' 3 +7104 'aze' 3 +7105 'azi' 3 +7106 'azo' 3 +7107 'azu' 3 +7108 'azy' 3 +7109 'azz' 3 +7110 'añ' 3 +7111 'ać' 3 +7112 'ał' 3 +7113 'aż' 3 +7114 'bab' 3 +7115 'bac' 3 +7116 'bad' 3 +7117 'bag' 3 +7118 'bah' 3 +7119 'bai' 3 +7120 'bak' 3 +7121 'bal' 3 +7122 'bam' 3 +7123 'ban' 3 +7124 'bar' 3 +7125 'bas' 3 +7126 'bat' 3 +7127 'bau' 3 +7128 'bay' 3 +7129 'baz' 3 +7130 'bbc' 3 +7131 'bbe' 3 +7132 'bdd' 3 +7133 'bec' 3 +7134 'bed' 3 +7135 'bee' 3 +7136 'bef' 3 +7137 'beg' 3 +7138 'beh' 3 +7139 'bei' 3 +7140 'bek' 3 +7141 'bel' 3 +7142 'ben' 3 +7143 'ber' 3 +7144 'bes' 3 +7145 'bet' 3 +7146 'bey' 3 +7147 'bfd' 3 +7148 'bia' 3 +7149 'bib' 3 +7150 'bic' 3 +7151 'bid' 3 +7152 'bie' 3 +7153 'big' 3 +7154 'bil' 3 +7155 'bin' 3 +7156 'bio' 3 +7157 'bir' 3 +7158 'bis' 3 +7159 'bit' 3 +7160 'biz' 3 +7161 'bla' 3 +7162 'ble' 3 +7163 'blk' 3 +7164 'blo' 3 +7165 'blr' 3 +7166 'bly' 3 +7167 'bmp' 3 +7168 'bnb' 3 +7169 'boa' 3 +7170 'bob' 3 +7171 'bol' 3 +7172 'bon' 3 +7173 'boo' 3 +7174 'bor' 3 +7175 'bos' 3 +7176 'bot' 3 +7177 'bow' 3 +7178 'box' 3 +7179 'boy' 3 +7180 'bps' 3 +7181 'bra' 3 +7182 'bre' 3 +7183 'bro' 3 +7184 'bru' 3 +7185 'bsd' 3 +7186 'bst' 3 +7187 'btn' 3 +7188 'bud' 3 +7189 'buf' 3 +7190 'bug' 3 +7191 'bul' 3 +7192 'bum' 3 +7193 'bur' 3 +7194 'bus' 3 +7195 'but' 3 +7196 'buy' 3 +7197 'bye' 3 +7198 'bys' 3 +7199 'bé' 3 +7200 'bü' 3 +7201 'bě' 3 +7202 'cab' 3 +7203 'cac' 3 +7204 'cad' 3 +7205 'cal' 3 +7206 'cam' 3 +7207 'can' 3 +7208 'cap' 3 +7209 'car' 3 +7210 'cas' 3 +7211 'cat' 3 +7212 'cca' 3 +7213 'ccc' 3 +7214 'cci' 3 +7215 'cco' 3 +7216 'cdf' 3 +7217 'cdn' 3 +7218 'cea' 3 +7219 'ced' 3 +7220 'cel' 3 +7221 'cem' 3 +7222 'cen' 3 +7223 'cep' 3 +7224 'cer' 3 +7225 'ces' 3 +7226 'ceu' 3 +7227 'cfg' 3 +7228 'cgi' 3 +7229 'cha' 3 +7230 'che' 3 +7231 'chi' 3 +7232 'chk' 3 +7233 'chl' 3 +7234 'chn' 3 +7235 'cho' 3 +7236 'chr' 3 +7237 'chs' 3 +7238 'cht' 3 +7239 'chu' 3 +7240 'chy' 3 +7241 'cia' 3 +7242 'cid' 3 +7243 'cie' 3 +7244 'cig' 3 +7245 'cii' 3 +7246 'cil' 3 +7247 'cin' 3 +7248 'cio' 3 +7249 'cip' 3 +7250 'cir' 3 +7251 'cis' 3 +7252 'cit' 3 +7253 'cke' 3 +7254 'cki' 3 +7255 'cko' 3 +7256 'cks' 3 +7257 'cla' 3 +7258 'cle' 3 +7259 'clf' 3 +7260 'cli' 3 +7261 'clk' 3 +7262 'clo' 3 +7263 'cls' 3 +7264 'cmb' 3 +7265 'cmd' 3 +7266 'cmp' 3 +7267 'cms' 3 +7268 'cnt' 3 +7269 'cod' 3 +7270 'coe' 3 +7271 'col' 3 +7272 'com' 3 +7273 'con' 3 +7274 'cop' 3 +7275 'cor' 3 +7276 'cos' 3 +7277 'cot' 3 +7278 'cou' 3 +7279 'cov' 3 +7280 'cow' 3 +7281 'cox' 3 +7282 'cpp' 3 +7283 'cpu' 3 +7284 'cpy' 3 +7285 'cra' 3 +7286 'crc' 3 +7287 'cre' 3 +7288 'cri' 3 +7289 'cro' 3 +7290 'cru' 3 +7291 'cry' 3 +7292 'csr' 3 +7293 'css' 3 +7294 'csv' 3 +7295 'cta' 3 +7296 'ctl' 3 +7297 'ctr' 3 +7298 'ctu' 3 +7299 'ctx' 3 +7300 'cub' 3 +7301 'cue' 3 +7302 'cul' 3 +7303 'cum' 3 +7304 'cup' 3 +7305 'cur' 3 +7306 'cus' 3 +7307 'cut' 3 +7308 'cwd' 3 +7309 'czy' 3 +7310 'cé' 3 +7311 'cí' 3 +7312 'dac' 3 +7313 'dad' 3 +7314 'dag' 3 +7315 'dal' 3 +7316 'dam' 3 +7317 'dan' 3 +7318 'dao' 3 +7319 'dap' 3 +7320 'dar' 3 +7321 'das' 3 +7322 'dat' 3 +7323 'dav' 3 +7324 'day' 3 +7325 'dbc' 3 +7326 'dbg' 3 +7327 'dbl' 3 +7328 'ddd' 3 +7329 'dea' 3 +7330 'deb' 3 +7331 'dec' 3 +7332 'ded' 3 +7333 'dee' 3 +7334 'def' 3 +7335 'deg' 3 +7336 'dek' 3 +7337 'del' 3 +7338 'dem' 3 +7339 'den' 3 +7340 'dep' 3 +7341 'der' 3 +7342 'des' 3 +7343 'det' 3 +7344 'dev' 3 +7345 'dex' 3 +7346 'dez' 3 +7347 'dfs' 3 +7348 'dia' 3 +7349 'dic' 3 +7350 'did' 3 +7351 'die' 3 +7352 'dif' 3 +7353 'dig' 3 +7354 'dil' 3 +7355 'dim' 3 +7356 'din' 3 +7357 'dio' 3 +7358 'dip' 3 +7359 'dir' 3 +7360 'dis' 3 +7361 'dit' 3 +7362 'div' 3 +7363 'dle' 3 +7364 'dll' 3 +7365 'dna' 3 +7366 'dob' 3 +7367 'doc' 3 +7368 'dof' 3 +7369 'dog' 3 +7370 'doi' 3 +7371 'dol' 3 +7372 'dom' 3 +7373 'don' 3 +7374 'dor' 3 +7375 'dos' 3 +7376 'dot' 3 +7377 'dou' 3 +7378 'dpi' 3 +7379 'dra' 3 +7380 'dre' 3 +7381 'dri' 3 +7382 'dro' 3 +7383 'drv' 3 +7384 'dry' 3 +7385 'dst' 3 +7386 'dtd' 3 +7387 'duc' 3 +7388 'due' 3 +7389 'dup' 3 +7390 'dur' 3 +7391 'dyn' 3 +7392 'ead' 3 +7393 'eah' 3 +7394 'ean' 3 +7395 'ear' 3 +7396 'eas' 3 +7397 'eat' 3 +7398 'eau' 3 +7399 'eba' 3 +7400 'ebb' 3 +7401 'eca' 3 +7402 'ecc' 3 +7403 'ecd' 3 +7404 'ece' 3 +7405 'ech' 3 +7406 'eck' 3 +7407 'ecl' 3 +7408 'eco' 3 +7409 'ecs' 3 +7410 'ect' 3 +7411 'eda' 3 +7412 'edd' 3 +7413 'ede' 3 +7414 'edi' 3 +7415 'edo' 3 +7416 'eds' 3 +7417 'edu' 3 +7418 'edy' 3 +7419 'eed' 3 +7420 'een' 3 +7421 'eer' 3 +7422 'ees' 3 +7423 'efe' 3 +7424 'eff' 3 +7425 'eft' 3 +7426 'ega' 3 +7427 'egg' 3 +7428 'ego' 3 +7429 'egr' 3 +7430 'egu' 3 +7431 'eil' 3 +7432 'ein' 3 +7433 'eka' 3 +7434 'eki' 3 +7435 'eks' 3 +7436 'ekt' 3 +7437 'ela' 3 +7438 'eld' 3 +7439 'ele' 3 +7440 'elf' 3 +7441 'eli' 3 +7442 'ell' 3 +7443 'elm' 3 +7444 'eln' 3 +7445 'elo' 3 +7446 'elp' 3 +7447 'els' 3 +7448 'elt' 3 +7449 'elu' 3 +7450 'ely' 3 +7451 'ema' 3 +7452 'emb' 3 +7453 'eme' 3 +7454 'emi' 3 +7455 'emn' 3 +7456 'emo' 3 +7457 'emp' 3 +7458 'ems' 3 +7459 'emu' 3 +7460 'emy' 3 +7461 'ena' 3 +7462 'enc' 3 +7463 'end' 3 +7464 'ene' 3 +7465 'enf' 3 +7466 'eng' 3 +7467 'enh' 3 +7468 'eni' 3 +7469 'enk' 3 +7470 'enn' 3 +7471 'eno' 3 +7472 'ens' 3 +7473 'ent' 3 +7474 'enu' 3 +7475 'env' 3 +7476 'eny' 3 +7477 'enz' 3 +7478 'eof' 3 +7479 'eon' 3 +7480 'eor' 3 +7481 'eph' 3 +7482 'epi' 3 +7483 'eps' 3 +7484 'ept' 3 +7485 'eqn' 3 +7486 'equ' 3 +7487 'era' 3 +7488 'erb' 3 +7489 'erc' 3 +7490 'erd' 3 +7491 'ere' 3 +7492 'erg' 3 +7493 'eri' 3 +7494 'erk' 3 +7495 'erm' 3 +7496 'ern' 3 +7497 'ero' 3 +7498 'erp' 3 +7499 'err' 3 +7500 'ers' 3 +7501 'ert' 3 +7502 'erv' 3 +7503 'ery' 3 +7504 'esa' 3 +7505 'esc' 3 +7506 'ese' 3 +7507 'esh' 3 +7508 'esi' 3 +7509 'esk' 3 +7510 'eso' 3 +7511 'esp' 3 +7512 'ess' 3 +7513 'est' 3 +7514 'esy' 3 +7515 'eta' 3 +7516 'etc' 3 +7517 'ete' 3 +7518 'eth' 3 +7519 'eti' 3 +7520 'eto' 3 +7521 'etr' 3 +7522 'ets' 3 +7523 'ett' 3 +7524 'etu' 3 +7525 'ety' 3 +7526 'etz' 3 +7527 'eur' 3 +7528 'eus' 3 +7529 'eva' 3 +7530 'eve' 3 +7531 'evt' 3 +7532 'ews' 3 +7533 'exc' 3 +7534 'exe' 3 +7535 'exp' 3 +7536 'ext' 3 +7537 'eye' 3 +7538 'fab' 3 +7539 'fac' 3 +7540 'fal' 3 +7541 'fan' 3 +7542 'far' 3 +7543 'fas' 3 +7544 'fat' 3 +7545 'fav' 3 +7546 'fax' 3 +7547 'feb' 3 +7548 'fed' 3 +7549 'fee' 3 +7550 'fel' 3 +7551 'fem' 3 +7552 'fen' 3 +7553 'fer' 3 +7554 'fet' 3 +7555 'few' 3 +7556 'ffe' 3 +7557 'fff' 3 +7558 'ffi' 3 +7559 'fft' 3 +7560 'fib' 3 +7561 'fic' 3 +7562 'fid' 3 +7563 'fif' 3 +7564 'fig' 3 +7565 'fil' 3 +7566 'fin' 3 +7567 'fir' 3 +7568 'fit' 3 +7569 'fix' 3 +7570 'fld' 3 +7571 'fle' 3 +7572 'flo' 3 +7573 'flu' 3 +7574 'fly' 3 +7575 'fmt' 3 +7576 'fol' 3 +7577 'fon' 3 +7578 'foo' 3 +7579 'for' 3 +7580 'fos' 3 +7581 'fox' 3 +7582 'fra' 3 +7583 'fre' 3 +7584 'fri' 3 +7585 'frm' 3 +7586 'fro' 3 +7587 'fst' 3 +7588 'fte' 3 +7589 'ftp' 3 +7590 'fts' 3 +7591 'fty' 3 +7592 'ful' 3 +7593 'fun' 3 +7594 'fur' 3 +7595 'fut' 3 +7596 'fé' 3 +7597 'fø' 3 +7598 'fü' 3 +7599 'gae' 3 +7600 'gal' 3 +7601 'gam' 3 +7602 'gan' 3 +7603 'gap' 3 +7604 'gar' 3 +7605 'gas' 3 +7606 'gat' 3 +7607 'gay' 3 +7608 'gca' 3 +7609 'gcc' 3 +7610 'gcd' 3 +7611 'geb' 3 +7612 'ged' 3 +7613 'geh' 3 +7614 'gel' 3 +7615 'gem' 3 +7616 'gen' 3 +7617 'geo' 3 +7618 'geq' 3 +7619 'ger' 3 +7620 'ges' 3 +7621 'get' 3 +7622 'gew' 3 +7623 'gex' 3 +7624 'ght' 3 +7625 'gia' 3 +7626 'gid' 3 +7627 'gie' 3 +7628 'gif' 3 +7629 'gil' 3 +7630 'gin' 3 +7631 'gio' 3 +7632 'gis' 3 +7633 'git' 3 +7634 'gle' 3 +7635 'gly' 3 +7636 'gmt' 3 +7637 'gnu' 3 +7638 'god' 3 +7639 'gol' 3 +7640 'gom' 3 +7641 'gon' 3 +7642 'gor' 3 +7643 'gos' 3 +7644 'got' 3 +7645 'gov' 3 +7646 'gow' 3 +7647 'gpu' 3 +7648 'gra' 3 +7649 'gre' 3 +7650 'gro' 3 +7651 'grp' 3 +7652 'gru' 3 +7653 'gte' 3 +7654 'gtk' 3 +7655 'gua' 3 +7656 'gue' 3 +7657 'gui' 3 +7658 'gun' 3 +7659 'gut' 3 +7660 'hab' 3 +7661 'had' 3 +7662 'hai' 3 +7663 'hal' 3 +7664 'ham' 3 +7665 'han' 3 +7666 'hao' 3 +7667 'hap' 3 +7668 'har' 3 +7669 'has' 3 +7670 'hat' 3 +7671 'hav' 3 +7672 'haw' 3 +7673 'hay' 3 +7674 'haz' 3 +7675 'hdr' 3 +7676 'hea' 3 +7677 'hed' 3 +7678 'hee' 3 +7679 'hei' 3 +7680 'hel' 3 +7681 'hem' 3 +7682 'hen' 3 +7683 'hep' 3 +7684 'her' 3 +7685 'hes' 3 +7686 'het' 3 +7687 'hev' 3 +7688 'hew' 3 +7689 'hex' 3 +7690 'hey' 3 +7691 'hib' 3 +7692 'hic' 3 +7693 'hid' 3 +7694 'hig' 3 +7695 'hil' 3 +7696 'him' 3 +7697 'hin' 3 +7698 'hip' 3 +7699 'hir' 3 +7700 'his' 3 +7701 'hit' 3 +7702 'hma' 3 +7703 'hoc' 3 +7704 'hod' 3 +7705 'hoe' 3 +7706 'hof' 3 +7707 'hog' 3 +7708 'hol' 3 +7709 'hom' 3 +7710 'hon' 3 +7711 'hop' 3 +7712 'hor' 3 +7713 'hos' 3 +7714 'hot' 3 +7715 'hou' 3 +7716 'hov' 3 +7717 'how' 3 +7718 'hpp' 3 +7719 'hra' 3 +7720 'hta' 3 +7721 'hti' 3 +7722 'htm' 3 +7723 'htt' 3 +7724 'hua' 3 +7725 'hub' 3 +7726 'hue' 3 +7727 'hui' 3 +7728 'hum' 3 +7729 'hur' 3 +7730 'hus' 3 +7731 'hyd' 3 +7732 'hyp' 3 +7733 'há' 3 +7734 'hã' 3 +7735 'hä' 3 +7736 'hé' 3 +7737 'hö' 3 +7738 'iOS' 3 +7739 'iac' 3 +7740 'iae' 3 +7741 'iah' 3 +7742 'iak' 3 +7743 'ial' 3 +7744 'iam' 3 +7745 'ian' 3 +7746 'iao' 3 +7747 'iar' 3 +7748 'ias' 3 +7749 'iat' 3 +7750 'iaz' 3 +7751 'iba' 3 +7752 'ibe' 3 +7753 'ibi' 3 +7754 'ibo' 3 +7755 'ibr' 3 +7756 'ibu' 3 +7757 'ica' 3 +7758 'icc' 3 +7759 'ice' 3 +7760 'ich' 3 +7761 'ici' 3 +7762 'ick' 3 +7763 'icl' 3 +7764 'ico' 3 +7765 'ics' 3 +7766 'ict' 3 +7767 'icy' 3 +7768 'icz' 3 +7769 'ida' 3 +7770 'idd' 3 +7771 'ide' 3 +7772 'idi' 3 +7773 'idl' 3 +7774 'ido' 3 +7775 'ids' 3 +7776 'idx' 3 +7777 'idy' 3 +7778 'iec' 3 +7779 'ied' 3 +7780 'ief' 3 +7781 'ieg' 3 +7782 'iei' 3 +7783 'iej' 3 +7784 'iek' 3 +7785 'iel' 3 +7786 'iem' 3 +7787 'ien' 3 +7788 'ier' 3 +7789 'ies' 3 +7790 'iet' 3 +7791 'ieu' 3 +7792 'iev' 3 +7793 'iew' 3 +7794 'iez' 3 +7795 'ifa' 3 +7796 'ife' 3 +7797 'iff' 3 +7798 'ifi' 3 +7799 'ifs' 3 +7800 'ift' 3 +7801 'ify' 3 +7802 'iga' 3 +7803 'ige' 3 +7804 'igg' 3 +7805 'igh' 3 +7806 'igi' 3 +7807 'igl' 3 +7808 'igm' 3 +7809 'ign' 3 +7810 'igo' 3 +7811 'igr' 3 +7812 'igs' 3 +7813 'igt' 3 +7814 'igu' 3 +7815 'iii' 3 +7816 'ija' 3 +7817 'ije' 3 +7818 'iji' 3 +7819 'ijk' 3 +7820 'ijn' 3 +7821 'ijo' 3 +7822 'iju' 3 +7823 'ika' 3 +7824 'ike' 3 +7825 'ikh' 3 +7826 'iki' 3 +7827 'ikk' 3 +7828 'iko' 3 +7829 'iks' 3 +7830 'ikt' 3 +7831 'iku' 3 +7832 'ila' 3 +7833 'ild' 3 +7834 'ile' 3 +7835 'ili' 3 +7836 'ilk' 3 +7837 'ill' 3 +7838 'ilo' 3 +7839 'ils' 3 +7840 'ilt' 3 +7841 'ily' 3 +7842 'ima' 3 +7843 'imb' 3 +7844 'ime' 3 +7845 'img' 3 +7846 'imi' 3 +7847 'imm' 3 +7848 'imo' 3 +7849 'imp' 3 +7850 'ims' 3 +7851 'ina' 3 +7852 'inc' 3 +7853 'ind' 3 +7854 'ine' 3 +7855 'inf' 3 +7856 'ing' 3 +7857 'inh' 3 +7858 'ini' 3 +7859 'inj' 3 +7860 'ink' 3 +7861 'inn' 3 +7862 'ino' 3 +7863 'inp' 3 +7864 'ins' 3 +7865 'int' 3 +7866 'inu' 3 +7867 'inv' 3 +7868 'inx' 3 +7869 'iny' 3 +7870 'inz' 3 +7871 'iod' 3 +7872 'iol' 3 +7873 'iom' 3 +7874 'ion' 3 +7875 'iop' 3 +7876 'ior' 3 +7877 'ios' 3 +7878 'iot' 3 +7879 'iou' 3 +7880 'iov' 3 +7881 'iox' 3 +7882 'ipa' 3 +7883 'ipe' 3 +7884 'iph' 3 +7885 'ipl' 3 +7886 'ipo' 3 +7887 'ipp' 3 +7888 'ips' 3 +7889 'ipt' 3 +7890 'ipv' 3 +7891 'ipy' 3 +7892 'iqu' 3 +7893 'ira' 3 +7894 'irc' 3 +7895 'ird' 3 +7896 'ire' 3 +7897 'iri' 3 +7898 'irk' 3 +7899 'irl' 3 +7900 'irm' 3 +7901 'iro' 3 +7902 'irq' 3 +7903 'irs' 3 +7904 'irt' 3 +7905 'iry' 3 +7906 'isa' 3 +7907 'isc' 3 +7908 'isd' 3 +7909 'ise' 3 +7910 'isf' 3 +7911 'ish' 3 +7912 'isi' 3 +7913 'isk' 3 +7914 'isl' 3 +7915 'ism' 3 +7916 'iso' 3 +7917 'isp' 3 +7918 'iss' 3 +7919 'ist' 3 +7920 'isu' 3 +7921 'isy' 3 +7922 'isz' 3 +7923 'ita' 3 +7924 'ite' 3 +7925 'ith' 3 +7926 'iti' 3 +7927 'itm' 3 +7928 'ito' 3 +7929 'itr' 3 +7930 'its' 3 +7931 'itt' 3 +7932 'itu' 3 +7933 'ity' 3 +7934 'itz' 3 +7935 'ium' 3 +7936 'ius' 3 +7937 'iva' 3 +7938 'ive' 3 +7939 'ivi' 3 +7940 'ivo' 3 +7941 'ivy' 3 +7942 'ixa' 3 +7943 'ixo' 3 +7944 'iya' 3 +7945 'iza' 3 +7946 'ize' 3 +7947 'izi' 3 +7948 'izo' 3 +7949 'izu' 3 +7950 'izz' 3 +7951 'iß' 3 +7952 'ié' 3 +7953 'ië' 3 +7954 'ió' 3 +7955 'ią' 3 +7956 'ić' 3 +7957 'ič' 3 +7958 'ię' 3 +7959 'ił' 3 +7960 'iş' 3 +7961 'iš' 3 +7962 'jab' 3 +7963 'jac' 3 +7964 'jad' 3 +7965 'jah' 3 +7966 'jak' 3 +7967 'jal' 3 +7968 'jam' 3 +7969 'jan' 3 +7970 'jar' 3 +7971 'jas' 3 +7972 'jav' 3 +7973 'jax' 3 +7974 'jay' 3 +7975 'jdk' 3 +7976 'jee' 3 +7977 'jel' 3 +7978 'jem' 3 +7979 'jen' 3 +7980 'jer' 3 +7981 'jes' 3 +7982 'jet' 3 +7983 'jid' 3 +7984 'jin' 3 +7985 'jis' 3 +7986 'jit' 3 +7987 'job' 3 +7988 'jon' 3 +7989 'jor' 3 +7990 'jos' 3 +7991 'jou' 3 +7992 'joy' 3 +7993 'jpg' 3 +7994 'jsp' 3 +7995 'jud' 3 +7996 'jug' 3 +7997 'jul' 3 +7998 'jun' 3 +7999 'jur' 3 +8000 'jà' 3 +8001 'jä' 3 +8002 'jö' 3 +8003 'jø' 3 +8004 'ją' 3 +8005 'ję' 3 +8006 'kal' 3 +8007 'kan' 3 +8008 'kap' 3 +8009 'kar' 3 +8010 'kas' 3 +8011 'kat' 3 +8012 'ked' 3 +8013 'kee' 3 +8014 'keh' 3 +8015 'kel' 3 +8016 'ken' 3 +8017 'ker' 3 +8018 'kes' 3 +8019 'ket' 3 +8020 'key' 3 +8021 'kid' 3 +8022 'kie' 3 +8023 'kil' 3 +8024 'kim' 3 +8025 'kin' 3 +8026 'kip' 3 +8027 'kir' 3 +8028 'kit' 3 +8029 'kle' 3 +8030 'kok' 3 +8031 'kol' 3 +8032 'kom' 3 +8033 'kon' 3 +8034 'kop' 3 +8035 'kor' 3 +8036 'kos' 3 +8037 'kov' 3 +8038 'kow' 3 +8039 'ksi' 3 +8040 'kte' 3 +8041 'kun' 3 +8042 'kur' 3 +8043 'kus' 3 +8044 'ká' 3 +8045 'kä' 3 +8046 'ké' 3 +8047 'kö' 3 +8048 'ką' 3 +8049 'kę' 3 +8050 'lab' 3 +8051 'lac' 3 +8052 'lad' 3 +8053 'lag' 3 +8054 'lah' 3 +8055 'lam' 3 +8056 'lan' 3 +8057 'lap' 3 +8058 'lar' 3 +8059 'las' 3 +8060 'lat' 3 +8061 'lav' 3 +8062 'law' 3 +8063 'lay' 3 +8064 'lbl' 3 +8065 'lea' 3 +8066 'lec' 3 +8067 'led' 3 +8068 'lee' 3 +8069 'lef' 3 +8070 'leg' 3 +8071 'lei' 3 +8072 'lek' 3 +8073 'lem' 3 +8074 'len' 3 +8075 'lep' 3 +8076 'leq' 3 +8077 'ler' 3 +8078 'les' 3 +8079 'let' 3 +8080 'lev' 3 +8081 'lew' 3 +8082 'lex' 3 +8083 'ley' 3 +8084 'lez' 3 +8085 'lia' 3 +8086 'lib' 3 +8087 'lic' 3 +8088 'lid' 3 +8089 'lie' 3 +8090 'lif' 3 +8091 'lig' 3 +8092 'lij' 3 +8093 'lik' 3 +8094 'lim' 3 +8095 'lin' 3 +8096 'lio' 3 +8097 'lip' 3 +8098 'lis' 3 +8099 'lit' 3 +8100 'liv' 3 +8101 'lla' 3 +8102 'lle' 3 +8103 'lli' 3 +8104 'llo' 3 +8105 'lng' 3 +8106 'lob' 3 +8107 'loc' 3 +8108 'lod' 3 +8109 'loe' 3 +8110 'log' 3 +8111 'lon' 3 +8112 'loo' 3 +8113 'lop' 3 +8114 'lor' 3 +8115 'los' 3 +8116 'lot' 3 +8117 'lou' 3 +8118 'lov' 3 +8119 'low' 3 +8120 'loy' 3 +8121 'lst' 3 +8122 'lua' 3 +8123 'luc' 3 +8124 'lum' 3 +8125 'lun' 3 +8126 'lus' 3 +8127 'lut' 3 +8128 'lux' 3 +8129 'lvl' 3 +8130 'lyn' 3 +8131 'lys' 3 +8132 'là' 3 +8133 'lá' 3 +8134 'lä' 3 +8135 'lé' 3 +8136 'ló' 3 +8137 'lö' 3 +8138 'lą' 3 +8139 'lı' 3 +8140 'mAh' 3 +8141 'mac' 3 +8142 'mad' 3 +8143 'mag' 3 +8144 'mai' 3 +8145 'maj' 3 +8146 'mak' 3 +8147 'mal' 3 +8148 'man' 3 +8149 'map' 3 +8150 'mar' 3 +8151 'mas' 3 +8152 'mat' 3 +8153 'max' 3 +8154 'may' 3 +8155 'maz' 3 +8156 'mbH' 3 +8157 'med' 3 +8158 'meg' 3 +8159 'mek' 3 +8160 'mel' 3 +8161 'mem' 3 +8162 'men' 3 +8163 'mer' 3 +8164 'mes' 3 +8165 'met' 3 +8166 'mez' 3 +8167 'mgr' 3 +8168 'mia' 3 +8169 'mic' 3 +8170 'mid' 3 +8171 'mie' 3 +8172 'mil' 3 +8173 'mim' 3 +8174 'min' 3 +8175 'mir' 3 +8176 'mis' 3 +8177 'mit' 3 +8178 'mix' 3 +8179 'mma' 3 +8180 'mmm' 3 +8181 'mob' 3 +8182 'mod' 3 +8183 'mol' 3 +8184 'mom' 3 +8185 'mon' 3 +8186 'mor' 3 +8187 'mos' 3 +8188 'mot' 3 +8189 'mov' 3 +8190 'moz' 3 +8191 'mph' 3 +8192 'mpi' 3 +8193 'mpl' 3 +8194 'mse' 3 +8195 'msg' 3 +8196 'mud' 3 +8197 'mul' 3 +8198 'mun' 3 +8199 'mur' 3 +8200 'mus' 3 +8201 'mut' 3 +8202 'mux' 3 +8203 'mys' 3 +8204 'mé' 3 +8205 'nad' 3 +8206 'nah' 3 +8207 'nai' 3 +8208 'nak' 3 +8209 'nal' 3 +8210 'nam' 3 +8211 'nan' 3 +8212 'nap' 3 +8213 'nar' 3 +8214 'nas' 3 +8215 'nat' 3 +8216 'nav' 3 +8217 'nbr' 3 +8218 'nce' 3 +8219 'nda' 3 +8220 'nds' 3 +8221 'nea' 3 +8222 'ned' 3 +8223 'nee' 3 +8224 'neg' 3 +8225 'neh' 3 +8226 'nej' 3 +8227 'nek' 3 +8228 'nel' 3 +8229 'nem' 3 +8230 'nen' 3 +8231 'neo' 3 +8232 'neq' 3 +8233 'ner' 3 +8234 'nes' 3 +8235 'net' 3 +8236 'neu' 3 +8237 'new' 3 +8238 'nex' 3 +8239 'ney' 3 +8240 'nez' 3 +8241 'nia' 3 +8242 'nic' 3 +8243 'nie' 3 +8244 'nih' 3 +8245 'nik' 3 +8246 'nil' 3 +8247 'nim' 3 +8248 'nin' 3 +8249 'nio' 3 +8250 'nis' 3 +8251 'nit' 3 +8252 'nob' 3 +8253 'noc' 3 +8254 'nod' 3 +8255 'nom' 3 +8256 'non' 3 +8257 'nop' 3 +8258 'nor' 3 +8259 'nos' 3 +8260 'not' 3 +8261 'nou' 3 +8262 'nov' 3 +8263 'now' 3 +8264 'nox' 3 +8265 'npc' 3 +8266 'npm' 3 +8267 'npy' 3 +8268 'nth' 3 +8269 'num' 3 +8270 'nut' 3 +8271 'nya' 3 +8272 'ná' 3 +8273 'né' 3 +8274 'ní' 3 +8275 'ný' 3 +8276 'ną' 3 +8277 'nę' 3 +8278 'ně' 3 +8279 'oad' 3 +8280 'oba' 3 +8281 'obb' 3 +8282 'obe' 3 +8283 'obi' 3 +8284 'obj' 3 +8285 'obl' 3 +8286 'obo' 3 +8287 'obs' 3 +8288 'oby' 3 +8289 'oca' 3 +8290 'occ' 3 +8291 'oce' 3 +8292 'och' 3 +8293 'oci' 3 +8294 'ock' 3 +8295 'ocl' 3 +8296 'oco' 3 +8297 'ocr' 3 +8298 'ocs' 3 +8299 'oct' 3 +8300 'ocy' 3 +8301 'oda' 3 +8302 'odb' 3 +8303 'odd' 3 +8304 'ode' 3 +8305 'odi' 3 +8306 'odo' 3 +8307 'ods' 3 +8308 'ody' 3 +8309 'oen' 3 +8310 'oes' 3 +8311 'off' 3 +8312 'ofs' 3 +8313 'oft' 3 +8314 'oga' 3 +8315 'oge' 3 +8316 'ogg' 3 +8317 'ogh' 3 +8318 'ogi' 3 +8319 'ogl' 3 +8320 'ogn' 3 +8321 'ogo' 3 +8322 'ogr' 3 +8323 'ogs' 3 +8324 'ogy' 3 +8325 'ohl' 3 +8326 'ohn' 3 +8327 'oho' 3 +8328 'oid' 3 +8329 'oil' 3 +8330 'oin' 3 +8331 'oir' 3 +8332 'ois' 3 +8333 'oit' 3 +8334 'oka' 3 +8335 'oke' 3 +8336 'oki' 3 +8337 'oko' 3 +8338 'oks' 3 +8339 'oku' 3 +8340 'oky' 3 +8341 'ola' 3 +8342 'old' 3 +8343 'ole' 3 +8344 'olf' 3 +8345 'oli' 3 +8346 'olk' 3 +8347 'oll' 3 +8348 'oln' 3 +8349 'olo' 3 +8350 'ols' 3 +8351 'olt' 3 +8352 'olu' 3 +8353 'oly' 3 +8354 'oma' 3 +8355 'omb' 3 +8356 'ome' 3 +8357 'omi' 3 +8358 'omm' 3 +8359 'omo' 3 +8360 'omp' 3 +8361 'oms' 3 +8362 'omy' 3 +8363 'ona' 3 +8364 'onc' 3 +8365 'ond' 3 +8366 'one' 3 +8367 'ong' 3 +8368 'oni' 3 +8369 'onn' 3 +8370 'ono' 3 +8371 'ons' 3 +8372 'ont' 3 +8373 'ony' 3 +8374 'onz' 3 +8375 'ood' 3 +8376 'ook' 3 +8377 'ool' 3 +8378 'oom' 3 +8379 'oon' 3 +8380 'ooo' 3 +8381 'oop' 3 +8382 'oor' 3 +8383 'oot' 3 +8384 'opa' 3 +8385 'ope' 3 +8386 'opf' 3 +8387 'oph' 3 +8388 'opi' 3 +8389 'opl' 3 +8390 'opo' 3 +8391 'opp' 3 +8392 'ops' 3 +8393 'opt' 3 +8394 'opy' 3 +8395 'ora' 3 +8396 'orb' 3 +8397 'orc' 3 +8398 'ord' 3 +8399 'ore' 3 +8400 'orf' 3 +8401 'org' 3 +8402 'ori' 3 +8403 'ork' 3 +8404 'orm' 3 +8405 'orn' 3 +8406 'oro' 3 +8407 'orp' 3 +8408 'orr' 3 +8409 'ors' 3 +8410 'ort' 3 +8411 'oru' 3 +8412 'ory' 3 +8413 'osa' 3 +8414 'osc' 3 +8415 'ose' 3 +8416 'osh' 3 +8417 'osi' 3 +8418 'oso' 3 +8419 'osp' 3 +8420 'oss' 3 +8421 'ost' 3 +8422 'ota' 3 +8423 'ote' 3 +8424 'oth' 3 +8425 'oti' 3 +8426 'oto' 3 +8427 'ots' 3 +8428 'ott' 3 +8429 'oty' 3 +8430 'oub' 3 +8431 'oud' 3 +8432 'oug' 3 +8433 'oui' 3 +8434 'ouk' 3 +8435 'oul' 3 +8436 'oun' 3 +8437 'oup' 3 +8438 'our' 3 +8439 'ous' 3 +8440 'out' 3 +8441 'ouv' 3 +8442 'oux' 3 +8443 'ova' 3 +8444 'ove' 3 +8445 'ovi' 3 +8446 'ovo' 3 +8447 'ovy' 3 +8448 'owa' 3 +8449 'owe' 3 +8450 'owi' 3 +8451 'owl' 3 +8452 'own' 3 +8453 'owo' 3 +8454 'ows' 3 +8455 'owy' 3 +8456 'oxy' 3 +8457 'oya' 3 +8458 'oyo' 3 +8459 'ozo' 3 +8460 'ozy' 3 +8461 'oł' 3 +8462 'pac' 3 +8463 'pad' 3 +8464 'pag' 3 +8465 'pak' 3 +8466 'pal' 3 +8467 'pan' 3 +8468 'pap' 3 +8469 'par' 3 +8470 'pas' 3 +8471 'pat' 3 +8472 'pay' 3 +8473 'pci' 3 +8474 'pdb' 3 +8475 'pdf' 3 +8476 'pec' 3 +8477 'ped' 3 +8478 'pee' 3 +8479 'peg' 3 +8480 'pei' 3 +8481 'pel' 3 +8482 'pem' 3 +8483 'pen' 3 +8484 'per' 3 +8485 'pes' 3 +8486 'pet' 3 +8487 'pex' 3 +8488 'pez' 3 +8489 'pha' 3 +8490 'phe' 3 +8491 'phi' 3 +8492 'php' 3 +8493 'phy' 3 +8494 'pic' 3 +8495 'pid' 3 +8496 'pie' 3 +8497 'pig' 3 +8498 'pin' 3 +8499 'pio' 3 +8500 'pip' 3 +8501 'pir' 3 +8502 'pis' 3 +8503 'pit' 3 +8504 'pix' 3 +8505 'pkg' 3 +8506 'pkl' 3 +8507 'pla' 3 +8508 'ple' 3 +8509 'plt' 3 +8510 'ply' 3 +8511 'png' 3 +8512 'pod' 3 +8513 'pol' 3 +8514 'pom' 3 +8515 'pon' 3 +8516 'pop' 3 +8517 'por' 3 +8518 'pos' 3 +8519 'pot' 3 +8520 'pow' 3 +8521 'ppa' 3 +8522 'ppe' 3 +8523 'ppo' 3 +8524 'pps' 3 +8525 'ppy' 3 +8526 'pra' 3 +8527 'pre' 3 +8528 'pri' 3 +8529 'pro' 3 +8530 'psi' 3 +8531 'psy' 3 +8532 'pta' 3 +8533 'pte' 3 +8534 'pth' 3 +8535 'pto' 3 +8536 'ptr' 3 +8537 'pts' 3 +8538 'pty' 3 +8539 'pub' 3 +8540 'pul' 3 +8541 'pun' 3 +8542 'pur' 3 +8543 'pus' 3 +8544 'put' 3 +8545 'pwd' 3 +8546 'qrt' 3 +8547 'qty' 3 +8548 'qua' 3 +8549 'que' 3 +8550 'qui' 3 +8551 'quo' 3 +8552 'rab' 3 +8553 'rac' 3 +8554 'rad' 3 +8555 'rae' 3 +8556 'raf' 3 +8557 'rag' 3 +8558 'rah' 3 +8559 'rai' 3 +8560 'raj' 3 +8561 'rak' 3 +8562 'ral' 3 +8563 'ram' 3 +8564 'ran' 3 +8565 'rap' 3 +8566 'raq' 3 +8567 'rar' 3 +8568 'ras' 3 +8569 'rat' 3 +8570 'rav' 3 +8571 'raw' 3 +8572 'rax' 3 +8573 'ray' 3 +8574 'raz' 3 +8575 'rdf' 3 +8576 'rea' 3 +8577 'reb' 3 +8578 'rec' 3 +8579 'red' 3 +8580 'ree' 3 +8581 'ref' 3 +8582 'reg' 3 +8583 'reh' 3 +8584 'rei' 3 +8585 'rek' 3 +8586 'rel' 3 +8587 'rem' 3 +8588 'ren' 3 +8589 'reo' 3 +8590 'rep' 3 +8591 'req' 3 +8592 'rer' 3 +8593 'res' 3 +8594 'ret' 3 +8595 'reu' 3 +8596 'rev' 3 +8597 'rew' 3 +8598 'rex' 3 +8599 'rey' 3 +8600 'rez' 3 +8601 'rgb' 3 +8602 'rho' 3 +8603 'rhs' 3 +8604 'ria' 3 +8605 'rib' 3 +8606 'ric' 3 +8607 'rid' 3 +8608 'rie' 3 +8609 'rif' 3 +8610 'rig' 3 +8611 'rij' 3 +8612 'rik' 3 +8613 'ril' 3 +8614 'rim' 3 +8615 'rin' 3 +8616 'rio' 3 +8617 'rip' 3 +8618 'rir' 3 +8619 'ris' 3 +8620 'rit' 3 +8621 'riv' 3 +8622 'rix' 3 +8623 'riz' 3 +8624 'rms' 3 +8625 'rna' 3 +8626 'rnd' 3 +8627 'rng' 3 +8628 'rnn' 3 +8629 'rob' 3 +8630 'roc' 3 +8631 'rod' 3 +8632 'roe' 3 +8633 'rog' 3 +8634 'roi' 3 +8635 'rok' 3 +8636 'rol' 3 +8637 'rom' 3 +8638 'ron' 3 +8639 'rop' 3 +8640 'ror' 3 +8641 'ros' 3 +8642 'rot' 3 +8643 'rou' 3 +8644 'rov' 3 +8645 'row' 3 +8646 'rox' 3 +8647 'roy' 3 +8648 'roz' 3 +8649 'rpc' 3 +8650 'rpm' 3 +8651 'rsa' 3 +8652 'rsp' 3 +8653 'rss' 3 +8654 'rst' 3 +8655 'rtl' 3 +8656 'rub' 3 +8657 'rud' 3 +8658 'rue' 3 +8659 'rug' 3 +8660 'rum' 3 +8661 'run' 3 +8662 'rup' 3 +8663 'rus' 3 +8664 'rut' 3 +8665 'ryn' 3 +8666 'rys' 3 +8667 'rà' 3 +8668 'rá' 3 +8669 'rä' 3 +8670 'rå' 3 +8671 'ré' 3 +8672 'rí' 3 +8673 'ró' 3 +8674 'rę' 3 +8675 'sac' 3 +8676 'sad' 3 +8677 'saf' 3 +8678 'sal' 3 +8679 'sam' 3 +8680 'san' 3 +8681 'sar' 3 +8682 'sas' 3 +8683 'sat' 3 +8684 'sav' 3 +8685 'saw' 3 +8686 'say' 3 +8687 'sce' 3 +8688 'sch' 3 +8689 'sci' 3 +8690 'scr' 3 +8691 'sdk' 3 +8692 'sea' 3 +8693 'sec' 3 +8694 'sed' 3 +8695 'see' 3 +8696 'seg' 3 +8697 'sei' 3 +8698 'sek' 3 +8699 'sel' 3 +8700 'sem' 3 +8701 'sen' 3 +8702 'sep' 3 +8703 'seq' 3 +8704 'ser' 3 +8705 'ses' 3 +8706 'set' 3 +8707 'sex' 3 +8708 'sey' 3 +8709 'sez' 3 +8710 'sha' 3 +8711 'she' 3 +8712 'shi' 3 +8713 'shr' 3 +8714 'sic' 3 +8715 'sid' 3 +8716 'sie' 3 +8717 'sig' 3 +8718 'sil' 3 +8719 'sim' 3 +8720 'sin' 3 +8721 'sis' 3 +8722 'sit' 3 +8723 'six' 3 +8724 'ska' 3 +8725 'ske' 3 +8726 'ski' 3 +8727 'sku' 3 +8728 'sky' 3 +8729 'snd' 3 +8730 'soc' 3 +8731 'sof' 3 +8732 'sol' 3 +8733 'som' 3 +8734 'son' 3 +8735 'sor' 3 +8736 'sov' 3 +8737 'spe' 3 +8738 'spi' 3 +8739 'spl' 3 +8740 'spo' 3 +8741 'spr' 3 +8742 'spy' 3 +8743 'sql' 3 +8744 'squ' 3 +8745 'src' 3 +8746 'ssa' 3 +8747 'ssh' 3 +8748 'ssl' 3 +8749 'sta' 3 +8750 'std' 3 +8751 'ste' 3 +8752 'sth' 3 +8753 'sti' 3 +8754 'stm' 3 +8755 'sto' 3 +8756 'str' 3 +8757 'sts' 3 +8758 'stu' 3 +8759 'sty' 3 +8760 'sub' 3 +8761 'suc' 3 +8762 'sum' 3 +8763 'sun' 3 +8764 'sup' 3 +8765 'sur' 3 +8766 'sus' 3 +8767 'svg' 3 +8768 'svn' 3 +8769 'swe' 3 +8770 'sym' 3 +8771 'syn' 3 +8772 'sys' 3 +8773 'tab' 3 +8774 'tag' 3 +8775 'tah' 3 +8776 'tal' 3 +8777 'tam' 3 +8778 'tan' 3 +8779 'tap' 3 +8780 'tar' 3 +8781 'tas' 3 +8782 'tat' 3 +8783 'tau' 3 +8784 'tax' 3 +8785 'tbl' 3 +8786 'tcp' 3 +8787 'tea' 3 +8788 'tec' 3 +8789 'ted' 3 +8790 'tee' 3 +8791 'tek' 3 +8792 'tel' 3 +8793 'tem' 3 +8794 'ten' 3 +8795 'ter' 3 +8796 'tes' 3 +8797 'tet' 3 +8798 'tex' 3 +8799 'tgt' 3 +8800 'tha' 3 +8801 'the' 3 +8802 'thi' 3 +8803 'thm' 3 +8804 'thr' 3 +8805 'ths' 3 +8806 'thy' 3 +8807 'tic' 3 +8808 'tid' 3 +8809 'tie' 3 +8810 'tif' 3 +8811 'tig' 3 +8812 'tik' 3 +8813 'til' 3 +8814 'tim' 3 +8815 'tin' 3 +8816 'tip' 3 +8817 'tis' 3 +8818 'tit' 3 +8819 'tle' 3 +8820 'tls' 3 +8821 'tml' 3 +8822 'tmp' 3 +8823 'toc' 3 +8824 'tod' 3 +8825 'tok' 3 +8826 'tol' 3 +8827 'tom' 3 +8828 'ton' 3 +8829 'too' 3 +8830 'top' 3 +8831 'tor' 3 +8832 'tos' 3 +8833 'tot' 3 +8834 'tow' 3 +8835 'tpl' 3 +8836 'tra' 3 +8837 'tre' 3 +8838 'tri' 3 +8839 'trl' 3 +8840 'tro' 3 +8841 'tru' 3 +8842 'try' 3 +8843 'tte' 3 +8844 'tti' 3 +8845 'ttl' 3 +8846 'ttp' 3 +8847 'tty' 3 +8848 'tum' 3 +8849 'tun' 3 +8850 'tur' 3 +8851 'two' 3 +8852 'txt' 3 +8853 'typ' 3 +8854 'té' 3 +8855 'tó' 3 +8856 'ual' 3 +8857 'uan' 3 +8858 'uar' 3 +8859 'uba' 3 +8860 'ubb' 3 +8861 'ube' 3 +8862 'ubi' 3 +8863 'ubl' 3 +8864 'ubs' 3 +8865 'uby' 3 +8866 'uca' 3 +8867 'ucc' 3 +8868 'uce' 3 +8869 'uch' 3 +8870 'uci' 3 +8871 'uck' 3 +8872 'uct' 3 +8873 'uda' 3 +8874 'udd' 3 +8875 'ude' 3 +8876 'udi' 3 +8877 'udo' 3 +8878 'uds' 3 +8879 'ued' 3 +8880 'uel' 3 +8881 'uen' 3 +8882 'uer' 3 +8883 'ues' 3 +8884 'uet' 3 +8885 'uez' 3 +8886 'ufe' 3 +8887 'uff' 3 +8888 'uga' 3 +8889 'uge' 3 +8890 'ugg' 3 +8891 'ugh' 3 +8892 'ugi' 3 +8893 'ugo' 3 +8894 'ugs' 3 +8895 'ugu' 3 +8896 'uid' 3 +8897 'uil' 3 +8898 'uin' 3 +8899 'uir' 3 +8900 'uis' 3 +8901 'uit' 3 +8902 'uje' 3 +8903 'uka' 3 +8904 'uke' 3 +8905 'uki' 3 +8906 'uko' 3 +8907 'uks' 3 +8908 'uku' 3 +8909 'ula' 3 +8910 'uld' 3 +8911 'ule' 3 +8912 'ulf' 3 +8913 'uli' 3 +8914 'ulk' 3 +8915 'ull' 3 +8916 'ulo' 3 +8917 'ulp' 3 +8918 'uls' 3 +8919 'ult' 3 +8920 'ulu' 3 +8921 'uly' 3 +8922 'uma' 3 +8923 'umb' 3 +8924 'ume' 3 +8925 'umi' 3 +8926 'uml' 3 +8927 'umm' 3 +8928 'umn' 3 +8929 'umo' 3 +8930 'ump' 3 +8931 'ums' 3 +8932 'umu' 3 +8933 'una' 3 +8934 'unc' 3 +8935 'und' 3 +8936 'une' 3 +8937 'ung' 3 +8938 'uni' 3 +8939 'unj' 3 +8940 'unk' 3 +8941 'unn' 3 +8942 'uno' 3 +8943 'uns' 3 +8944 'unt' 3 +8945 'upa' 3 +8946 'upe' 3 +8947 'upo' 3 +8948 'upp' 3 +8949 'ups' 3 +8950 'upt' 3 +8951 'ura' 3 +8952 'urb' 3 +8953 'urd' 3 +8954 'ure' 3 +8955 'urf' 3 +8956 'urg' 3 +8957 'uri' 3 +8958 'urk' 3 +8959 'url' 3 +8960 'urm' 3 +8961 'urn' 3 +8962 'uro' 3 +8963 'urr' 3 +8964 'urs' 3 +8965 'urt' 3 +8966 'uru' 3 +8967 'ury' 3 +8968 'usa' 3 +8969 'usb' 3 +8970 'usc' 3 +8971 'use' 3 +8972 'ush' 3 +8973 'usi' 3 +8974 'usk' 3 +8975 'uso' 3 +8976 'usp' 3 +8977 'usr' 3 +8978 'uss' 3 +8979 'ust' 3 +8980 'usu' 3 +8981 'usz' 3 +8982 'uta' 3 +8983 'utc' 3 +8984 'ute' 3 +8985 'utf' 3 +8986 'uth' 3 +8987 'uti' 3 +8988 'utm' 3 +8989 'uto' 3 +8990 'uts' 3 +8991 'utt' 3 +8992 'uty' 3 +8993 'utz' 3 +8994 'uum' 3 +8995 'uve' 3 +8996 'uvo' 3 +8997 'uxe' 3 +8998 'uya' 3 +8999 'uzz' 3 +9000 'uß' 3 +9001 'ué' 3 +9002 'uí' 3 +9003 'už' 3 +9004 'vac' 3 +9005 'vae' 3 +9006 'val' 3 +9007 'van' 3 +9008 'var' 3 +9009 'vas' 3 +9010 'vat' 3 +9011 'vec' 3 +9012 'ved' 3 +9013 'vee' 3 +9014 'veg' 3 +9015 'veh' 3 +9016 'vel' 3 +9017 'ven' 3 +9018 'ver' 3 +9019 'ves' 3 +9020 'vet' 3 +9021 'vex' 3 +9022 'vey' 3 +9023 'vez' 3 +9024 'via' 3 +9025 'vic' 3 +9026 'vid' 3 +9027 'vie' 3 +9028 'vig' 3 +9029 'vii' 3 +9030 'vik' 3 +9031 'vil' 3 +9032 'vim' 3 +9033 'vin' 3 +9034 'vio' 3 +9035 'vip' 3 +9036 'vir' 3 +9037 'vis' 3 +9038 'vit' 3 +9039 'viv' 3 +9040 'viz' 3 +9041 'voc' 3 +9042 'vod' 3 +9043 'vol' 3 +9044 'von' 3 +9045 'vor' 3 +9046 'vos' 3 +9047 'vox' 3 +9048 'voy' 3 +9049 'vre' 3 +9050 'vue' 3 +9051 'vá' 3 +9052 'vä' 3 +9053 'vé' 3 +9054 'ví' 3 +9055 'vě' 3 +9056 'wal' 3 +9057 'wan' 3 +9058 'wap' 3 +9059 'war' 3 +9060 'was' 3 +9061 'wat' 3 +9062 'wav' 3 +9063 'way' 3 +9064 'web' 3 +9065 'wed' 3 +9066 'weg' 3 +9067 'wei' 3 +9068 'wel' 3 +9069 'wen' 3 +9070 'wer' 3 +9071 'wet' 3 +9072 'whe' 3 +9073 'who' 3 +9074 'why' 3 +9075 'wid' 3 +9076 'wie' 3 +9077 'wig' 3 +9078 'wik' 3 +9079 'wil' 3 +9080 'win' 3 +9081 'wis' 3 +9082 'wit' 3 +9083 'wol' 3 +9084 'won' 3 +9085 'wor' 3 +9086 'www' 3 +9087 'wyn' 3 +9088 'xFF' 3 +9089 'xcb' 3 +9090 'xed' 3 +9091 'xes' 3 +9092 'xfe' 3 +9093 'xff' 3 +9094 'xhr' 3 +9095 'xia' 3 +9096 'xic' 3 +9097 'xim' 3 +9098 'xin' 3 +9099 'xis' 3 +9100 'xit' 3 +9101 'xiv' 3 +9102 'xls' 3 +9103 'xml' 3 +9104 'xon' 3 +9105 'xor' 3 +9106 'xsd' 3 +9107 'xsl' 3 +9108 'xxx' 3 +9109 'xyz' 3 +9110 'yah' 3 +9111 'yal' 3 +9112 'yam' 3 +9113 'yan' 3 +9114 'yar' 3 +9115 'yaw' 3 +9116 'ych' 3 +9117 'ycl' 3 +9118 'yel' 3 +9119 'yen' 3 +9120 'yer' 3 +9121 'yes' 3 +9122 'yet' 3 +9123 'yla' 3 +9124 'yle' 3 +9125 'yll' 3 +9126 'yme' 3 +9127 'yml' 3 +9128 'yna' 3 +9129 'ync' 3 +9130 'yne' 3 +9131 'ynn' 3 +9132 'ynt' 3 +9133 'yon' 3 +9134 'yor' 3 +9135 'you' 3 +9136 'ype' 3 +9137 'yre' 3 +9138 'ysi' 3 +9139 'yst' 3 +9140 'ysz' 3 +9141 'yth' 3 +9142 'yun' 3 +9143 'yyy' 3 +9144 'yó' 3 +9145 'zag' 3 +9146 'zak' 3 +9147 'zan' 3 +9148 'zar' 3 +9149 'zas' 3 +9150 'zed' 3 +9151 'zee' 3 +9152 'zej' 3 +9153 'zek' 3 +9154 'zel' 3 +9155 'zem' 3 +9156 'zen' 3 +9157 'zer' 3 +9158 'zes' 3 +9159 'zet' 3 +9160 'zew' 3 +9161 'zia' 3 +9162 'zie' 3 +9163 'zig' 3 +9164 'zik' 3 +9165 'zin' 3 +9166 'zip' 3 +9167 'zon' 3 +9168 'zor' 3 +9169 'zos' 3 +9170 'zyk' 3 +9171 'zym' 3 +9172 'zza' 3 +9173 'zzi' 3 +9174 'zzo' 3 +9175 'zá' 3 +9176 'zó' 3 +9177 'zą' 3 +9178 'zę' 3 +9179 'ző' 3 +9180 '{{\\' 3 +9181 '{})' 3 +9182 '{},' 3 +9183 '{}.' 3 +9184 '{}\\' 3 +9185 '{}_' 3 +9186 '}")' 3 +9187 '}",' 3 +9188 '}$$' 3 +9189 "}')" 3 +9190 "}'," 3 +9191 '}))' 3 +9192 '}),' 3 +9193 '}).' 3 +9194 '});' 3 +9195 '})\\' 3 +9196 '},"' 3 +9197 '},{' 3 +9198 '}.{' 3 +9199 '}/{' 3 +9200 '}:{' 3 +9201 '}%' 4 +19277 ' \'"\'' 4 +19278 " '#'" 4 +19279 " '''" 4 +19280 " '')" 4 +19281 " ''," 4 +19282 " '';" 4 +19283 " '*'" 4 +19284 " '-'" 4 +19285 " '--" 4 +19286 " './" 4 +19287 " '/'" 4 +19288 " ':'" 4 +19289 " '' 4 +19312 ' ...' 4 +19313 ' ../' 4 +19314 ' /**' 4 +19315 ' ///' 4 +19316 ' /><' 4 +19317 ' :-)' 4 +19318 ' <%=' 4 +19319 ' <--' 4 +19320 ' ===' 4 +19321 ' ==>' 4 +19322 ' >>>' 4 +19323 ' ???' 4 +19324 ' AAA' 4 +19325 ' AAP' 4 +19326 ' ABC' 4 +19327 ' ABI' 4 +19328 ' ABS' 4 +19329 ' ACC' 4 +19330 ' ACE' 4 +19331 ' ACK' 4 +19332 ' ACL' 4 +19333 ' ACS' 4 +19334 ' ACT' 4 +19335 ' ADA' 4 +19336 ' ADC' 4 +19337 ' ADD' 4 +19338 ' AES' 4 +19339 ' AFC' 4 +19340 ' AFL' 4 +19341 ' AFP' 4 +19342 ' AIR' 4 +19343 ' ALL' 4 +19344 ' ALS' 4 +19345 ' ALT' 4 +19346 ' AMD' 4 +19347 ' AMP' 4 +19348 ' ANC' 4 +19349 ' AND' 4 +19350 ' ANN' 4 +19351 ' ANY' 4 +19352 ' APC' 4 +19353 ' API' 4 +19354 ' APP' 4 +19355 ' APR' 4 +19356 ' ARE' 4 +19357 ' ARG' 4 +19358 ' ARM' 4 +19359 ' ART' 4 +19360 ' ASC' 4 +19361 ' ASD' 4 +19362 ' ASE' 4 +19363 ' ASF' 4 +19364 ' ASP' 4 +19365 ' ASS' 4 +19366 ' AST' 4 +19367 ' ATM' 4 +19368 ' ATP' 4 +19369 ' ATT' 4 +19370 ' AUT' 4 +19371 ' AWS' 4 +19372 ' Abb' 4 +19373 ' Abd' 4 +19374 ' Abe' 4 +19375 ' Abl' 4 +19376 ' Abr' 4 +19377 ' Abs' 4 +19378 ' Abu' 4 +19379 ' Acc' 4 +19380 ' Ace' 4 +19381 ' Ach' 4 +19382 ' Act' 4 +19383 ' Ada' 4 +19384 ' Add' 4 +19385 ' Ade' 4 +19386 ' Adv' 4 +19387 ' Aer' 4 +19388 ' Aff' 4 +19389 ' Afr' 4 +19390 ' Age' 4 +19391 ' Agg' 4 +19392 ' Agr' 4 +19393 ' Agu' 4 +19394 ' Aid' 4 +19395 ' Aim' 4 +19396 ' Ain' 4 +19397 ' Air' 4 +19398 ' Akt' 4 +19399 ' Ala' 4 +19400 ' Alb' 4 +19401 ' Alc' 4 +19402 ' Ald' 4 +19403 ' Ale' 4 +19404 ' Alf' 4 +19405 ' Alg' 4 +19406 ' Ali' 4 +19407 ' All' 4 +19408 ' Alo' 4 +19409 ' Als' 4 +19410 ' Alt' 4 +19411 ' Ama' 4 +19412 ' Amb' 4 +19413 ' Amp' 4 +19414 ' Amy' 4 +19415 ' Ana' 4 +19416 ' Anc' 4 +19417 ' And' 4 +19418 ' Ang' 4 +19419 ' Ank' 4 +19420 ' Ann' 4 +19421 ' Ans' 4 +19422 ' Ant' 4 +19423 ' Any' 4 +19424 ' Aph' 4 +19425 ' Api' 4 +19426 ' App' 4 +19427 ' Apr' 4 +19428 ' Aqu' 4 +19429 ' Ara' 4 +19430 ' Arc' 4 +19431 ' Are' 4 +19432 ' Arg' 4 +19433 ' Ari' 4 +19434 ' Ark' 4 +19435 ' Arm' 4 +19436 ' Arn' 4 +19437 ' Arr' 4 +19438 ' Ars' 4 +19439 ' Art' 4 +19440 ' Asc' 4 +19441 ' Ash' 4 +19442 ' Ask' 4 +19443 ' Asp' 4 +19444 ' Ass' 4 +19445 ' Ast' 4 +19446 ' Ath' 4 +19447 ' Atl' 4 +19448 ' Att' 4 +19449 ' Aub' 4 +19450 ' Aud' 4 +19451 ' Auf' 4 +19452 ' Aug' 4 +19453 ' Aur' 4 +19454 ' Aus' 4 +19455 ' Aut' 4 +19456 ' Aux' 4 +19457 ' Ave' 4 +19458 ' Aβ' 4 +19459 ' BAL' 4 +19460 ' BAR' 4 +19461 ' BAS' 4 +19462 ' BAT' 4 +19463 ' BBB' 4 +19464 ' BBC' 4 +19465 ' BCE' 4 +19466 ' BEL' 4 +19467 ' BET' 4 +19468 ' BIG' 4 +19469 ' BIN' 4 +19470 ' BIT' 4 +19471 ' BJP' 4 +19472 ' BMC' 4 +19473 ' BMI' 4 +19474 ' BMP' 4 +19475 ' BMW' 4 +19476 ' BRE' 4 +19477 ' BSD' 4 +19478 ' BTC' 4 +19479 ' BUS' 4 +19480 ' BUT' 4 +19481 ' Bab' 4 +19482 ' Bac' 4 +19483 ' Bad' 4 +19484 ' Bag' 4 +19485 ' Bah' 4 +19486 ' Bai' 4 +19487 ' Bak' 4 +19488 ' Bal' 4 +19489 ' Bam' 4 +19490 ' Ban' 4 +19491 ' Bar' 4 +19492 ' Bas' 4 +19493 ' Bat' 4 +19494 ' Bau' 4 +19495 ' Bav' 4 +19496 ' Bay' 4 +19497 ' Baz' 4 +19498 ' Bea' 4 +19499 ' Bec' 4 +19500 ' Bed' 4 +19501 ' Bee' 4 +19502 ' Beg' 4 +19503 ' Beh' 4 +19504 ' Bei' 4 +19505 ' Bek' 4 +19506 ' Bel' 4 +19507 ' Ben' 4 +19508 ' Ber' 4 +19509 ' Bes' 4 +19510 ' Bet' 4 +19511 ' Bew' 4 +19512 ' Bey' 4 +19513 ' Bez' 4 +19514 ' Bib' 4 +19515 ' Bid' 4 +19516 ' Big' 4 +19517 ' Bij' 4 +19518 ' Bil' 4 +19519 ' Bin' 4 +19520 ' Bio' 4 +19521 ' Bir' 4 +19522 ' Bis' 4 +19523 ' Bit' 4 +19524 ' Ble' 4 +19525 ' Blo' 4 +19526 ' Blu' 4 +19527 ' Bob' 4 +19528 ' Bod' 4 +19529 ' Bog' 4 +19530 ' Boh' 4 +19531 ' Bol' 4 +19532 ' Bom' 4 +19533 ' Bon' 4 +19534 ' Bor' 4 +19535 ' Bos' 4 +19536 ' Bot' 4 +19537 ' Bou' 4 +19538 ' Bow' 4 +19539 ' Box' 4 +19540 ' Boy' 4 +19541 ' Bra' 4 +19542 ' Bre' 4 +19543 ' Bri' 4 +19544 ' Bro' 4 +19545 ' Bru' 4 +19546 ' Bry' 4 +19547 ' Buc' 4 +19548 ' Bud' 4 +19549 ' Bug' 4 +19550 ' Buk' 4 +19551 ' Bul' 4 +19552 ' Bun' 4 +19553 ' Bur' 4 +19554 ' Bus' 4 +19555 ' But' 4 +19556 ' Buy' 4 +19557 ' Byr' 4 +19558 ' Byz' 4 +19559 ' Bé' 4 +19560 ' Bö' 4 +19561 ' Bü' 4 +19562 ' CAB' 4 +19563 ' CAD' 4 +19564 ' CAL' 4 +19565 ' CAM' 4 +19566 ' CAN' 4 +19567 ' CAP' 4 +19568 ' CAR' 4 +19569 ' CAS' 4 +19570 ' CAT' 4 +19571 ' CBC' 4 +19572 ' CBD' 4 +19573 ' CBS' 4 +19574 ' CCC' 4 +19575 ' CCD' 4 +19576 ' CCT' 4 +19577 ' CDC' 4 +19578 ' CDs' 4 +19579 ' CEO' 4 +19580 ' CES' 4 +19581 ' CGI' 4 +19582 ' CHE' 4 +19583 ' CHO' 4 +19584 ' CIA' 4 +19585 ' CID' 4 +19586 ' CIF' 4 +19587 ' CIS' 4 +19588 ' CIT' 4 +19589 ' CLA' 4 +19590 ' CLI' 4 +19591 ' CMD' 4 +19592 ' CMS' 4 +19593 ' CNN' 4 +19594 ' CNS' 4 +19595 ' COL' 4 +19596 ' COM' 4 +19597 ' CON' 4 +19598 ' COP' 4 +19599 ' COR' 4 +19600 ' COS' 4 +19601 ' CPR' 4 +19602 ' CPU' 4 +19603 ' CRC' 4 +19604 ' CRE' 4 +19605 ' CRM' 4 +19606 ' CSR' 4 +19607 ' CSS' 4 +19608 ' CST' 4 +19609 ' CSV' 4 +19610 ' CTR' 4 +19611 ' CUR' 4 +19612 ' Cab' 4 +19613 ' Cad' 4 +19614 ' Caf' 4 +19615 ' Cal' 4 +19616 ' Cam' 4 +19617 ' Can' 4 +19618 ' Cap' 4 +19619 ' Car' 4 +19620 ' Cas' 4 +19621 ' Cat' 4 +19622 ' Cav' 4 +19623 ' Cay' 4 +19624 ' Cec' 4 +19625 ' Ced' 4 +19626 ' Cel' 4 +19627 ' Cer' 4 +19628 ' Ces' 4 +19629 ' Cet' 4 +19630 ' Cha' 4 +19631 ' Che' 4 +19632 ' Chi' 4 +19633 ' Cho' 4 +19634 ' Chr' 4 +19635 ' Chu' 4 +19636 ' Cic' 4 +19637 ' Cin' 4 +19638 ' Cir' 4 +19639 ' Cit' 4 +19640 ' Civ' 4 +19641 ' Cla' 4 +19642 ' Cle' 4 +19643 ' Cli' 4 +19644 ' Clo' 4 +19645 ' Cly' 4 +19646 ' Cob' 4 +19647 ' Coc' 4 +19648 ' Cod' 4 +19649 ' Coh' 4 +19650 ' Col' 4 +19651 ' Com' 4 +19652 ' Con' 4 +19653 ' Cop' 4 +19654 ' Cor' 4 +19655 ' Cos' 4 +19656 ' Cot' 4 +19657 ' Cou' 4 +19658 ' Cov' 4 +19659 ' Cow' 4 +19660 ' Cox' 4 +19661 ' Coy' 4 +19662 ' Cra' 4 +19663 ' Cre' 4 +19664 ' Cri' 4 +19665 ' Cro' 4 +19666 ' Cru' 4 +19667 ' Cry' 4 +19668 ' Cub' 4 +19669 ' Cul' 4 +19670 ' Cum' 4 +19671 ' Cup' 4 +19672 ' Cur' 4 +19673 ' Cut' 4 +19674 ' Cyr' 4 +19675 ' DAC' 4 +19676 ' DAG' 4 +19677 ' DAM' 4 +19678 ' DAR' 4 +19679 ' DAT' 4 +19680 ' DAY' 4 +19681 ' DDR' 4 +19682 ' DEA' 4 +19683 ' DEC' 4 +19684 ' DEF' 4 +19685 ' DEL' 4 +19686 ' DEM' 4 +19687 ' DEN' 4 +19688 ' DEP' 4 +19689 ' DES' 4 +19690 ' DET' 4 +19691 ' DEV' 4 +19692 ' DFS' 4 +19693 ' DHS' 4 +19694 ' DID' 4 +19695 ' DIG' 4 +19696 ' DIR' 4 +19697 ' DIS' 4 +19698 ' DIV' 4 +19699 ' DIY' 4 +19700 ' DLL' 4 +19701 ' DNA' 4 +19702 ' DNS' 4 +19703 ' DOC' 4 +19704 ' DOI' 4 +19705 ' DOM' 4 +19706 ' DON' 4 +19707 ' DOS' 4 +19708 ' DOT' 4 +19709 ' DSL' 4 +19710 ' DSM' 4 +19711 ' DVD' 4 +19712 ' Dad' 4 +19713 ' Dag' 4 +19714 ' Dah' 4 +19715 ' Dai' 4 +19716 ' Dak' 4 +19717 ' Dal' 4 +19718 ' Dam' 4 +19719 ' Dan' 4 +19720 ' Dar' 4 +19721 ' Das' 4 +19722 ' Dat' 4 +19723 ' Dav' 4 +19724 ' Daw' 4 +19725 ' Day' 4 +19726 ' Deb' 4 +19727 ' Dec' 4 +19728 ' Ded' 4 +19729 ' Dee' 4 +19730 ' Def' 4 +19731 ' Deg' 4 +19732 ' Dek' 4 +19733 ' Del' 4 +19734 ' Dem' 4 +19735 ' Den' 4 +19736 ' Dep' 4 +19737 ' Der' 4 +19738 ' Des' 4 +19739 ' Det' 4 +19740 ' Dev' 4 +19741 ' Dew' 4 +19742 ' Dex' 4 +19743 ' Dez' 4 +19744 ' Dia' 4 +19745 ' Did' 4 +19746 ' Die' 4 +19747 ' Dig' 4 +19748 ' Dil' 4 +19749 ' Dim' 4 +19750 ' Din' 4 +19751 ' Dip' 4 +19752 ' Dir' 4 +19753 ' Dis' 4 +19754 ' Dit' 4 +19755 ' Div' 4 +19756 ' Dix' 4 +19757 ' Dob' 4 +19758 ' Doc' 4 +19759 ' Dod' 4 +19760 ' Doe' 4 +19761 ' Dog' 4 +19762 ' Dok' 4 +19763 ' Dol' 4 +19764 ' Dom' 4 +19765 ' Don' 4 +19766 ' Dop' 4 +19767 ' Dor' 4 +19768 ' Dos' 4 +19769 ' Dot' 4 +19770 ' Dou' 4 +19771 ' Dow' 4 +19772 ' Dra' 4 +19773 ' Dre' 4 +19774 ' Dro' 4 +19775 ' Dru' 4 +19776 ' Dry' 4 +19777 ' Dub' 4 +19778 ' Duc' 4 +19779 ' Dud' 4 +19780 ' Due' 4 +19781 ' Dul' 4 +19782 ' Dum' 4 +19783 ' Dun' 4 +19784 ' Duo' 4 +19785 ' Dup' 4 +19786 ' Dur' 4 +19787 ' Dyn' 4 +19788 ' Dé' 4 +19789 ' Dí' 4 +19790 ' ECM' 4 +19791 ' EEG' 4 +19792 ' EMP' 4 +19793 ' EMS' 4 +19794 ' END' 4 +19795 ' ENG' 4 +19796 ' EOF' 4 +19797 ' EOS' 4 +19798 ' EPA' 4 +19799 ' EPS' 4 +19800 ' ERA' 4 +19801 ' ERR' 4 +19802 ' ESA' 4 +19803 ' ESC' 4 +19804 ' ESP' 4 +19805 ' EST' 4 +19806 ' ETH' 4 +19807 ' EUR' 4 +19808 ' EXP' 4 +19809 ' EXT' 4 +19810 ' Ear' 4 +19811 ' Eat' 4 +19812 ' Eck' 4 +19813 ' Eco' 4 +19814 ' Edd' 4 +19815 ' Edu' 4 +19816 ' Eff' 4 +19817 ' Egg' 4 +19818 ' Ein' 4 +19819 ' Eld' 4 +19820 ' Ele' 4 +19821 ' Eli' 4 +19822 ' Ell' 4 +19823 ' Emb' 4 +19824 ' Emp' 4 +19825 ' Enc' 4 +19826 ' End' 4 +19827 ' Eng' 4 +19828 ' Enh' 4 +19829 ' Ens' 4 +19830 ' Ent' 4 +19831 ' Env' 4 +19832 ' Eph' 4 +19833 ' Equ' 4 +19834 ' Era' 4 +19835 ' Erd' 4 +19836 ' Ern' 4 +19837 ' Err' 4 +19838 ' Esc' 4 +19839 ' Esp' 4 +19840 ' Ess' 4 +19841 ' Est' 4 +19842 ' Eth' 4 +19843 ' Eug' 4 +19844 ' Eur' 4 +19845 ' Eva' 4 +19846 ' Eve' 4 +19847 ' Exc' 4 +19848 ' Exp' 4 +19849 ' Ext' 4 +19850 ' Eye' 4 +19851 ' FAA' 4 +19852 ' FAC' 4 +19853 ' FAQ' 4 +19854 ' FAR' 4 +19855 ' FAT' 4 +19856 ' FBI' 4 +19857 ' FCC' 4 +19858 ' FDA' 4 +19859 ' FFT' 4 +19860 ' FIF' 4 +19861 ' FIG' 4 +19862 ' FIL' 4 +19863 ' FIN' 4 +19864 ' FIR' 4 +19865 ' FIT' 4 +19866 ' FIX' 4 +19867 ' FOR' 4 +19868 ' FOX' 4 +19869 ' FPS' 4 +19870 ' FTP' 4 +19871 ' FUN' 4 +19872 ' Fab' 4 +19873 ' Fac' 4 +19874 ' Fah' 4 +19875 ' Fal' 4 +19876 ' Fam' 4 +19877 ' Fan' 4 +19878 ' Far' 4 +19879 ' Fas' 4 +19880 ' Fat' 4 +19881 ' Fay' 4 +19882 ' Feb' 4 +19883 ' Fed' 4 +19884 ' Fel' 4 +19885 ' Fem' 4 +19886 ' Fen' 4 +19887 ' Fer' 4 +19888 ' Fet' 4 +19889 ' Few' 4 +19890 ' Fib' 4 +19891 ' Fif' 4 +19892 ' Fig' 4 +19893 ' Fil' 4 +19894 ' Fin' 4 +19895 ' Fir' 4 +19896 ' Fit' 4 +19897 ' Fix' 4 +19898 ' Fla' 4 +19899 ' Fle' 4 +19900 ' Flo' 4 +19901 ' Flu' 4 +19902 ' Fly' 4 +19903 ' Fog' 4 +19904 ' Fol' 4 +19905 ' Fon' 4 +19906 ' Foo' 4 +19907 ' For' 4 +19908 ' Fot' 4 +19909 ' Fou' 4 +19910 ' Fox' 4 +19911 ' Fra' 4 +19912 ' Fre' 4 +19913 ' Fri' 4 +19914 ' Fro' 4 +19915 ' Fry' 4 +19916 ' Fuj' 4 +19917 ' Fuk' 4 +19918 ' Ful' 4 +19919 ' Fun' 4 +19920 ' Fur' 4 +19921 ' Fut' 4 +19922 ' Fé' 4 +19923 ' GAM' 4 +19924 ' GCC' 4 +19925 ' GDP' 4 +19926 ' GEN' 4 +19927 ' GET' 4 +19928 ' GFP' 4 +19929 ' GHz' 4 +19930 ' GMT' 4 +19931 ' GNU' 4 +19932 ' GOD' 4 +19933 ' GOP' 4 +19934 ' GPL' 4 +19935 ' GPS' 4 +19936 ' GPU' 4 +19937 ' GRE' 4 +19938 ' GRO' 4 +19939 ' GSM' 4 +19940 ' GST' 4 +19941 ' GUI' 4 +19942 ' Gab' 4 +19943 ' Gad' 4 +19944 ' Gal' 4 +19945 ' Gam' 4 +19946 ' Gan' 4 +19947 ' Gap' 4 +19948 ' Gar' 4 +19949 ' Gas' 4 +19950 ' Gat' 4 +19951 ' Gay' 4 +19952 ' Gaz' 4 +19953 ' GeV' 4 +19954 ' Geb' 4 +19955 ' Ged' 4 +19956 ' Geg' 4 +19957 ' Gel' 4 +19958 ' Gem' 4 +19959 ' Gen' 4 +19960 ' Geo' 4 +19961 ' Ger' 4 +19962 ' Ges' 4 +19963 ' Get' 4 +19964 ' Gew' 4 +19965 ' Gib' 4 +19966 ' Gig' 4 +19967 ' Gil' 4 +19968 ' Gin' 4 +19969 ' Gir' 4 +19970 ' Git' 4 +19971 ' Gle' 4 +19972 ' Gly' 4 +19973 ' Gob' 4 +19974 ' God' 4 +19975 ' Gol' 4 +19976 ' Gon' 4 +19977 ' Gor' 4 +19978 ' Gos' 4 +19979 ' Got' 4 +19980 ' Gov' 4 +19981 ' Gow' 4 +19982 ' Gra' 4 +19983 ' Gre' 4 +19984 ' Gri' 4 +19985 ' Gro' 4 +19986 ' Gru' 4 +19987 ' Gtk' 4 +19988 ' Gul' 4 +19989 ' Gum' 4 +19990 ' Gun' 4 +19991 ' Gur' 4 +19992 ' Gus' 4 +19993 ' Gut' 4 +19994 ' Guy' 4 +19995 ' Gym' 4 +19996 ' Gä' 4 +19997 ' Gé' 4 +19998 ' Gó' 4 +19999 ' Gö' 4 +20000 ' Gü' 4 +20001 ' HAL' 4 +20002 ' HAR' 4 +20003 ' HAS' 4 +20004 ' HBO' 4 +20005 ' HEL' 4 +20006 ' HER' 4 +20007 ' HIS' 4 +20008 ' HIV' 4 +20009 ' HMS' 4 +20010 ' HOW' 4 +20011 ' HPV' 4 +20012 ' HTC' 4 +20013 ' Hab' 4 +20014 ' Had' 4 +20015 ' Hag' 4 +20016 ' Hai' 4 +20017 ' Haj' 4 +20018 ' Hak' 4 +20019 ' Hal' 4 +20020 ' Ham' 4 +20021 ' Han' 4 +20022 ' Har' 4 +20023 ' Has' 4 +20024 ' Hat' 4 +20025 ' Hav' 4 +20026 ' Haw' 4 +20027 ' Hay' 4 +20028 ' Haz' 4 +20029 ' Heb' 4 +20030 ' Hed' 4 +20031 ' Hel' 4 +20032 ' Hem' 4 +20033 ' Hen' 4 +20034 ' Hep' 4 +20035 ' Her' 4 +20036 ' Het' 4 +20037 ' Hew' 4 +20038 ' Hex' 4 +20039 ' Hey' 4 +20040 ' Hib' 4 +20041 ' Hig' 4 +20042 ' Hij' 4 +20043 ' Hil' 4 +20044 ' Him' 4 +20045 ' Hin' 4 +20046 ' Hip' 4 +20047 ' Hir' 4 +20048 ' His' 4 +20049 ' Hit' 4 +20050 ' Hmm' 4 +20051 ' Hob' 4 +20052 ' Hod' 4 +20053 ' Hof' 4 +20054 ' Hog' 4 +20055 ' Hol' 4 +20056 ' Hom' 4 +20057 ' Hon' 4 +20058 ' Hop' 4 +20059 ' Hor' 4 +20060 ' Hos' 4 +20061 ' Hot' 4 +20062 ' Hou' 4 +20063 ' How' 4 +20064 ' Hoy' 4 +20065 ' Hua' 4 +20066 ' Hub' 4 +20067 ' Hud' 4 +20068 ' Hug' 4 +20069 ' Hum' 4 +20070 ' Hun' 4 +20071 ' Hur' 4 +20072 ' Hus' 4 +20073 ' Hut' 4 +20074 ' Hyp' 4 +20075 ' Hä' 4 +20076 ' Hö' 4 +20077 ' IBM' 4 +20078 ' ICC' 4 +20079 ' ICE' 4 +20080 ' ICO' 4 +20081 ' ICT' 4 +20082 ' ICU' 4 +20083 ' IDE' 4 +20084 ' IDs' 4 +20085 ' III' 4 +20086 ' IIS' 4 +20087 ' IMF' 4 +20088 ' IMP' 4 +20089 ' INC' 4 +20090 ' IND' 4 +20091 ' INF' 4 +20092 ' INS' 4 +20093 ' INT' 4 +20094 ' IPA' 4 +20095 ' IPO' 4 +20096 ' IPS' 4 +20097 ' IPv' 4 +20098 ' IRA' 4 +20099 ' IRC' 4 +20100 ' IRS' 4 +20101 ' ISO' 4 +20102 ' ISP' 4 +20103 ' ISS' 4 +20104 ' ITE' 4 +20105 ' ITS' 4 +20106 ' Ian' 4 +20107 ' Ice' 4 +20108 ' Ich' 4 +20109 ' Ide' 4 +20110 ' Ign' 4 +20111 ' Ill' 4 +20112 ' Ils' 4 +20113 ' Imm' 4 +20114 ' Imp' 4 +20115 ' Inc' 4 +20116 ' Ind' 4 +20117 ' Inf' 4 +20118 ' Ing' 4 +20119 ' Ink' 4 +20120 ' Inn' 4 +20121 ' Ins' 4 +20122 ' Int' 4 +20123 ' Inv' 4 +20124 ' IoT' 4 +20125 ' Ion' 4 +20126 ' Ips' 4 +20127 ' Ira' 4 +20128 ' Isa' 4 +20129 ' Ish' 4 +20130 ' Isl' 4 +20131 ' Isn' 4 +20132 ' Iss' 4 +20133 ' Ist' 4 +20134 ' Its' 4 +20135 ' Ivy' 4 +20136 ' JVM' 4 +20137 ' Jab' 4 +20138 ' Jac' 4 +20139 ' Jag' 4 +20140 ' Jah' 4 +20141 ' Jak' 4 +20142 ' Jal' 4 +20143 ' Jam' 4 +20144 ' Jan' 4 +20145 ' Jar' 4 +20146 ' Jas' 4 +20147 ' Jaw' 4 +20148 ' Jay' 4 +20149 ' Jed' 4 +20150 ' Jen' 4 +20151 ' Jer' 4 +20152 ' Jes' 4 +20153 ' Jet' 4 +20154 ' Jew' 4 +20155 ' Jim' 4 +20156 ' Jin' 4 +20157 ' Job' 4 +20158 ' Joe' 4 +20159 ' Joh' 4 +20160 ' Jon' 4 +20161 ' Jos' 4 +20162 ' Joy' 4 +20163 ' Jub' 4 +20164 ' Jud' 4 +20165 ' Jug' 4 +20166 ' Jul' 4 +20167 ' Jun' 4 +20168 ' Jur' 4 +20169 ' Já' 4 +20170 ' Jó' 4 +20171 ' KDE' 4 +20172 ' KEY' 4 +20173 ' Kab' 4 +20174 ' Kad' 4 +20175 ' Kag' 4 +20176 ' Kah' 4 +20177 ' Kai' 4 +20178 ' Kak' 4 +20179 ' Kal' 4 +20180 ' Kam' 4 +20181 ' Kan' 4 +20182 ' Kap' 4 +20183 ' Kar' 4 +20184 ' Kas' 4 +20185 ' Kat' 4 +20186 ' Kaw' 4 +20187 ' Kay' 4 +20188 ' Kaz' 4 +20189 ' Kel' 4 +20190 ' Kem' 4 +20191 ' Ken' 4 +20192 ' Ker' 4 +20193 ' Kes' 4 +20194 ' Ket' 4 +20195 ' Key' 4 +20196 ' Kid' 4 +20197 ' Kil' 4 +20198 ' Kim' 4 +20199 ' Kin' 4 +20200 ' Kir' 4 +20201 ' Kit' 4 +20202 ' Kle' 4 +20203 ' Kob' 4 +20204 ' Kod' 4 +20205 ' Koh' 4 +20206 ' Kok' 4 +20207 ' Kol' 4 +20208 ' Kom' 4 +20209 ' Kon' 4 +20210 ' Kop' 4 +20211 ' Kor' 4 +20212 ' Kos' 4 +20213 ' Kot' 4 +20214 ' Kou' 4 +20215 ' Kov' 4 +20216 ' Kra' 4 +20217 ' Kre' 4 +20218 ' Kro' 4 +20219 ' Kub' 4 +20220 ' Kul' 4 +20221 ' Kum' 4 +20222 ' Kun' 4 +20223 ' Kur' 4 +20224 ' Kut' 4 +20225 ' Kö' 4 +20226 ' Kü' 4 +20227 ' LAB' 4 +20228 ' LAN' 4 +20229 ' LAP' 4 +20230 ' LAS' 4 +20231 ' LAT' 4 +20232 ' LAW' 4 +20233 ' LCD' 4 +20234 ' LDL' 4 +20235 ' LED' 4 +20236 ' LEG' 4 +20237 ' LET' 4 +20238 ' LIB' 4 +20239 ' LIM' 4 +20240 ' LIN' 4 +20241 ' LLC' 4 +20242 ' LLP' 4 +20243 ' LOC' 4 +20244 ' LOG' 4 +20245 ' LOL' 4 +20246 ' LOS' 4 +20247 ' LOT' 4 +20248 ' LPS' 4 +20249 ' LSD' 4 +20250 ' LTE' 4 +20251 ' Lab' 4 +20252 ' Lac' 4 +20253 ' Lad' 4 +20254 ' Laf' 4 +20255 ' Lag' 4 +20256 ' Lah' 4 +20257 ' Lak' 4 +20258 ' Lal' 4 +20259 ' Lam' 4 +20260 ' Lan' 4 +20261 ' Lap' 4 +20262 ' Lar' 4 +20263 ' Las' 4 +20264 ' Lat' 4 +20265 ' Lau' 4 +20266 ' Lav' 4 +20267 ' Law' 4 +20268 ' Lay' 4 +20269 ' Laz' 4 +20270 ' Leb' 4 +20271 ' Lec' 4 +20272 ' Led' 4 +20273 ' Lee' 4 +20274 ' Leg' 4 +20275 ' Leh' 4 +20276 ' Lei' 4 +20277 ' Lem' 4 +20278 ' Len' 4 +20279 ' Leo' 4 +20280 ' Ler' 4 +20281 ' Les' 4 +20282 ' Let' 4 +20283 ' Lev' 4 +20284 ' Lew' 4 +20285 ' Lex' 4 +20286 ' Ley' 4 +20287 ' Lia' 4 +20288 ' Lib' 4 +20289 ' Lic' 4 +20290 ' Lid' 4 +20291 ' Lie' 4 +20292 ' Lif' 4 +20293 ' Lig' 4 +20294 ' Lik' 4 +20295 ' Lil' 4 +20296 ' Lim' 4 +20297 ' Lin' 4 +20298 ' Lip' 4 +20299 ' Lis' 4 +20300 ' Lit' 4 +20301 ' Liu' 4 +20302 ' Liv' 4 +20303 ' Liz' 4 +20304 ' Lob' 4 +20305 ' Loc' 4 +20306 ' Log' 4 +20307 ' Lok' 4 +20308 ' Lon' 4 +20309 ' Lor' 4 +20310 ' Los' 4 +20311 ' Lot' 4 +20312 ' Lou' 4 +20313 ' Lov' 4 +20314 ' Low' 4 +20315 ' Ltd' 4 +20316 ' Lua' 4 +20317 ' Lub' 4 +20318 ' Luc' 4 +20319 ' Lud' 4 +20320 ' Lug' 4 +20321 ' Luk' 4 +20322 ' Lum' 4 +20323 ' Lun' 4 +20324 ' Lup' 4 +20325 ' Lux' 4 +20326 ' Lyn' 4 +20327 ' Lys' 4 +20328 ' Lé' 4 +20329 ' Lö' 4 +20330 ' Lü' 4 +20331 ' MAC' 4 +20332 ' MAG' 4 +20333 ' MAL' 4 +20334 ' MAN' 4 +20335 ' MAP' 4 +20336 ' MAR' 4 +20337 ' MAS' 4 +20338 ' MAT' 4 +20339 ' MAX' 4 +20340 ' MAY' 4 +20341 ' MBA' 4 +20342 ' MED' 4 +20343 ' MEM' 4 +20344 ' MEN' 4 +20345 ' MEP' 4 +20346 ' MER' 4 +20347 ' MET' 4 +20348 ' MHz' 4 +20349 ' MIC' 4 +20350 ' MID' 4 +20351 ' MIL' 4 +20352 ' MIN' 4 +20353 ' MIS' 4 +20354 ' MIT' 4 +20355 ' MLB' 4 +20356 ' MLP' 4 +20357 ' MLS' 4 +20358 ' MMA' 4 +20359 ' MMP' 4 +20360 ' MOD' 4 +20361 ' MON' 4 +20362 ' MOR' 4 +20363 ' MOS' 4 +20364 ' MOT' 4 +20365 ' MPI' 4 +20366 ' MPs' 4 +20367 ' MRI' 4 +20368 ' MSC' 4 +20369 ' MSE' 4 +20370 ' MSG' 4 +20371 ' MSM' 4 +20372 ' MTV' 4 +20373 ' MUS' 4 +20374 ' MVC' 4 +20375 ' MVP' 4 +20376 ' Mac' 4 +20377 ' Mad' 4 +20378 ' Mae' 4 +20379 ' Mag' 4 +20380 ' Mah' 4 +20381 ' Mai' 4 +20382 ' Maj' 4 +20383 ' Mak' 4 +20384 ' Mal' 4 +20385 ' Mam' 4 +20386 ' Man' 4 +20387 ' Mao' 4 +20388 ' Map' 4 +20389 ' Mar' 4 +20390 ' Mas' 4 +20391 ' Mat' 4 +20392 ' Mau' 4 +20393 ' Max' 4 +20394 ' May' 4 +20395 ' Maz' 4 +20396 ' McC' 4 +20397 ' McD' 4 +20398 ' McG' 4 +20399 ' McK' 4 +20400 ' McL' 4 +20401 ' McN' 4 +20402 ' MeV' 4 +20403 ' Med' 4 +20404 ' Meg' 4 +20405 ' Meh' 4 +20406 ' Mei' 4 +20407 ' Mel' 4 +20408 ' Mem' 4 +20409 ' Men' 4 +20410 ' Mer' 4 +20411 ' Mes' 4 +20412 ' Met' 4 +20413 ' Mex' 4 +20414 ' Mey' 4 +20415 ' Mia' 4 +20416 ' Mic' 4 +20417 ' Mid' 4 +20418 ' Mig' 4 +20419 ' Mik' 4 +20420 ' Mil' 4 +20421 ' Mim' 4 +20422 ' Min' 4 +20423 ' Mir' 4 +20424 ' Mis' 4 +20425 ' Mit' 4 +20426 ' Mix' 4 +20427 ' Miy' 4 +20428 ' Miz' 4 +20429 ' Mob' 4 +20430 ' Mod' 4 +20431 ' Mog' 4 +20432 ' Moh' 4 +20433 ' Mol' 4 +20434 ' Mom' 4 +20435 ' Mon' 4 +20436 ' Mor' 4 +20437 ' Mos' 4 +20438 ' Mot' 4 +20439 ' Mou' 4 +20440 ' Mov' 4 +20441 ' Moy' 4 +20442 ' Moz' 4 +20443 ' Mrs' 4 +20444 ' Msg' 4 +20445 ' Mud' 4 +20446 ' Mug' 4 +20447 ' Muk' 4 +20448 ' Mul' 4 +20449 ' Mum' 4 +20450 ' Mun' 4 +20451 ' Mur' 4 +20452 ' Mus' 4 +20453 ' Mut' 4 +20454 ' Mys' 4 +20455 ' Mé' 4 +20456 ' Mö' 4 +20457 ' Mü' 4 +20458 ' NAD' 4 +20459 ' NAS' 4 +20460 ' NAT' 4 +20461 ' NBA' 4 +20462 ' NBC' 4 +20463 ' NEC' 4 +20464 ' NET' 4 +20465 ' NEW' 4 +20466 ' NFC' 4 +20467 ' NFL' 4 +20468 ' NGC' 4 +20469 ' NGO' 4 +20470 ' NHL' 4 +20471 ' NHS' 4 +20472 ' NIC' 4 +20473 ' NIH' 4 +20474 ' NON' 4 +20475 ' NOR' 4 +20476 ' NOT' 4 +20477 ' NOW' 4 +20478 ' NPC' 4 +20479 ' NPR' 4 +20480 ' NRA' 4 +20481 ' NSA' 4 +20482 ' NSW' 4 +20483 ' NUM' 4 +20484 ' NYC' 4 +20485 ' NaN' 4 +20486 ' Nab' 4 +20487 ' Nad' 4 +20488 ' Nag' 4 +20489 ' Nah' 4 +20490 ' Naj' 4 +20491 ' Nak' 4 +20492 ' Nam' 4 +20493 ' Nan' 4 +20494 ' Nap' 4 +20495 ' Nar' 4 +20496 ' Nas' 4 +20497 ' Nat' 4 +20498 ' Nav' 4 +20499 ' Naz' 4 +20500 ' Neb' 4 +20501 ' Nec' 4 +20502 ' Ned' 4 +20503 ' Neg' 4 +20504 ' Nel' 4 +20505 ' Nem' 4 +20506 ' Neo' 4 +20507 ' Nep' 4 +20508 ' Ner' 4 +20509 ' Net' 4 +20510 ' Neu' 4 +20511 ' Nev' 4 +20512 ' New' 4 +20513 ' Nex' 4 +20514 ' Nic' 4 +20515 ' Nie' 4 +20516 ' Nig' 4 +20517 ' Nik' 4 +20518 ' Nil' 4 +20519 ' Nim' 4 +20520 ' Nin' 4 +20521 ' Nit' 4 +20522 ' Nob' 4 +20523 ' Nom' 4 +20524 ' Non' 4 +20525 ' Nor' 4 +20526 ' Nos' 4 +20527 ' Not' 4 +20528 ' Nou' 4 +20529 ' Nov' 4 +20530 ' Now' 4 +20531 ' Nug' 4 +20532 ' Num' 4 +20533 ' Nun' 4 +20534 ' Nur' 4 +20535 ' Nut' 4 +20536 ' Nä' 4 +20537 ' Né' 4 +20538 ' OCD' 4 +20539 ' OCT' 4 +20540 ' OFF' 4 +20541 ' ONE' 4 +20542 ' OPT' 4 +20543 ' OUR' 4 +20544 ' OUT' 4 +20545 ' Oak' 4 +20546 ' Obj' 4 +20547 ' Obl' 4 +20548 ' Obs' 4 +20549 ' Occ' 4 +20550 ' Oct' 4 +20551 ' Odd' 4 +20552 ' Off' 4 +20553 ' Oil' 4 +20554 ' Old' 4 +20555 ' Ole' 4 +20556 ' One' 4 +20557 ' Ont' 4 +20558 ' Opp' 4 +20559 ' Ops' 4 +20560 ' Opt' 4 +20561 ' Orb' 4 +20562 ' Ord' 4 +20563 ' Ore' 4 +20564 ' Org' 4 +20565 ' Ori' 4 +20566 ' Orn' 4 +20567 ' Ort' 4 +20568 ' Osc' 4 +20569 ' Ost' 4 +20570 ' Ott' 4 +20571 ' Our' 4 +20572 ' Out' 4 +20573 ' Own' 4 +20574 ' PAC' 4 +20575 ' PAD' 4 +20576 ' PAL' 4 +20577 ' PAN' 4 +20578 ' PAR' 4 +20579 ' PAS' 4 +20580 ' PAT' 4 +20581 ' PAY' 4 +20582 ' PBS' 4 +20583 ' PCA' 4 +20584 ' PCB' 4 +20585 ' PCI' 4 +20586 ' PCR' 4 +20587 ' PCs' 4 +20588 ' PDB' 4 +20589 ' PDF' 4 +20590 ' PDO' 4 +20591 ' PDT' 4 +20592 ' PEM' 4 +20593 ' PER' 4 +20594 ' PET' 4 +20595 ' PHP' 4 +20596 ' PHY' 4 +20597 ' PID' 4 +20598 ' PIL' 4 +20599 ' PIN' 4 +20600 ' PLA' 4 +20601 ' PLC' 4 +20602 ' PLL' 4 +20603 ' PMC' 4 +20604 ' PNG' 4 +20605 ' POL' 4 +20606 ' POP' 4 +20607 ' POS' 4 +20608 ' PPP' 4 +20609 ' PRE' 4 +20610 ' PRI' 4 +20611 ' PRO' 4 +20612 ' PSA' 4 +20613 ' PSD' 4 +20614 ' PST' 4 +20615 ' PUR' 4 +20616 ' PUT' 4 +20617 ' PVC' 4 +20618 ' Pac' 4 +20619 ' Pad' 4 +20620 ' Pag' 4 +20621 ' Pak' 4 +20622 ' Pal' 4 +20623 ' Pam' 4 +20624 ' Pan' 4 +20625 ' Pap' 4 +20626 ' Par' 4 +20627 ' Pas' 4 +20628 ' Pat' 4 +20629 ' Pav' 4 +20630 ' Paw' 4 +20631 ' Pay' 4 +20632 ' Paz' 4 +20633 ' Pdf' 4 +20634 ' Pec' 4 +20635 ' Ped' 4 +20636 ' Peg' 4 +20637 ' Pel' 4 +20638 ' Pen' 4 +20639 ' Pep' 4 +20640 ' Per' 4 +20641 ' Pes' 4 +20642 ' Pet' 4 +20643 ' PhD' 4 +20644 ' Phi' 4 +20645 ' Pho' 4 +20646 ' Pic' 4 +20647 ' Pie' 4 +20648 ' Pig' 4 +20649 ' Pik' 4 +20650 ' Pil' 4 +20651 ' Pin' 4 +20652 ' Pip' 4 +20653 ' Pir' 4 +20654 ' Pis' 4 +20655 ' Pit' 4 +20656 ' Pix' 4 +20657 ' Ple' 4 +20658 ' Ply' 4 +20659 ' Pod' 4 +20660 ' Pok' 4 +20661 ' Pol' 4 +20662 ' Pom' 4 +20663 ' Pon' 4 +20664 ' Pop' 4 +20665 ' Por' 4 +20666 ' Pos' 4 +20667 ' Pot' 4 +20668 ' Pow' 4 +20669 ' Poz' 4 +20670 ' Pra' 4 +20671 ' Pre' 4 +20672 ' Pri' 4 +20673 ' Pro' 4 +20674 ' Psy' 4 +20675 ' Pub' 4 +20676 ' Pul' 4 +20677 ' Pun' 4 +20678 ' Pur' 4 +20679 ' Put' 4 +20680 ' Pé' 4 +20681 ' QUE' 4 +20682 ' Que' 4 +20683 ' Qui' 4 +20684 ' RAD' 4 +20685 ' RAF' 4 +20686 ' RAM' 4 +20687 ' RAW' 4 +20688 ' RBI' 4 +20689 ' REC' 4 +20690 ' RED' 4 +20691 ' REF' 4 +20692 ' REG' 4 +20693 ' REL' 4 +20694 ' REM' 4 +20695 ' RES' 4 +20696 ' RET' 4 +20697 ' RFC' 4 +20698 ' RGB' 4 +20699 ' RIP' 4 +20700 ' RMS' 4 +20701 ' RNA' 4 +20702 ' ROC' 4 +20703 ' ROI' 4 +20704 ' ROM' 4 +20705 ' ROS' 4 +20706 ' ROT' 4 +20707 ' RPC' 4 +20708 ' RPG' 4 +20709 ' RPM' 4 +20710 ' RSA' 4 +20711 ' RSS' 4 +20712 ' RUN' 4 +20713 ' Rab' 4 +20714 ' Rac' 4 +20715 ' Rad' 4 +20716 ' Raf' 4 +20717 ' Rag' 4 +20718 ' Rah' 4 +20719 ' Raj' 4 +20720 ' Rak' 4 +20721 ' Ram' 4 +20722 ' Ran' 4 +20723 ' Rao' 4 +20724 ' Rap' 4 +20725 ' Ras' 4 +20726 ' Rat' 4 +20727 ' Rav' 4 +20728 ' Raw' 4 +20729 ' Ray' 4 +20730 ' Raz' 4 +20731 ' Reb' 4 +20732 ' Rec' 4 +20733 ' Red' 4 +20734 ' Ref' 4 +20735 ' Reg' 4 +20736 ' Rei' 4 +20737 ' Rel' 4 +20738 ' Rem' 4 +20739 ' Ren' 4 +20740 ' Rep' 4 +20741 ' Res' 4 +20742 ' Ret' 4 +20743 ' Rev' 4 +20744 ' Rew' 4 +20745 ' Rex' 4 +20746 ' Rey' 4 +20747 ' Rhe' 4 +20748 ' Rib' 4 +20749 ' Ric' 4 +20750 ' Rid' 4 +20751 ' Rif' 4 +20752 ' Rig' 4 +20753 ' Rim' 4 +20754 ' Rin' 4 +20755 ' Rio' 4 +20756 ' Rip' 4 +20757 ' Ris' 4 +20758 ' Rit' 4 +20759 ' Riv' 4 +20760 ' Rob' 4 +20761 ' Roc' 4 +20762 ' Rod' 4 +20763 ' Rog' 4 +20764 ' Roh' 4 +20765 ' Rol' 4 +20766 ' Rom' 4 +20767 ' Ron' 4 +20768 ' Ros' 4 +20769 ' Rot' 4 +20770 ' Rou' 4 +20771 ' Row' 4 +20772 ' Rox' 4 +20773 ' Roy' 4 +20774 ' Rub' 4 +20775 ' Rud' 4 +20776 ' Rue' 4 +20777 ' Rug' 4 +20778 ' Rum' 4 +20779 ' Run' 4 +20780 ' Rus' 4 +20781 ' Rut' 4 +20782 ' Ré' 4 +20783 ' Rö' 4 +20784 ' SAF' 4 +20785 ' SAL' 4 +20786 ' SAM' 4 +20787 ' SAN' 4 +20788 ' SAP' 4 +20789 ' SAR' 4 +20790 ' SAS' 4 +20791 ' SAT' 4 +20792 ' SCH' 4 +20793 ' SCI' 4 +20794 ' SCM' 4 +20795 ' SCO' 4 +20796 ' SDK' 4 +20797 ' SDL' 4 +20798 ' SDS' 4 +20799 ' SEC' 4 +20800 ' SEE' 4 +20801 ' SEL' 4 +20802 ' SEM' 4 +20803 ' SEO' 4 +20804 ' SER' 4 +20805 ' SES' 4 +20806 ' SET' 4 +20807 ' SGD' 4 +20808 ' SHA' 4 +20809 ' SHE' 4 +20810 ' SHO' 4 +20811 ' SIG' 4 +20812 ' SIL' 4 +20813 ' SIM' 4 +20814 ' SIP' 4 +20815 ' SMB' 4 +20816 ' SMS' 4 +20817 ' SNP' 4 +20818 ' SOC' 4 +20819 ' SOL' 4 +20820 ' SOM' 4 +20821 ' SOS' 4 +20822 ' SPD' 4 +20823 ' SPE' 4 +20824 ' SPI' 4 +20825 ' SPR' 4 +20826 ' SQL' 4 +20827 ' SSD' 4 +20828 ' SSH' 4 +20829 ' SSL' 4 +20830 ' STD' 4 +20831 ' STE' 4 +20832 ' STR' 4 +20833 ' SUB' 4 +20834 ' SUM' 4 +20835 ' SUN' 4 +20836 ' SUP' 4 +20837 ' SUR' 4 +20838 ' SUS' 4 +20839 ' SUV' 4 +20840 ' SVG' 4 +20841 ' SVM' 4 +20842 ' Sab' 4 +20843 ' Sac' 4 +20844 ' Sad' 4 +20845 ' Saf' 4 +20846 ' Sag' 4 +20847 ' Sah' 4 +20848 ' Sai' 4 +20849 ' Sak' 4 +20850 ' Sal' 4 +20851 ' Sam' 4 +20852 ' San' 4 +20853 ' Sap' 4 +20854 ' Sar' 4 +20855 ' Sas' 4 +20856 ' Sat' 4 +20857 ' Sau' 4 +20858 ' Sav' 4 +20859 ' Saw' 4 +20860 ' Sax' 4 +20861 ' Say' 4 +20862 ' Sch' 4 +20863 ' Sci' 4 +20864 ' Sco' 4 +20865 ' Scr' 4 +20866 ' Sea' 4 +20867 ' Sec' 4 +20868 ' Sed' 4 +20869 ' See' 4 +20870 ' Seg' 4 +20871 ' Sek' 4 +20872 ' Sel' 4 +20873 ' Sem' 4 +20874 ' Sen' 4 +20875 ' Sep' 4 +20876 ' Seq' 4 +20877 ' Ser' 4 +20878 ' Ses' 4 +20879 ' Set' 4 +20880 ' Sew' 4 +20881 ' Sex' 4 +20882 ' Sey' 4 +20883 ' Sgt' 4 +20884 ' Sha' 4 +20885 ' She' 4 +20886 ' Shi' 4 +20887 ' Sho' 4 +20888 ' Sic' 4 +20889 ' Sid' 4 +20890 ' Sie' 4 +20891 ' Sig' 4 +20892 ' Sik' 4 +20893 ' Sil' 4 +20894 ' Sim' 4 +20895 ' Sin' 4 +20896 ' Sir' 4 +20897 ' Sit' 4 +20898 ' Six' 4 +20899 ' Ske' 4 +20900 ' Ski' 4 +20901 ' Sky' 4 +20902 ' Sob' 4 +20903 ' Soc' 4 +20904 ' Sof' 4 +20905 ' Sok' 4 +20906 ' Sol' 4 +20907 ' Som' 4 +20908 ' Son' 4 +20909 ' Sor' 4 +20910 ' Sou' 4 +20911 ' Sov' 4 +20912 ' Sox' 4 +20913 ' Soy' 4 +20914 ' Spa' 4 +20915 ' Spe' 4 +20916 ' Spl' 4 +20917 ' Spo' 4 +20918 ' Spr' 4 +20919 ' Spy' 4 +20920 ' Sql' 4 +20921 ' Squ' 4 +20922 ' Sri' 4 +20923 ' Sta' 4 +20924 ' Ste' 4 +20925 ' Sto' 4 +20926 ' Str' 4 +20927 ' Sty' 4 +20928 ' Sub' 4 +20929 ' Suc' 4 +20930 ' Sud' 4 +20931 ' Sue' 4 +20932 ' Sug' 4 +20933 ' Suk' 4 +20934 ' Sul' 4 +20935 ' Sum' 4 +20936 ' Sun' 4 +20937 ' Sup' 4 +20938 ' Sur' 4 +20939 ' Sus' 4 +20940 ' Suz' 4 +20941 ' Swe' 4 +20942 ' Syd' 4 +20943 ' Syl' 4 +20944 ' Sym' 4 +20945 ' Syn' 4 +20946 ' Sys' 4 +20947 ' Sé' 4 +20948 ' Sü' 4 +20949 ' TAB' 4 +20950 ' TAG' 4 +20951 ' TAM' 4 +20952 ' TCP' 4 +20953 ' TED' 4 +20954 ' TEM' 4 +20955 ' TER' 4 +20956 ' THE' 4 +20957 ' TIM' 4 +20958 ' TLS' 4 +20959 ' TOD' 4 +20960 ' TOP' 4 +20961 ' TPP' 4 +20962 ' TRA' 4 +20963 ' TRE' 4 +20964 ' TRI' 4 +20965 ' TWO' 4 +20966 ' Tab' 4 +20967 ' Tac' 4 +20968 ' Tag' 4 +20969 ' Tah' 4 +20970 ' Tai' 4 +20971 ' Taj' 4 +20972 ' Tak' 4 +20973 ' Tal' 4 +20974 ' Tam' 4 +20975 ' Tan' 4 +20976 ' Tao' 4 +20977 ' Tap' 4 +20978 ' Tar' 4 +20979 ' Tas' 4 +20980 ' Tat' 4 +20981 ' Tau' 4 +20982 ' Tax' 4 +20983 ' Tay' 4 +20984 ' Tea' 4 +20985 ' Tec' 4 +20986 ' Ted' 4 +20987 ' Teh' 4 +20988 ' Tek' 4 +20989 ' Tel' 4 +20990 ' Tem' 4 +20991 ' Ten' 4 +20992 ' Ter' 4 +20993 ' Tes' 4 +20994 ' Tet' 4 +20995 ' Tex' 4 +20996 ' The' 4 +20997 ' Thi' 4 +20998 ' Thr' 4 +20999 ' Thu' 4 +21000 ' Thy' 4 +21001 ' Tib' 4 +21002 ' Tie' 4 +21003 ' Tig' 4 +21004 ' Tik' 4 +21005 ' Til' 4 +21006 ' Tim' 4 +21007 ' Tin' 4 +21008 ' Tip' 4 +21009 ' Tir' 4 +21010 ' Tit' 4 +21011 ' Tob' 4 +21012 ' Tod' 4 +21013 ' Tok' 4 +21014 ' Tol' 4 +21015 ' Tom' 4 +21016 ' Ton' 4 +21017 ' Too' 4 +21018 ' Top' 4 +21019 ' Tor' 4 +21020 ' Tos' 4 +21021 ' Tot' 4 +21022 ' Tou' 4 +21023 ' Tow' 4 +21024 ' Toy' 4 +21025 ' Tra' 4 +21026 ' Tre' 4 +21027 ' Tri' 4 +21028 ' Tro' 4 +21029 ' Tru' 4 +21030 ' Try' 4 +21031 ' Tub' 4 +21032 ' Tuc' 4 +21033 ' Tud' 4 +21034 ' Tue' 4 +21035 ' Tul' 4 +21036 ' Tum' 4 +21037 ' Tun' 4 +21038 ' Tur' 4 +21039 ' Tus' 4 +21040 ' Tut' 4 +21041 ' Twe' 4 +21042 ' Two' 4 +21043 ' Typ' 4 +21044 ' Tyr' 4 +21045 ' UAE' 4 +21046 ' UDP' 4 +21047 ' UFC' 4 +21048 ' UFO' 4 +21049 ' UID' 4 +21050 ' UIT' 4 +21051 ' UPS' 4 +21052 ' URI' 4 +21053 ' URL' 4 +21054 ' USA' 4 +21055 ' USB' 4 +21056 ' USC' 4 +21057 ' USD' 4 +21058 ' USE' 4 +21059 ' USS' 4 +21060 ' UTC' 4 +21061 ' UTF' 4 +21062 ' Uhr' 4 +21063 ' Ult' 4 +21064 ' Una' 4 +21065 ' Und' 4 +21066 ' Une' 4 +21067 ' Ung' 4 +21068 ' Uni' 4 +21069 ' Uns' 4 +21070 ' Unt' 4 +21071 ' Urb' 4 +21072 ' Uri' 4 +21073 ' Url' 4 +21074 ' Urs' 4 +21075 ' Use' 4 +21076 ' Utt' 4 +21077 ' VAL' 4 +21078 ' VAR' 4 +21079 ' VAT' 4 +21080 ' VER' 4 +21081 ' VID' 4 +21082 ' VII' 4 +21083 ' VIP' 4 +21084 ' VIS' 4 +21085 ' VOC' 4 +21086 ' VOL' 4 +21087 ' VPN' 4 +21088 ' Vac' 4 +21089 ' Val' 4 +21090 ' Van' 4 +21091 ' Var' 4 +21092 ' Vas' 4 +21093 ' Vec' 4 +21094 ' Ved' 4 +21095 ' Veg' 4 +21096 ' Veh' 4 +21097 ' Vel' 4 +21098 ' Ven' 4 +21099 ' Ver' 4 +21100 ' Ves' 4 +21101 ' Via' 4 +21102 ' Vic' 4 +21103 ' Vid' 4 +21104 ' Vie' 4 +21105 ' Vig' 4 +21106 ' Vij' 4 +21107 ' Vik' 4 +21108 ' Vil' 4 +21109 ' Vim' 4 +21110 ' Vin' 4 +21111 ' Vir' 4 +21112 ' Vis' 4 +21113 ' Vit' 4 +21114 ' Viv' 4 +21115 ' Voc' 4 +21116 ' Vog' 4 +21117 ' Vol' 4 +21118 ' Von' 4 +21119 ' Vor' 4 +21120 ' Vox' 4 +21121 ' Voy' 4 +21122 ' Vue' 4 +21123 ' Vul' 4 +21124 ' Vé' 4 +21125 ' WAR' 4 +21126 ' WAS' 4 +21127 ' WAY' 4 +21128 ' WEB' 4 +21129 ' WHO' 4 +21130 ' WIN' 4 +21131 ' WIT' 4 +21132 ' WOR' 4 +21133 ' WWE' 4 +21134 ' Wah' 4 +21135 ' Wak' 4 +21136 ' Wal' 4 +21137 ' Wan' 4 +21138 ' War' 4 +21139 ' Was' 4 +21140 ' Wat' 4 +21141 ' Way' 4 +21142 ' Web' 4 +21143 ' Wed' 4 +21144 ' Wei' 4 +21145 ' Wel' 4 +21146 ' Wen' 4 +21147 ' Wer' 4 +21148 ' Wes' 4 +21149 ' Wet' 4 +21150 ' Whe' 4 +21151 ' Who' 4 +21152 ' Why' 4 +21153 ' Wid' 4 +21154 ' Wie' 4 +21155 ' Wii' 4 +21156 ' Wik' 4 +21157 ' Wil' 4 +21158 ' Win' 4 +21159 ' Wir' 4 +21160 ' Wis' 4 +21161 ' Wit' 4 +21162 ' Wol' 4 +21163 ' Won' 4 +21164 ' Woo' 4 +21165 ' Wor' 4 +21166 ' Wow' 4 +21167 ' Wyn' 4 +21168 ' XII' 4 +21169 ' XIV' 4 +21170 ' XML' 4 +21171 ' XOR' 4 +21172 ' XVI' 4 +21173 ' XXX' 4 +21174 ' Xen' 4 +21175 ' Xia' 4 +21176 ' Xin' 4 +21177 ' Xml' 4 +21178 ' YES' 4 +21179 ' YOU' 4 +21180 ' Yad' 4 +21181 ' Yak' 4 +21182 ' Yam' 4 +21183 ' Yan' 4 +21184 ' Yao' 4 +21185 ' Yas' 4 +21186 ' Yes' 4 +21187 ' Yet' 4 +21188 ' Yin' 4 +21189 ' You' 4 +21190 ' Yuk' 4 +21191 ' Yun' 4 +21192 ' Yus' 4 +21193 ' ZIP' 4 +21194 ' Zag' 4 +21195 ' Zah' 4 +21196 ' Zak' 4 +21197 ' Zam' 4 +21198 ' Zap' 4 +21199 ' Zar' 4 +21200 ' Zel' 4 +21201 ' Zen' 4 +21202 ' Zhu' 4 +21203 ' Zig' 4 +21204 ' Zip' 4 +21205 ' Zoe' 4 +21206 ' Zoo' 4 +21207 ' Zum' 4 +21208 ' Zur' 4 +21209 ' Zwe' 4 +21210 ' [],' 4 +21211 ' [];' 4 +21212 ' ___' 4 +21213 ' ``(' 4 +21214 ' ```' 4 +21215 ' aan' 4 +21216 ' abb' 4 +21217 ' abc' 4 +21218 ' abi' 4 +21219 ' abl' 4 +21220 ' abs' 4 +21221 ' aby' 4 +21222 ' acc' 4 +21223 ' ace' 4 +21224 ' ach' 4 +21225 ' acl' 4 +21226 ' act' 4 +21227 ' add' 4 +21228 ' ade' 4 +21229 ' adj' 4 +21230 ' adm' 4 +21231 ' ado' 4 +21232 ' ads' 4 +21233 ' adv' 4 +21234 ' aer' 4 +21235 ' aes' 4 +21236 ' aff' 4 +21237 ' aft' 4 +21238 ' age' 4 +21239 ' agg' 4 +21240 ' ago' 4 +21241 ' agr' 4 +21242 ' aid' 4 +21243 ' ail' 4 +21244 ' aim' 4 +21245 ' ain' 4 +21246 ' air' 4 +21247 ' aka' 4 +21248 ' akt' 4 +21249 ' alb' 4 +21250 ' alc' 4 +21251 ' ald' 4 +21252 ' ale' 4 +21253 ' alg' 4 +21254 ' ali' 4 +21255 ' alk' 4 +21256 ' all' 4 +21257 ' als' 4 +21258 ' alt' 4 +21259 ' ama' 4 +21260 ' amb' 4 +21261 ' ami' 4 +21262 ' amp' 4 +21263 ' ana' 4 +21264 ' anc' 4 +21265 ' and' 4 +21266 ' ang' 4 +21267 ' ank' 4 +21268 ' ann' 4 +21269 ' ano' 4 +21270 ' ans' 4 +21271 ' ant' 4 +21272 ' anx' 4 +21273 ' any' 4 +21274 ' aos' 4 +21275 ' aph' 4 +21276 ' api' 4 +21277 ' apo' 4 +21278 ' app' 4 +21279 ' apr' 4 +21280 ' apt' 4 +21281 ' aqu' 4 +21282 ' ara' 4 +21283 ' arb' 4 +21284 ' arc' 4 +21285 ' ard' 4 +21286 ' are' 4 +21287 ' arg' 4 +21288 ' ark' 4 +21289 ' arm' 4 +21290 ' arr' 4 +21291 ' art' 4 +21292 ' asc' 4 +21293 ' ash' 4 +21294 ' asi' 4 +21295 ' ask' 4 +21296 ' asm' 4 +21297 ' asp' 4 +21298 ' ass' 4 +21299 ' ast' 4 +21300 ' ate' 4 +21301 ' ath' 4 +21302 ' atm' 4 +21303 ' att' 4 +21304 ' auc' 4 +21305 ' aud' 4 +21306 ' auf' 4 +21307 ' aug' 4 +21308 ' aur' 4 +21309 ' aus' 4 +21310 ' aut' 4 +21311 ' aux' 4 +21312 ' ave' 4 +21313 ' avg' 4 +21314 ' avo' 4 +21315 ' awa' 4 +21316 ' awe' 4 +21317 ' awk' 4 +21318 ' aws' 4 +21319 ' axe' 4 +21320 ' aç' 4 +21321 ' añ' 4 +21322 ' až' 4 +21323 ' bab' 4 +21324 ' bac' 4 +21325 ' bad' 4 +21326 ' bag' 4 +21327 ' bak' 4 +21328 ' bal' 4 +21329 ' bam' 4 +21330 ' ban' 4 +21331 ' bar' 4 +21332 ' bas' 4 +21333 ' bat' 4 +21334 ' bay' 4 +21335 ' baz' 4 +21336 ' bec' 4 +21337 ' bed' 4 +21338 ' bee' 4 +21339 ' bef' 4 +21340 ' beg' 4 +21341 ' beh' 4 +21342 ' bei' 4 +21343 ' bek' 4 +21344 ' bel' 4 +21345 ' bem' 4 +21346 ' ben' 4 +21347 ' ber' 4 +21348 ' bes' 4 +21349 ' bet' 4 +21350 ' bew' 4 +21351 ' bey' 4 +21352 ' bez' 4 +21353 ' bib' 4 +21354 ' bic' 4 +21355 ' bid' 4 +21356 ' bif' 4 +21357 ' big' 4 +21358 ' bij' 4 +21359 ' bil' 4 +21360 ' bin' 4 +21361 ' bio' 4 +21362 ' bip' 4 +21363 ' bir' 4 +21364 ' bis' 4 +21365 ' bit' 4 +21366 ' biz' 4 +21367 ' bla' 4 +21368 ' ble' 4 +21369 ' blk' 4 +21370 ' blo' 4 +21371 ' bob' 4 +21372 ' bod' 4 +21373 ' bog' 4 +21374 ' bol' 4 +21375 ' bom' 4 +21376 ' bon' 4 +21377 ' boo' 4 +21378 ' bor' 4 +21379 ' bos' 4 +21380 ' bot' 4 +21381 ' bou' 4 +21382 ' bow' 4 +21383 ' box' 4 +21384 ' boy' 4 +21385 ' bra' 4 +21386 ' bre' 4 +21387 ' bri' 4 +21388 ' bro' 4 +21389 ' bru' 4 +21390 ' btn' 4 +21391 ' bub' 4 +21392 ' bud' 4 +21393 ' buf' 4 +21394 ' bug' 4 +21395 ' bul' 4 +21396 ' bum' 4 +21397 ' bun' 4 +21398 ' bur' 4 +21399 ' bus' 4 +21400 ' but' 4 +21401 ' buy' 4 +21402 ' bye' 4 +21403 ' bzw' 4 +21404 ' bä' 4 +21405 ' bé' 4 +21406 ' bý' 4 +21407 ' cab' 4 +21408 ' cac' 4 +21409 ' cad' 4 +21410 ' caf' 4 +21411 ' cal' 4 +21412 ' cam' 4 +21413 ' can' 4 +21414 ' cap' 4 +21415 ' car' 4 +21416 ' cas' 4 +21417 ' cat' 4 +21418 ' cav' 4 +21419 ' cel' 4 +21420 ' cen' 4 +21421 ' cep' 4 +21422 ' cer' 4 +21423 ' ces' 4 +21424 ' cet' 4 +21425 ' cfg' 4 +21426 ' cha' 4 +21427 ' che' 4 +21428 ' chi' 4 +21429 ' chk' 4 +21430 ' cho' 4 +21431 ' chr' 4 +21432 ' cic' 4 +21433 ' cid' 4 +21434 ' cig' 4 +21435 ' cin' 4 +21436 ' cir' 4 +21437 ' cis' 4 +21438 ' cit' 4 +21439 ' civ' 4 +21440 ' cla' 4 +21441 ' cle' 4 +21442 ' cli' 4 +21443 ' clo' 4 +21444 ' cls' 4 +21445 ' cmd' 4 +21446 ' cmp' 4 +21447 ' cnt' 4 +21448 ' cob' 4 +21449 ' coc' 4 +21450 ' cod' 4 +21451 ' cof' 4 +21452 ' cog' 4 +21453 ' coh' 4 +21454 ' col' 4 +21455 ' com' 4 +21456 ' con' 4 +21457 ' cop' 4 +21458 ' cor' 4 +21459 ' cos' 4 +21460 ' cot' 4 +21461 ' cou' 4 +21462 ' cov' 4 +21463 ' cow' 4 +21464 ' coy' 4 +21465 ' cpu' 4 +21466 ' cra' 4 +21467 ' cre' 4 +21468 ' cri' 4 +21469 ' cro' 4 +21470 ' cru' 4 +21471 ' cry' 4 +21472 ' css' 4 +21473 ' csv' 4 +21474 ' ctx' 4 +21475 ' cub' 4 +21476 ' cuc' 4 +21477 ' cue' 4 +21478 ' cui' 4 +21479 ' cul' 4 +21480 ' cum' 4 +21481 ' cup' 4 +21482 ' cur' 4 +21483 ' cus' 4 +21484 ' cut' 4 +21485 ' cyl' 4 +21486 ' cyn' 4 +21487 ' cyt' 4 +21488 ' cá' 4 +21489 ' câ' 4 +21490 ' cé' 4 +21491 ' cí' 4 +21492 ' có' 4 +21493 ' cô' 4 +21494 ' că' 4 +21495 ' cơ' 4 +21496 ' dab' 4 +21497 ' dad' 4 +21498 ' dag' 4 +21499 ' dah' 4 +21500 ' dai' 4 +21501 ' dal' 4 +21502 ' dam' 4 +21503 ' dan' 4 +21504 ' dao' 4 +21505 ' dar' 4 +21506 ' das' 4 +21507 ' dat' 4 +21508 ' dav' 4 +21509 ' day' 4 +21510 ' dbo' 4 +21511 ' deb' 4 +21512 ' dec' 4 +21513 ' ded' 4 +21514 ' dee' 4 +21515 ' def' 4 +21516 ' deg' 4 +21517 ' dei' 4 +21518 ' dej' 4 +21519 ' del' 4 +21520 ' dem' 4 +21521 ' den' 4 +21522 ' dep' 4 +21523 ' der' 4 +21524 ' des' 4 +21525 ' det' 4 +21526 ' dev' 4 +21527 ' dex' 4 +21528 ' dez' 4 +21529 ' dia' 4 +21530 ' dib' 4 +21531 ' dic' 4 +21532 ' did' 4 +21533 ' die' 4 +21534 ' dif' 4 +21535 ' dig' 4 +21536 ' dil' 4 +21537 ' dim' 4 +21538 ' din' 4 +21539 ' dio' 4 +21540 ' dip' 4 +21541 ' dir' 4 +21542 ' dis' 4 +21543 ' dit' 4 +21544 ' div' 4 +21545 ' diz' 4 +21546 ' dll' 4 +21547 ' dns' 4 +21548 ' dob' 4 +21549 ' doc' 4 +21550 ' dod' 4 +21551 ' dog' 4 +21552 ' doi' 4 +21553 ' dok' 4 +21554 ' dol' 4 +21555 ' dom' 4 +21556 ' don' 4 +21557 ' dop' 4 +21558 ' dor' 4 +21559 ' dos' 4 +21560 ' dot' 4 +21561 ' dou' 4 +21562 ' dow' 4 +21563 ' dpi' 4 +21564 ' dra' 4 +21565 ' dre' 4 +21566 ' dri' 4 +21567 ' dro' 4 +21568 ' dru' 4 +21569 ' dry' 4 +21570 ' dst' 4 +21571 ' dub' 4 +21572 ' due' 4 +21573 ' dug' 4 +21574 ' dum' 4 +21575 ' dun' 4 +21576 ' duo' 4 +21577 ' dup' 4 +21578 ' dur' 4 +21579 ' dus' 4 +21580 ' dut' 4 +21581 ' dye' 4 +21582 ' dyn' 4 +21583 ' dys' 4 +21584 ' dá' 4 +21585 ' då' 4 +21586 ' dé' 4 +21587 ' dí' 4 +21588 ' dó' 4 +21589 ' dü' 4 +21590 ' ear' 4 +21591 ' eas' 4 +21592 ' eat' 4 +21593 ' ecc' 4 +21594 ' ech' 4 +21595 ' ecl' 4 +21596 ' eco' 4 +21597 ' ect' 4 +21598 ' eds' 4 +21599 ' een' 4 +21600 ' eer' 4 +21601 ' eff' 4 +21602 ' egg' 4 +21603 ' ego' 4 +21604 ' egy' 4 +21605 ' eig' 4 +21606 ' ein' 4 +21607 ' ela' 4 +21608 ' ele' 4 +21609 ' elf' 4 +21610 ' ell' 4 +21611 ' els' 4 +21612 ' emb' 4 +21613 ' emo' 4 +21614 ' emp' 4 +21615 ' enc' 4 +21616 ' end' 4 +21617 ' enf' 4 +21618 ' eng' 4 +21619 ' enh' 4 +21620 ' ens' 4 +21621 ' ent' 4 +21622 ' env' 4 +21623 ' eos' 4 +21624 ' eps' 4 +21625 ' equ' 4 +21626 ' era' 4 +21627 ' ere' 4 +21628 ' erf' 4 +21629 ' erg' 4 +21630 ' ern' 4 +21631 ' err' 4 +21632 ' ers' 4 +21633 ' eru' 4 +21634 ' ery' 4 +21635 ' esa' 4 +21636 ' esc' 4 +21637 ' ese' 4 +21638 ' eso' 4 +21639 ' esp' 4 +21640 ' ess' 4 +21641 ' est' 4 +21642 ' eta' 4 +21643 ' etc' 4 +21644 ' eth' 4 +21645 ' ett' 4 +21646 ' eux' 4 +21647 ' eve' 4 +21648 ' evt' 4 +21649 ' exc' 4 +21650 ' exe' 4 +21651 ' exh' 4 +21652 ' exp' 4 +21653 ' ext' 4 +21654 ' eye' 4 +21655 ' fab' 4 +21656 ' fac' 4 +21657 ' fal' 4 +21658 ' fam' 4 +21659 ' fan' 4 +21660 ' far' 4 +21661 ' fas' 4 +21662 ' fat' 4 +21663 ' fav' 4 +21664 ' fax' 4 +21665 ' faz' 4 +21666 ' fed' 4 +21667 ' fee' 4 +21668 ' fel' 4 +21669 ' fem' 4 +21670 ' fen' 4 +21671 ' fer' 4 +21672 ' fet' 4 +21673 ' feu' 4 +21674 ' few' 4 +21675 ' fft' 4 +21676 ' fib' 4 +21677 ' fic' 4 +21678 ' fid' 4 +21679 ' fif' 4 +21680 ' fig' 4 +21681 ' fil' 4 +21682 ' fim' 4 +21683 ' fin' 4 +21684 ' fir' 4 +21685 ' fis' 4 +21686 ' fit' 4 +21687 ' fix' 4 +21688 ' fla' 4 +21689 ' fle' 4 +21690 ' flo' 4 +21691 ' flu' 4 +21692 ' fly' 4 +21693 ' fmt' 4 +21694 ' foc' 4 +21695 ' fog' 4 +21696 ' foi' 4 +21697 ' fol' 4 +21698 ' fon' 4 +21699 ' foo' 4 +21700 ' for' 4 +21701 ' fos' 4 +21702 ' fot' 4 +21703 ' fou' 4 +21704 ' fox' 4 +21705 ' fra' 4 +21706 ' fre' 4 +21707 ' fri' 4 +21708 ' frm' 4 +21709 ' fro' 4 +21710 ' fru' 4 +21711 ' fry' 4 +21712 ' ftp' 4 +21713 ' fue' 4 +21714 ' fug' 4 +21715 ' ful' 4 +21716 ' fun' 4 +21717 ' fur' 4 +21718 ' fus' 4 +21719 ' fut' 4 +21720 ' fá' 4 +21721 ' få' 4 +21722 ' fé' 4 +21723 ' fö' 4 +21724 ' fø' 4 +21725 ' fő' 4 +21726 ' gab' 4 +21727 ' gad' 4 +21728 ' gag' 4 +21729 ' gal' 4 +21730 ' gam' 4 +21731 ' gan' 4 +21732 ' gap' 4 +21733 ' gar' 4 +21734 ' gas' 4 +21735 ' gau' 4 +21736 ' gay' 4 +21737 ' gaz' 4 +21738 ' gcc' 4 +21739 ' gcd' 4 +21740 ' geb' 4 +21741 ' ged' 4 +21742 ' gef' 4 +21743 ' geg' 4 +21744 ' gek' 4 +21745 ' gel' 4 +21746 ' gem' 4 +21747 ' gen' 4 +21748 ' geo' 4 +21749 ' ger' 4 +21750 ' ges' 4 +21751 ' get' 4 +21752 ' gew' 4 +21753 ' gez' 4 +21754 ' gib' 4 +21755 ' gid' 4 +21756 ' gif' 4 +21757 ' gig' 4 +21758 ' gin' 4 +21759 ' gir' 4 +21760 ' git' 4 +21761 ' giv' 4 +21762 ' gle' 4 +21763 ' gli' 4 +21764 ' glo' 4 +21765 ' glu' 4 +21766 ' gly' 4 +21767 ' gob' 4 +21768 ' god' 4 +21769 ' gol' 4 +21770 ' gon' 4 +21771 ' gor' 4 +21772 ' got' 4 +21773 ' gou' 4 +21774 ' gpu' 4 +21775 ' gra' 4 +21776 ' gre' 4 +21777 ' gri' 4 +21778 ' gro' 4 +21779 ' gru' 4 +21780 ' gtk' 4 +21781 ' gui' 4 +21782 ' gul' 4 +21783 ' gum' 4 +21784 ' gun' 4 +21785 ' gut' 4 +21786 ' guy' 4 +21787 ' gym' 4 +21788 ' gå' 4 +21789 ' gé' 4 +21790 ' gö' 4 +21791 ' gü' 4 +21792 ' gł' 4 +21793 ' hab' 4 +21794 ' hac' 4 +21795 ' had' 4 +21796 ' hal' 4 +21797 ' ham' 4 +21798 ' han' 4 +21799 ' har' 4 +21800 ' has' 4 +21801 ' hat' 4 +21802 ' hav' 4 +21803 ' haw' 4 +21804 ' hay' 4 +21805 ' haz' 4 +21806 ' hed' 4 +21807 ' hel' 4 +21808 ' hem' 4 +21809 ' hen' 4 +21810 ' hep' 4 +21811 ' her' 4 +21812 ' hes' 4 +21813 ' het' 4 +21814 ' hex' 4 +21815 ' hey' 4 +21816 ' hid' 4 +21817 ' hig' 4 +21818 ' hij' 4 +21819 ' hil' 4 +21820 ' him' 4 +21821 ' hin' 4 +21822 ' hip' 4 +21823 ' his' 4 +21824 ' hit' 4 +21825 ' hob' 4 +21826 ' hoc' 4 +21827 ' hog' 4 +21828 ' hol' 4 +21829 ' hom' 4 +21830 ' hon' 4 +21831 ' hop' 4 +21832 ' hor' 4 +21833 ' hos' 4 +21834 ' hot' 4 +21835 ' how' 4 +21836 ' hrs' 4 +21837 ' htt' 4 +21838 ' hub' 4 +21839 ' hue' 4 +21840 ' hug' 4 +21841 ' huh' 4 +21842 ' hum' 4 +21843 ' hun' 4 +21844 ' hur' 4 +21845 ' hus' 4 +21846 ' hut' 4 +21847 ' hyd' 4 +21848 ' hym' 4 +21849 ' hyp' 4 +21850 ' há' 4 +21851 ' hä' 4 +21852 ' hå' 4 +21853 ' hé' 4 +21854 ' hö' 4 +21855 ' iOS' 4 +21856 ' ice' 4 +21857 ' ich' 4 +21858 ' ici' 4 +21859 ' icy' 4 +21860 ' ide' 4 +21861 ' idi' 4 +21862 ' ids' 4 +21863 ' idx' 4 +21864 ' iff' 4 +21865 ' ign' 4 +21866 ' ihm' 4 +21867 ' ihn' 4 +21868 ' ihr' 4 +21869 ' iii' 4 +21870 ' ile' 4 +21871 ' ili' 4 +21872 ' ill' 4 +21873 ' ils' 4 +21874 ' imb' 4 +21875 ' img' 4 +21876 ' imm' 4 +21877 ' imp' 4 +21878 ' inc' 4 +21879 ' ind' 4 +21880 ' inf' 4 +21881 ' ing' 4 +21882 ' inh' 4 +21883 ' ini' 4 +21884 ' inj' 4 +21885 ' ink' 4 +21886 ' inn' 4 +21887 ' ins' 4 +21888 ' int' 4 +21889 ' inv' 4 +21890 ' iod' 4 +21891 ' ion' 4 +21892 ' ios' 4 +21893 ' ips' 4 +21894 ' ire' 4 +21895 ' irr' 4 +21896 ' isn' 4 +21897 ' iso' 4 +21898 ' iss' 4 +21899 ' ist' 4 +21900 ' ith' 4 +21901 ' itr' 4 +21902 ' its' 4 +21903 ' iç' 4 +21904 ' iş' 4 +21905 ' jab' 4 +21906 ' jac' 4 +21907 ' jag' 4 +21908 ' jak' 4 +21909 ' jal' 4 +21910 ' jam' 4 +21911 ' jan' 4 +21912 ' jap' 4 +21913 ' jar' 4 +21914 ' jas' 4 +21915 ' jav' 4 +21916 ' jaw' 4 +21917 ' jed' 4 +21918 ' jej' 4 +21919 ' jel' 4 +21920 ' jer' 4 +21921 ' jet' 4 +21922 ' jeu' 4 +21923 ' jew' 4 +21924 ' job' 4 +21925 ' jog' 4 +21926 ' jou' 4 +21927 ' joy' 4 +21928 ' jud' 4 +21929 ' jug' 4 +21930 ' jul' 4 +21931 ' jun' 4 +21932 ' jur' 4 +21933 ' jus' 4 +21934 ' já' 4 +21935 ' jä' 4 +21936 ' jó' 4 +21937 ' jú' 4 +21938 ' kHz' 4 +21939 ' kad' 4 +21940 ' kal' 4 +21941 ' kam' 4 +21942 ' kan' 4 +21943 ' kap' 4 +21944 ' kar' 4 +21945 ' kas' 4 +21946 ' kat' 4 +21947 ' kay' 4 +21948 ' kde' 4 +21949 ' kel' 4 +21950 ' ker' 4 +21951 ' ket' 4 +21952 ' key' 4 +21953 ' kid' 4 +21954 ' kil' 4 +21955 ' kin' 4 +21956 ' kir' 4 +21957 ' kit' 4 +21958 ' kle' 4 +21959 ' kne' 4 +21960 ' kol' 4 +21961 ' kom' 4 +21962 ' kon' 4 +21963 ' kop' 4 +21964 ' kor' 4 +21965 ' kos' 4 +21966 ' kot' 4 +21967 ' kre' 4 +21968 ' kun' 4 +21969 ' kur' 4 +21970 ' kä' 4 +21971 ' ké' 4 +21972 ' kö' 4 +21973 ' kø' 4 +21974 ' kü' 4 +21975 ' kā' 4 +21976 ' lab' 4 +21977 ' lac' 4 +21978 ' lad' 4 +21979 ' lag' 4 +21980 ' lak' 4 +21981 ' lam' 4 +21982 ' lan' 4 +21983 ' lap' 4 +21984 ' lar' 4 +21985 ' las' 4 +21986 ' lat' 4 +21987 ' lav' 4 +21988 ' law' 4 +21989 ' lax' 4 +21990 ' lay' 4 +21991 ' laz' 4 +21992 ' lbl' 4 +21993 ' lbs' 4 +21994 ' led' 4 +21995 ' leg' 4 +21996 ' lei' 4 +21997 ' lem' 4 +21998 ' len' 4 +21999 ' ler' 4 +22000 ' les' 4 +22001 ' let' 4 +22002 ' lev' 4 +22003 ' lex' 4 +22004 ' lhs' 4 +22005 ' lia' 4 +22006 ' lib' 4 +22007 ' lic' 4 +22008 ' lid' 4 +22009 ' lie' 4 +22010 ' lif' 4 +22011 ' lig' 4 +22012 ' lik' 4 +22013 ' lil' 4 +22014 ' lim' 4 +22015 ' lin' 4 +22016 ' lip' 4 +22017 ' lis' 4 +22018 ' lit' 4 +22019 ' liv' 4 +22020 ' lle' 4 +22021 ' lng' 4 +22022 ' lob' 4 +22023 ' loc' 4 +22024 ' lod' 4 +22025 ' log' 4 +22026 ' loi' 4 +22027 ' lok' 4 +22028 ' lol' 4 +22029 ' lon' 4 +22030 ' los' 4 +22031 ' lot' 4 +22032 ' lou' 4 +22033 ' lov' 4 +22034 ' low' 4 +22035 ' lst' 4 +22036 ' lua' 4 +22037 ' lub' 4 +22038 ' luc' 4 +22039 ' lud' 4 +22040 ' lug' 4 +22041 ' lui' 4 +22042 ' lum' 4 +22043 ' lun' 4 +22044 ' lup' 4 +22045 ' lur' 4 +22046 ' lut' 4 +22047 ' lux' 4 +22048 ' lyr' 4 +22049 ' lys' 4 +22050 ' là' 4 +22051 ' lá' 4 +22052 ' lä' 4 +22053 ' lå' 4 +22054 ' læ' 4 +22055 ' lé' 4 +22056 ' lí' 4 +22057 ' lö' 4 +22058 ' lø' 4 +22059 ' mac' 4 +22060 ' mad' 4 +22061 ' mag' 4 +22062 ' mah' 4 +22063 ' mai' 4 +22064 ' maj' 4 +22065 ' mak' 4 +22066 ' mal' 4 +22067 ' mam' 4 +22068 ' man' 4 +22069 ' map' 4 +22070 ' mar' 4 +22071 ' mas' 4 +22072 ' mat' 4 +22073 ' max' 4 +22074 ' may' 4 +22075 ' mec' 4 +22076 ' med' 4 +22077 ' meg' 4 +22078 ' mel' 4 +22079 ' mem' 4 +22080 ' men' 4 +22081 ' mer' 4 +22082 ' mes' 4 +22083 ' met' 4 +22084 ' meu' 4 +22085 ' mex' 4 +22086 ' mez' 4 +22087 ' miR' 4 +22088 ' mic' 4 +22089 ' mid' 4 +22090 ' mie' 4 +22091 ' mig' 4 +22092 ' mij' 4 +22093 ' mil' 4 +22094 ' mim' 4 +22095 ' min' 4 +22096 ' mir' 4 +22097 ' mis' 4 +22098 ' mit' 4 +22099 ' mix' 4 +22100 ' mob' 4 +22101 ' mod' 4 +22102 ' mog' 4 +22103 ' moi' 4 +22104 ' mol' 4 +22105 ' mom' 4 +22106 ' mon' 4 +22107 ' mor' 4 +22108 ' mos' 4 +22109 ' mot' 4 +22110 ' mou' 4 +22111 ' mov' 4 +22112 ' moy' 4 +22113 ' mph' 4 +22114 ' msg' 4 +22115 ' muc' 4 +22116 ' mud' 4 +22117 ' mug' 4 +22118 ' mul' 4 +22119 ' mum' 4 +22120 ' mun' 4 +22121 ' mur' 4 +22122 ' mus' 4 +22123 ' mut' 4 +22124 ' muy' 4 +22125 ' mys' 4 +22126 ' mà' 4 +22127 ' má' 4 +22128 ' mã' 4 +22129 ' må' 4 +22130 ' mé' 4 +22131 ' mí' 4 +22132 ' mó' 4 +22133 ' mô' 4 +22134 ' mö' 4 +22135 ' mø' 4 +22136 ' mú' 4 +22137 ' mü' 4 +22138 ' mě' 4 +22139 ' mű' 4 +22140 ' nab' 4 +22141 ' nad' 4 +22142 ' nag' 4 +22143 ' nah' 4 +22144 ' naj' 4 +22145 ' nak' 4 +22146 ' nal' 4 +22147 ' nam' 4 +22148 ' nan' 4 +22149 ' nap' 4 +22150 ' nar' 4 +22151 ' nas' 4 +22152 ' nat' 4 +22153 ' nau' 4 +22154 ' nav' 4 +22155 ' naz' 4 +22156 ' neb' 4 +22157 ' nec' 4 +22158 ' ned' 4 +22159 ' neg' 4 +22160 ' nel' 4 +22161 ' nem' 4 +22162 ' nen' 4 +22163 ' neo' 4 +22164 ' nep' 4 +22165 ' ner' 4 +22166 ' net' 4 +22167 ' neu' 4 +22168 ' new' 4 +22169 ' nex' 4 +22170 ' nib' 4 +22171 ' nic' 4 +22172 ' nid' 4 +22173 ' nie' 4 +22174 ' nig' 4 +22175 ' nil' 4 +22176 ' nim' 4 +22177 ' nin' 4 +22178 ' nit' 4 +22179 ' nob' 4 +22180 ' noc' 4 +22181 ' nod' 4 +22182 ' nog' 4 +22183 ' nom' 4 +22184 ' non' 4 +22185 ' nor' 4 +22186 ' nos' 4 +22187 ' not' 4 +22188 ' nou' 4 +22189 ' nov' 4 +22190 ' now' 4 +22191 ' npc' 4 +22192 ' npm' 4 +22193 ' nth' 4 +22194 ' nud' 4 +22195 ' nue' 4 +22196 ' num' 4 +22197 ' nun' 4 +22198 ' nur' 4 +22199 ' nut' 4 +22200 ' ná' 4 +22201 ' nä' 4 +22202 ' nå' 4 +22203 ' né' 4 +22204 ' në' 4 +22205 ' nó' 4 +22206 ' nú' 4 +22207 ' ně' 4 +22208 ' oak' 4 +22209 ' obj' 4 +22210 ' obl' 4 +22211 ' obs' 4 +22212 ' obt' 4 +22213 ' occ' 4 +22214 ' och' 4 +22215 ' oct' 4 +22216 ' odd' 4 +22217 ' ode' 4 +22218 ' off' 4 +22219 ' oft' 4 +22220 ' oil' 4 +22221 ' old' 4 +22222 ' ole' 4 +22223 ' oli' 4 +22224 ' omn' 4 +22225 ' onc' 4 +22226 ' one' 4 +22227 ' ont' 4 +22228 ' ook' 4 +22229 ' opp' 4 +22230 ' ops' 4 +22231 ' opt' 4 +22232 ' ora' 4 +22233 ' orb' 4 +22234 ' ord' 4 +22235 ' ore' 4 +22236 ' org' 4 +22237 ' ori' 4 +22238 ' orn' 4 +22239 ' oro' 4 +22240 ' ort' 4 +22241 ' osc' 4 +22242 ' osm' 4 +22243 ' osp' 4 +22244 ' oss' 4 +22245 ' ost' 4 +22246 ' ott' 4 +22247 ' oun' 4 +22248 ' our' 4 +22249 ' out' 4 +22250 ' owe' 4 +22251 ' own' 4 +22252 ' oxy' 4 +22253 ' où' 4 +22254 ' pac' 4 +22255 ' pad' 4 +22256 ' pag' 4 +22257 ' pai' 4 +22258 ' pak' 4 +22259 ' pal' 4 +22260 ' pam' 4 +22261 ' pan' 4 +22262 ' pap' 4 +22263 ' par' 4 +22264 ' pas' 4 +22265 ' pat' 4 +22266 ' pau' 4 +22267 ' pav' 4 +22268 ' paw' 4 +22269 ' pay' 4 +22270 ' pdf' 4 +22271 ' pec' 4 +22272 ' ped' 4 +22273 ' peg' 4 +22274 ' pel' 4 +22275 ' pem' 4 +22276 ' pen' 4 +22277 ' pep' 4 +22278 ' per' 4 +22279 ' pes' 4 +22280 ' pet' 4 +22281 ' peu' 4 +22282 ' phi' 4 +22283 ' php' 4 +22284 ' phr' 4 +22285 ' phy' 4 +22286 ' pic' 4 +22287 ' pid' 4 +22288 ' pie' 4 +22289 ' pig' 4 +22290 ' pil' 4 +22291 ' pin' 4 +22292 ' pip' 4 +22293 ' pir' 4 +22294 ' pis' 4 +22295 ' pit' 4 +22296 ' piv' 4 +22297 ' pix' 4 +22298 ' pkg' 4 +22299 ' pla' 4 +22300 ' ple' 4 +22301 ' plt' 4 +22302 ' ply' 4 +22303 ' png' 4 +22304 ' pob' 4 +22305 ' poc' 4 +22306 ' pod' 4 +22307 ' pog' 4 +22308 ' poi' 4 +22309 ' pok' 4 +22310 ' pol' 4 +22311 ' pom' 4 +22312 ' pon' 4 +22313 ' pop' 4 +22314 ' por' 4 +22315 ' pos' 4 +22316 ' pot' 4 +22317 ' pou' 4 +22318 ' pov' 4 +22319 ' pow' 4 +22320 ' poz' 4 +22321 ' ppm' 4 +22322 ' pra' 4 +22323 ' pre' 4 +22324 ' pri' 4 +22325 ' pro' 4 +22326 ' prz' 4 +22327 ' pse' 4 +22328 ' psi' 4 +22329 ' psy' 4 +22330 ' ptr' 4 +22331 ' pts' 4 +22332 ' pub' 4 +22333 ' pud' 4 +22334 ' pul' 4 +22335 ' pun' 4 +22336 ' pup' 4 +22337 ' pur' 4 +22338 ' pus' 4 +22339 ' put' 4 +22340 ' pyg' 4 +22341 ' pyl' 4 +22342 ' pá' 4 +22343 ' pä' 4 +22344 ' på' 4 +22345 ' pé' 4 +22346 ' pó' 4 +22347 ' pł' 4 +22348 ' př' 4 +22349 ' pů' 4 +22350 ' que' 4 +22351 ' qui' 4 +22352 ' quo' 4 +22353 ' rab' 4 +22354 ' rac' 4 +22355 ' rad' 4 +22356 ' rag' 4 +22357 ' ram' 4 +22358 ' ran' 4 +22359 ' rap' 4 +22360 ' ras' 4 +22361 ' rat' 4 +22362 ' rav' 4 +22363 ' raw' 4 +22364 ' ray' 4 +22365 ' raz' 4 +22366 ' reb' 4 +22367 ' rec' 4 +22368 ' red' 4 +22369 ' ref' 4 +22370 ' reg' 4 +22371 ' rel' 4 +22372 ' rem' 4 +22373 ' ren' 4 +22374 ' rep' 4 +22375 ' req' 4 +22376 ' rer' 4 +22377 ' res' 4 +22378 ' ret' 4 +22379 ' rev' 4 +22380 ' rez' 4 +22381 ' rgb' 4 +22382 ' rhe' 4 +22383 ' rho' 4 +22384 ' rhs' 4 +22385 ' rib' 4 +22386 ' ric' 4 +22387 ' rid' 4 +22388 ' rif' 4 +22389 ' rig' 4 +22390 ' rim' 4 +22391 ' rin' 4 +22392 ' rip' 4 +22393 ' ris' 4 +22394 ' rit' 4 +22395 ' riv' 4 +22396 ' rms' 4 +22397 ' rng' 4 +22398 ' rob' 4 +22399 ' roc' 4 +22400 ' rod' 4 +22401 ' roi' 4 +22402 ' rol' 4 +22403 ' rom' 4 +22404 ' ros' 4 +22405 ' rot' 4 +22406 ' rou' 4 +22407 ' row' 4 +22408 ' roy' 4 +22409 ' roz' 4 +22410 ' rpm' 4 +22411 ' rst' 4 +22412 ' rub' 4 +22413 ' rud' 4 +22414 ' rue' 4 +22415 ' rug' 4 +22416 ' rul' 4 +22417 ' rum' 4 +22418 ' run' 4 +22419 ' rus' 4 +22420 ' rut' 4 +22421 ' rá' 4 +22422 ' rå' 4 +22423 ' rè' 4 +22424 ' ré' 4 +22425 ' rê' 4 +22426 ' sab' 4 +22427 ' sac' 4 +22428 ' sad' 4 +22429 ' saf' 4 +22430 ' sag' 4 +22431 ' sal' 4 +22432 ' sam' 4 +22433 ' san' 4 +22434 ' sap' 4 +22435 ' sar' 4 +22436 ' sat' 4 +22437 ' sau' 4 +22438 ' sav' 4 +22439 ' saw' 4 +22440 ' sax' 4 +22441 ' say' 4 +22442 ' sch' 4 +22443 ' sci' 4 +22444 ' sco' 4 +22445 ' scr' 4 +22446 ' sea' 4 +22447 ' sec' 4 +22448 ' sed' 4 +22449 ' see' 4 +22450 ' seg' 4 +22451 ' sei' 4 +22452 ' sel' 4 +22453 ' sem' 4 +22454 ' sen' 4 +22455 ' sep' 4 +22456 ' seq' 4 +22457 ' ser' 4 +22458 ' ses' 4 +22459 ' set' 4 +22460 ' seu' 4 +22461 ' sew' 4 +22462 ' sex' 4 +22463 ' sha' 4 +22464 ' she' 4 +22465 ' sho' 4 +22466 ' shr' 4 +22467 ' shy' 4 +22468 ' sia' 4 +22469 ' sib' 4 +22470 ' sic' 4 +22471 ' sid' 4 +22472 ' sie' 4 +22473 ' sig' 4 +22474 ' sil' 4 +22475 ' sim' 4 +22476 ' sin' 4 +22477 ' sip' 4 +22478 ' sir' 4 +22479 ' sis' 4 +22480 ' sit' 4 +22481 ' six' 4 +22482 ' ske' 4 +22483 ' ski' 4 +22484 ' sku' 4 +22485 ' sky' 4 +22486 ' sla' 4 +22487 ' sle' 4 +22488 ' sme' 4 +22489 ' smo' 4 +22490 ' sms' 4 +22491 ' snd' 4 +22492 ' sne' 4 +22493 ' sob' 4 +22494 ' soc' 4 +22495 ' sod' 4 +22496 ' sog' 4 +22497 ' sol' 4 +22498 ' som' 4 +22499 ' son' 4 +22500 ' sop' 4 +22501 ' sor' 4 +22502 ' sou' 4 +22503 ' sow' 4 +22504 ' soy' 4 +22505 ' spa' 4 +22506 ' spe' 4 +22507 ' sph' 4 +22508 ' spl' 4 +22509 ' spo' 4 +22510 ' spp' 4 +22511 ' spr' 4 +22512 ' spy' 4 +22513 ' sql' 4 +22514 ' squ' 4 +22515 ' src' 4 +22516 ' ssh' 4 +22517 ' ssl' 4 +22518 ' sta' 4 +22519 ' std' 4 +22520 ' ste' 4 +22521 ' sto' 4 +22522 ' str' 4 +22523 ' sty' 4 +22524 ' sua' 4 +22525 ' sub' 4 +22526 ' suc' 4 +22527 ' sud' 4 +22528 ' sue' 4 +22529 ' suf' 4 +22530 ' sug' 4 +22531 ' sul' 4 +22532 ' sum' 4 +22533 ' sun' 4 +22534 ' suo' 4 +22535 ' sup' 4 +22536 ' sur' 4 +22537 ' sus' 4 +22538 ' sut' 4 +22539 ' svg' 4 +22540 ' swe' 4 +22541 ' swo' 4 +22542 ' sym' 4 +22543 ' syn' 4 +22544 ' sys' 4 +22545 ' sä' 4 +22546 ' så' 4 +22547 ' sæ' 4 +22548 ' sé' 4 +22549 ' sí' 4 +22550 ' só' 4 +22551 ' sø' 4 +22552 ' sú' 4 +22553 ' sû' 4 +22554 ' sü' 4 +22555 ' să' 4 +22556 ' są' 4 +22557 ' sł' 4 +22558 ' tab' 4 +22559 ' tac' 4 +22560 ' tad' 4 +22561 ' tag' 4 +22562 ' tai' 4 +22563 ' tak' 4 +22564 ' tal' 4 +22565 ' tam' 4 +22566 ' tan' 4 +22567 ' tap' 4 +22568 ' tar' 4 +22569 ' tas' 4 +22570 ' tat' 4 +22571 ' tau' 4 +22572 ' tax' 4 +22573 ' tbl' 4 +22574 ' tcp' 4 +22575 ' tea' 4 +22576 ' tec' 4 +22577 ' ted' 4 +22578 ' tee' 4 +22579 ' tej' 4 +22580 ' tek' 4 +22581 ' tel' 4 +22582 ' tem' 4 +22583 ' ten' 4 +22584 ' ter' 4 +22585 ' tes' 4 +22586 ' tet' 4 +22587 ' tex' 4 +22588 ' tgt' 4 +22589 ' tha' 4 +22590 ' the' 4 +22591 ' thi' 4 +22592 ' tho' 4 +22593 ' thr' 4 +22594 ' thy' 4 +22595 ' tib' 4 +22596 ' tic' 4 +22597 ' tid' 4 +22598 ' tie' 4 +22599 ' til' 4 +22600 ' tim' 4 +22601 ' tin' 4 +22602 ' tip' 4 +22603 ' tir' 4 +22604 ' tit' 4 +22605 ' tmp' 4 +22606 ' tob' 4 +22607 ' toc' 4 +22608 ' tod' 4 +22609 ' toe' 4 +22610 ' tok' 4 +22611 ' tol' 4 +22612 ' tom' 4 +22613 ' ton' 4 +22614 ' too' 4 +22615 ' top' 4 +22616 ' tor' 4 +22617 ' tot' 4 +22618 ' tou' 4 +22619 ' tow' 4 +22620 ' tox' 4 +22621 ' toy' 4 +22622 ' tra' 4 +22623 ' tre' 4 +22624 ' tri' 4 +22625 ' tro' 4 +22626 ' try' 4 +22627 ' tsp' 4 +22628 ' tub' 4 +22629 ' tud' 4 +22630 ' tug' 4 +22631 ' tul' 4 +22632 ' tum' 4 +22633 ' tun' 4 +22634 ' tup' 4 +22635 ' tur' 4 +22636 ' tut' 4 +22637 ' twe' 4 +22638 ' two' 4 +22639 ' txt' 4 +22640 ' typ' 4 +22641 ' tyr' 4 +22642 ' tá' 4 +22643 ' tä' 4 +22644 ' té' 4 +22645 ' të' 4 +22646 ' tí' 4 +22647 ' tö' 4 +22648 ' tú' 4 +22649 ' uid' 4 +22650 ' uit' 4 +22651 ' ult' 4 +22652 ' uma' 4 +22653 ' umb' 4 +22654 ' una' 4 +22655 ' unb' 4 +22656 ' unc' 4 +22657 ' und' 4 +22658 ' une' 4 +22659 ' unf' 4 +22660 ' ung' 4 +22661 ' unh' 4 +22662 ' uni' 4 +22663 ' unl' 4 +22664 ' unm' 4 +22665 ' uno' 4 +22666 ' uns' 4 +22667 ' unt' 4 +22668 ' unw' 4 +22669 ' upd' 4 +22670 ' upl' 4 +22671 ' upp' 4 +22672 ' ups' 4 +22673 ' upt' 4 +22674 ' urb' 4 +22675 ' ure' 4 +22676 ' urg' 4 +22677 ' uri' 4 +22678 ' url' 4 +22679 ' urn' 4 +22680 ' usb' 4 +22681 ' use' 4 +22682 ' uso' 4 +22683 ' usu' 4 +22684 ' utf' 4 +22685 ' vac' 4 +22686 ' vad' 4 +22687 ' vag' 4 +22688 ' vai' 4 +22689 ' val' 4 +22690 ' van' 4 +22691 ' vap' 4 +22692 ' var' 4 +22693 ' vas' 4 +22694 ' vec' 4 +22695 ' ved' 4 +22696 ' veg' 4 +22697 ' veh' 4 +22698 ' vel' 4 +22699 ' ven' 4 +22700 ' ver' 4 +22701 ' ves' 4 +22702 ' vet' 4 +22703 ' vex' 4 +22704 ' vez' 4 +22705 ' via' 4 +22706 ' vib' 4 +22707 ' vic' 4 +22708 ' vid' 4 +22709 ' vie' 4 +22710 ' vig' 4 +22711 ' vil' 4 +22712 ' vim' 4 +22713 ' vin' 4 +22714 ' vip' 4 +22715 ' vir' 4 +22716 ' vis' 4 +22717 ' vit' 4 +22718 ' viv' 4 +22719 ' viz' 4 +22720 ' voc' 4 +22721 ' vol' 4 +22722 ' vom' 4 +22723 ' von' 4 +22724 ' vor' 4 +22725 ' vos' 4 +22726 ' vot' 4 +22727 ' vou' 4 +22728 ' vow' 4 +22729 ' vox' 4 +22730 ' voy' 4 +22731 ' voz' 4 +22732 ' vra' 4 +22733 ' vue' 4 +22734 ' vul' 4 +22735 ' và' 4 +22736 ' vá' 4 +22737 ' vä' 4 +22738 ' vå' 4 +22739 ' væ' 4 +22740 ' vé' 4 +22741 ' ví' 4 +22742 ' võ' 4 +22743 ' vý' 4 +22744 ' vě' 4 +22745 ' vš' 4 +22746 ' wal' 4 +22747 ' war' 4 +22748 ' was' 4 +22749 ' wat' 4 +22750 ' wav' 4 +22751 ' wax' 4 +22752 ' way' 4 +22753 ' web' 4 +22754 ' wed' 4 +22755 ' wee' 4 +22756 ' weg' 4 +22757 ' wel' 4 +22758 ' wen' 4 +22759 ' wer' 4 +22760 ' wet' 4 +22761 ' whe' 4 +22762 ' who' 4 +22763 ' why' 4 +22764 ' wid' 4 +22765 ' wie' 4 +22766 ' wig' 4 +22767 ' wij' 4 +22768 ' wik' 4 +22769 ' wil' 4 +22770 ' win' 4 +22771 ' wir' 4 +22772 ' wis' 4 +22773 ' wit' 4 +22774 ' wob' 4 +22775 ' wol' 4 +22776 ' wom' 4 +22777 ' won' 4 +22778 ' woo' 4 +22779 ' wor' 4 +22780 ' wow' 4 +22781 ' wra' 4 +22782 ' wre' 4 +22783 ' wsp' 4 +22784 ' wur' 4 +22785 ' www' 4 +22786 ' wä' 4 +22787 ' wł' 4 +22788 ' xen' 4 +22789 ' xml' 4 +22790 ' xxx' 4 +22791 ' xyz' 4 +22792 ' yap' 4 +22793 ' yaw' 4 +22794 ' yen' 4 +22795 ' yer' 4 +22796 ' yes' 4 +22797 ' yet' 4 +22798 ' yog' 4 +22799 ' you' 4 +22800 ' zab' 4 +22801 ' zak' 4 +22802 ' zal' 4 +22803 ' zam' 4 +22804 ' zap' 4 +22805 ' zar' 4 +22806 ' zaw' 4 +22807 ' zen' 4 +22808 ' zer' 4 +22809 ' zig' 4 +22810 ' zij' 4 +22811 ' zip' 4 +22812 ' zon' 4 +22813 ' zoo' 4 +22814 ' zug' 4 +22815 ' zum' 4 +22816 ' zur' 4 +22817 ' zwe' 4 +22818 ' zá' 4 +22819 ' zł' 4 +22820 ' {},' 4 +22821 ' {};' 4 +22822 ' {¶' 4 +22823 ' }).' 4 +22824 ' });' 4 +22825 ' »,' 4 +22826 ' ».' 4 +22827 ' Ál' 4 +22828 ' Éd' 4 +22829 ' És' 4 +22830 ' Ét' 4 +22831 ' În' 4 +22832 ' às' 4 +22833 ' ál' 4 +22834 ' ár' 4 +22835 ' át' 4 +22836 ' äl' 4 +22837 ' än' 4 +22838 ' är' 4 +22839 ' år' 4 +22840 ' ça' 4 +22841 ' éc' 4 +22842 ' éd' 4 +22843 ' ég' 4 +22844 ' él' 4 +22845 ' én' 4 +22846 ' ép' 4 +22847 ' ér' 4 +22848 ' és' 4 +22849 ' ét' 4 +22850 ' év' 4 +22851 ' éx' 4 +22852 ' în' 4 +22853 ' ór' 4 +22854 ' ön' 4 +22855 ' új' 4 +22856 ' ún' 4 +22857 ' će' 4 +22858 ' či' 4 +22859 ' đi' 4 +22860 ' św' 4 +22861 ' şi' 4 +22862 ' że' 4 +22863 ' ży' 4 +22864 ' že' 4 +22865 ' și' 4 +22866 ' μL' 4 +22867 ' μM' 4 +22868 ' μg' 4 +22869 ' μl' 4 +22870 ' μm' 4 +22871 ' μs' 4 +22872 ' अ' 4 +22873 ' आ' 4 +22874 ' क' 4 +22875 ' ज' 4 +22876 ' त' 4 +22877 ' द' 4 +22878 ' न' 4 +22879 ' प' 4 +22880 ' ब' 4 +22881 ' म' 4 +22882 ' र' 4 +22883 ' ल' 4 +22884 ' व' 4 +22885 ' स' 4 +22886 ' ह' 4 +22887 ' ক' 4 +22888 ' ਦ' 4 +22889 ' ਸ' 4 +22890 ' ப' 4 +22891 ' เ' 4 +22892 ' ở' 4 +22893 ' ἀ' 4 +22894 ' ἐ' 4 +22895 ' \u200b' 4 +22896 ' \u200e' 4 +22897 ' –' 4 +22898 ' —' 4 +22899 ' ―' 4 +22900 ' ‖' 4 +22901 ' ‘' 4 +22902 ' ’' 4 +22903 ' “' 4 +22904 ' ”' 4 +22905 ' „' 4 +22906 ' †' 4 +22907 ' •' 4 +22908 ' …' 4 +22909 ' ′' 4 +22910 ' ›' 4 +22911 ' €' 4 +22912 ' ₹' 4 +22913 ' №' 4 +22914 ' ←' 4 +22915 ' ↑' 4 +22916 ' →' 4 +22917 ' ↓' 4 +22918 ' ↔' 4 +22919 ' ⇒' 4 +22920 ' ⇔' 4 +22921 ' ∀' 4 +22922 ' ∂' 4 +22923 ' ∃' 4 +22924 ' ∅' 4 +22925 ' ∆' 4 +22926 ' ∇' 4 +22927 ' ∈' 4 +22928 ' ∑' 4 +22929 ' −' 4 +22930 ' ∗' 4 +22931 ' ∘' 4 +22932 ' √' 4 +22933 ' ∞' 4 +22934 ' ∧' 4 +22935 ' ∨' 4 +22936 ' ∩' 4 +22937 ' ∪' 4 +22938 ' ∫' 4 +22939 ' ∼' 4 +22940 ' ≃' 4 +22941 ' ≈' 4 +22942 ' ≠' 4 +22943 ' ≡' 4 +22944 ' ≤' 4 +22945 ' ≥' 4 +22946 ' ⊂' 4 +22947 ' ⊆' 4 +22948 ' ⊕' 4 +22949 ' ⊗' 4 +22950 ' ⊥' 4 +22951 ' ⋅' 4 +22952 ' ⋯' 4 +22953 ' │' 4 +22954 ' ├' 4 +22955 ' ╚' 4 +22956 ' █' 4 +22957 ' ░' 4 +22958 ' ■' 4 +22959 ' ►' 4 +22960 ' ●' 4 +22961 ' ★' 4 +22962 ' ♥' 4 +22963 ' ♦' 4 +22964 ' ♪' 4 +22965 ' ✓' 4 +22966 ' ✔' 4 +22967 ' ❤' 4 +22968 ' ⟨' 4 +22969 ' ⟩' 4 +22970 ' 。' 4 +22971 ' 〈' 4 +22972 ' 「' 4 +22973 ' 【' 4 +22974 ' 가' 4 +22975 ' 각' 4 +22976 ' 간' 4 +22977 ' 감' 4 +22978 ' 강' 4 +22979 ' 같' 4 +22980 ' 개' 4 +22981 ' 거' 4 +22982 ' 건' 4 +22983 ' 걸' 4 +22984 ' 검' 4 +22985 ' 것' 4 +22986 ' 게' 4 +22987 ' 결' 4 +22988 ' 경' 4 +22989 ' 계' 4 +22990 ' 고' 4 +22991 ' 공' 4 +22992 ' 과' 4 +22993 ' 관' 4 +22994 ' 광' 4 +22995 ' 교' 4 +22996 ' 구' 4 +22997 ' 국' 4 +22998 ' 군' 4 +22999 ' 권' 4 +23000 ' 규' 4 +23001 ' 그' 4 +23002 ' 근' 4 +23003 ' 금' 4 +23004 ' 기' 4 +23005 ' 김' 4 +23006 ' 나' 4 +23007 ' 날' 4 +23008 ' 남' 4 +23009 ' 내' 4 +23010 ' 네' 4 +23011 ' 노' 4 +23012 ' 높' 4 +23013 ' 누' 4 +23014 ' 눈' 4 +23015 ' 다' 4 +23016 ' 단' 4 +23017 ' 달' 4 +23018 ' 당' 4 +23019 ' 대' 4 +23020 ' 더' 4 +23021 ' 덤' 4 +23022 ' 데' 4 +23023 ' 도' 4 +23024 ' 독' 4 +23025 ' 돌' 4 +23026 ' 동' 4 +23027 ' 되' 4 +23028 ' 된' 4 +23029 ' 두' 4 +23030 ' 뒤' 4 +23031 ' 드' 4 +23032 ' 들' 4 +23033 ' 등' 4 +23034 ' 디' 4 +23035 ' 따' 4 +23036 ' 때' 4 +23037 ' 또' 4 +23038 ' 라' 4 +23039 ' 레' 4 +23040 ' 로' 4 +23041 ' 루' 4 +23042 ' 리' 4 +23043 ' 링' 4 +23044 ' 마' 4 +23045 ' 만' 4 +23046 ' 많' 4 +23047 ' 말' 4 +23048 ' 맞' 4 +23049 ' 매' 4 +23050 ' 메' 4 +23051 ' 명' 4 +23052 ' 모' 4 +23053 ' 목' 4 +23054 ' 못' 4 +23055 ' 무' 4 +23056 ' 문' 4 +23057 ' 물' 4 +23058 ' 미' 4 +23059 ' 민' 4 +23060 ' 및' 4 +23061 ' 바' 4 +23062 ' 박' 4 +23063 ' 반' 4 +23064 ' 받' 4 +23065 ' 발' 4 +23066 ' 밝' 4 +23067 ' 방' 4 +23068 ' 배' 4 +23069 ' 백' 4 +23070 ' 버' 4 +23071 ' 번' 4 +23072 ' 법' 4 +23073 ' 베' 4 +23074 ' 변' 4 +23075 ' 병' 4 +23076 ' 보' 4 +23077 ' 복' 4 +23078 ' 본' 4 +23079 ' 부' 4 +23080 ' 북' 4 +23081 ' 분' 4 +23082 ' 불' 4 +23083 ' 브' 4 +23084 ' 비' 4 +23085 ' 사' 4 +23086 ' 산' 4 +23087 ' 살' 4 +23088 ' 삼' 4 +23089 ' 상' 4 +23090 ' 새' 4 +23091 ' 생' 4 +23092 ' 서' 4 +23093 ' 선' 4 +23094 ' 설' 4 +23095 ' 성' 4 +23096 ' 세' 4 +23097 ' 소' 4 +23098 ' 속' 4 +23099 ' 손' 4 +23100 ' 수' 4 +23101 ' 순' 4 +23102 ' 스' 4 +23103 ' 승' 4 +23104 ' 시' 4 +23105 ' 신' 4 +23106 ' 실' 4 +23107 ' 심' 4 +23108 ' 아' 4 +23109 ' 안' 4 +23110 ' 않' 4 +23111 ' 알' 4 +23112 ' 앞' 4 +23113 ' 애' 4 +23114 ' 야' 4 +23115 ' 약' 4 +23116 ' 양' 4 +23117 ' 어' 4 +23118 ' 언' 4 +23119 ' 얼' 4 +23120 ' 업' 4 +23121 ' 없' 4 +23122 ' 에' 4 +23123 ' 여' 4 +23124 ' 역' 4 +23125 ' 연' 4 +23126 ' 열' 4 +23127 ' 영' 4 +23128 ' 예' 4 +23129 ' 오' 4 +23130 ' 온' 4 +23131 ' 올' 4 +23132 ' 완' 4 +23133 ' 왕' 4 +23134 ' 외' 4 +23135 ' 요' 4 +23136 ' 용' 4 +23137 ' 우' 4 +23138 ' 운' 4 +23139 ' 원' 4 +23140 ' 월' 4 +23141 ' 위' 4 +23142 ' 유' 4 +23143 ' 음' 4 +23144 ' 의' 4 +23145 ' 이' 4 +23146 ' 인' 4 +23147 ' 일' 4 +23148 ' 임' 4 +23149 ' 입' 4 +23150 ' 있' 4 +23151 ' 자' 4 +23152 ' 작' 4 +23153 ' 잘' 4 +23154 ' 장' 4 +23155 ' 재' 4 +23156 ' 저' 4 +23157 ' 적' 4 +23158 ' 전' 4 +23159 ' 점' 4 +23160 ' 정' 4 +23161 ' 제' 4 +23162 ' 조' 4 +23163 ' 존' 4 +23164 ' 종' 4 +23165 ' 좋' 4 +23166 ' 주' 4 +23167 ' 죽' 4 +23168 ' 준' 4 +23169 ' 중' 4 +23170 ' 증' 4 +23171 ' 지' 4 +23172 ' 직' 4 +23173 ' 진' 4 +23174 ' 집' 4 +23175 ' 차' 4 +23176 ' 참' 4 +23177 ' 창' 4 +23178 ' 찾' 4 +23179 ' 채' 4 +23180 ' 책' 4 +23181 ' 처' 4 +23182 ' 천' 4 +23183 ' 철' 4 +23184 ' 첫' 4 +23185 ' 청' 4 +23186 ' 체' 4 +23187 ' 초' 4 +23188 ' 총' 4 +23189 ' 최' 4 +23190 ' 추' 4 +23191 ' 축' 4 +23192 ' 출' 4 +23193 ' 충' 4 +23194 ' 취' 4 +23195 ' 치' 4 +23196 ' 친' 4 +23197 ' 카' 4 +23198 ' 코' 4 +23199 ' 크' 4 +23200 ' 클' 4 +23201 ' 타' 4 +23202 ' 태' 4 +23203 ' 테' 4 +23204 ' 토' 4 +23205 ' 통' 4 +23206 ' 투' 4 +23207 ' 트' 4 +23208 ' 특' 4 +23209 ' 팀' 4 +23210 ' 파' 4 +23211 ' 판' 4 +23212 ' 패' 4 +23213 ' 페' 4 +23214 ' 편' 4 +23215 ' 평' 4 +23216 ' 포' 4 +23217 ' 표' 4 +23218 ' 프' 4 +23219 ' 플' 4 +23220 ' 피' 4 +23221 ' 필' 4 +23222 ' 하' 4 +23223 ' 학' 4 +23224 ' 한' 4 +23225 ' 할' 4 +23226 ' 함' 4 +23227 ' 합' 4 +23228 ' 항' 4 +23229 ' 해' 4 +23230 ' 했' 4 +23231 ' 행' 4 +23232 ' 현' 4 +23233 ' 형' 4 +23234 ' 호' 4 +23235 ' 화' 4 +23236 ' 확' 4 +23237 ' 환' 4 +23238 ' 활' 4 +23239 ' 황' 4 +23240 ' 회' 4 +23241 ' 후' 4 +23242 ' 히' 4 +23243 ' \ufeff' 4 +23244 ' (' 4 +23245 ' ,' 4 +23246 ' :' 4 +23247 ' �' 4 +23248 '!!!!' 4 +23249 '!");' 4 +23250 '!’' 4 +23251 '!”' 4 +23252 '""""' 4 +23253 '")))' 4 +23254 '")),' 4 +23255 '"));' 4 +23256 '"...' 4 +23257 '"/><' 4 +23258 '":["' 4 +23259 '":{"' 4 +23260 '">' 4 +23264 '"]["' 4 +23265 '"—' 4 +23266 '####' 4 +23267 '$$$$' 4 +23268 '$’' 4 +23269 '%%%%' 4 +23270 "')))" 4 +23271 "'))," 4 +23272 "'))." 4 +23273 "'));" 4 +23274 "')->" 4 +23275 "']))" 4 +23276 "'])," 4 +23277 "'])." 4 +23278 "']):" 4 +23279 "']);" 4 +23280 "']==" 4 +23281 "']['" 4 +23282 "']]," 4 +23283 '("--' 4 +23284 '("./' 4 +23285 "(''," 4 +23286 "('--" 4 +23287 "('./" 4 +23288 '()))' 4 +23289 '()),' 4 +23290 '()).' 4 +23291 '()):' 4 +23292 '());' 4 +23293 '()->' 4 +23294 '()' 4 +23340 '="${' 4 +23341 '="@+' 4 +23342 "='')" 4 +23343 '=-=-' 4 +23344 '====' 4 +23345 '=”' 4 +23346 '>();' 4 +23347 '>>>>' 4 +23348 '?,?,' 4 +23349 '????' 4 +23350 '?’' 4 +23351 '?”' 4 +23352 '@@@@' 4 +23353 'AAAA' 4 +23354 'ABEL' 4 +23355 'ABLE' 4 +23356 'ACES' 4 +23357 'ACHE' 4 +23358 'ADDR' 4 +23359 'ADER' 4 +23360 'AGES' 4 +23361 'AIDS' 4 +23362 'ALLY' 4 +23363 'ALOG' 4 +23364 'ALSE' 4 +23365 'ALTH' 4 +23366 'AMES' 4 +23367 'ANCE' 4 +23368 'ANGE' 4 +23369 'ANGO' 4 +23370 'ANTS' 4 +23371 'ARCH' 4 +23372 'ARGS' 4 +23373 'ATAL' 4 +23374 'ATCH' 4 +23375 'ATED' 4 +23376 'ATEG' 4 +23377 'ATER' 4 +23378 'ATES' 4 +23379 'ATIC' 4 +23380 'ATOM' 4 +23381 'ATOR' 4 +23382 'ATTR' 4 +23383 'AUTH' 4 +23384 'AUTO' 4 +23385 'Adam' 4 +23386 'Addr' 4 +23387 'Alan' 4 +23388 'Alex' 4 +23389 'Also' 4 +23390 'Anal' 4 +23391 'Andy' 4 +23392 'Anim' 4 +23393 'Anna' 4 +23394 'Anne' 4 +23395 'Anth' 4 +23396 'Anti' 4 +23397 'Appe' 4 +23398 'Apps' 4 +23399 'Arab' 4 +23400 'Arch' 4 +23401 'Area' 4 +23402 'Args' 4 +23403 'Asia' 4 +23404 'Atom' 4 +23405 'Attr' 4 +23406 'Auth' 4 +23407 'Auto' 4 +23408 'Axes' 4 +23409 'Axis' 4 +23410 'BACK' 4 +23411 'BASE' 4 +23412 'BERT' 4 +23413 'BITS' 4 +23414 'BLUE' 4 +23415 'BOOK' 4 +23416 'BOOL' 4 +23417 'BUFF' 4 +23418 'BYTE' 4 +23419 'Baby' 4 +23420 'Back' 4 +23421 'Ball' 4 +23422 'Band' 4 +23423 'Bang' 4 +23424 'Bank' 4 +23425 'Base' 4 +23426 'Beam' 4 +23427 'Bean' 4 +23428 'Beat' 4 +23429 'Bell' 4 +23430 'Bern' 4 +23431 'Bert' 4 +23432 'Best' 4 +23433 'Beta' 4 +23434 'Bias' 4 +23435 'Bill' 4 +23436 'Bind' 4 +23437 'Bits' 4 +23438 'Blob' 4 +23439 'Blog' 4 +23440 'Blue' 4 +23441 'Blur' 4 +23442 'Body' 4 +23443 'Bold' 4 +23444 'Book' 4 +23445 'Bool' 4 +23446 'Boot' 4 +23447 'Born' 4 +23448 'Boss' 4 +23449 'Both' 4 +23450 'Brad' 4 +23451 'Brit' 4 +23452 'Bron' 4 +23453 'Buff' 4 +23454 'Burn' 4 +23455 'ById' 4 +23456 'Byte' 4 +23457 'CADE' 4 +23458 'CALL' 4 +23459 'CASE' 4 +23460 'CAST' 4 +23461 'CCCC' 4 +23462 'CENT' 4 +23463 'CEPT' 4 +23464 'CHAR' 4 +23465 'CLUD' 4 +23466 'CLUS' 4 +23467 'CODE' 4 +23468 'COMM' 4 +23469 'COMP' 4 +23470 'COND' 4 +23471 'CONF' 4 +23472 'CONN' 4 +23473 'CONT' 4 +23474 'COPY' 4 +23475 'CORE' 4 +23476 'COUN' 4 +23477 'CTOR' 4 +23478 'CTRL' 4 +23479 'CUDA' 4 +23480 'Calc' 4 +23481 'Call' 4 +23482 'Camb' 4 +23483 'Camp' 4 +23484 'Cand' 4 +23485 'Capt' 4 +23486 'Card' 4 +23487 'Care' 4 +23488 'Carl' 4 +23489 'Cart' 4 +23490 'Case' 4 +23491 'Cash' 4 +23492 'Cast' 4 +23493 'Cath' 4 +23494 'Cell' 4 +23495 'Cent' 4 +23496 'Cert' 4 +23497 'Chan' 4 +23498 'Chap' 4 +23499 'Char' 4 +23500 'Chat' 4 +23501 'Chem' 4 +23502 'Chen' 4 +23503 'Chip' 4 +23504 'Circ' 4 +23505 'City' 4 +23506 'Clar' 4 +23507 'Clip' 4 +23508 'Club' 4 +23509 'Code' 4 +23510 'Coin' 4 +23511 'Cold' 4 +23512 'Cole' 4 +23513 'Coll' 4 +23514 'Cols' 4 +23515 'Comb' 4 +23516 'Come' 4 +23517 'Comm' 4 +23518 'Comp' 4 +23519 'Cond' 4 +23520 'Conf' 4 +23521 'Cong' 4 +23522 'Conn' 4 +23523 'Cons' 4 +23524 'Cont' 4 +23525 'Conv' 4 +23526 'Cook' 4 +23527 'Cool' 4 +23528 'Copy' 4 +23529 'Core' 4 +23530 'Corn' 4 +23531 'Corp' 4 +23532 'Cost' 4 +23533 'Cour' 4 +23534 'Cred' 4 +23535 'Crit' 4 +23536 'Crop' 4 +23537 'Ctrl' 4 +23538 'Cube' 4 +23539 'Curr' 4 +23540 'DATA' 4 +23541 'DATE' 4 +23542 'DECL' 4 +23543 'DESC' 4 +23544 'DIFF' 4 +23545 'DIST' 4 +23546 'DONE' 4 +23547 'DOWN' 4 +23548 'DRAW' 4 +23549 'DROP' 4 +23550 'Damn' 4 +23551 'Dark' 4 +23552 'Dash' 4 +23553 'Data' 4 +23554 'Date' 4 +23555 'Dave' 4 +23556 'Days' 4 +23557 'Dead' 4 +23558 'Dear' 4 +23559 'Decl' 4 +23560 'Deep' 4 +23561 'Dele' 4 +23562 'Demo' 4 +23563 'Desc' 4 +23564 'Dest' 4 +23565 'Diam' 4 +23566 'Dick' 4 +23567 'Dict' 4 +23568 'Diff' 4 +23569 'Dire' 4 +23570 'Disc' 4 +23571 'Disk' 4 +23572 'Disp' 4 +23573 'Dist' 4 +23574 'Dock' 4 +23575 'Docs' 4 +23576 'Does' 4 +23577 'Done' 4 +23578 'Door' 4 +23579 'Doug' 4 +23580 'Down' 4 +23581 'Drag' 4 +23582 'Draw' 4 +23583 'Drop' 4 +23584 'Drug' 4 +23585 'Dump' 4 +23586 'EDIT' 4 +23587 'EEEE' 4 +23588 'EGIN' 4 +23589 'EMPL' 4 +23590 'ENCE' 4 +23591 'ENCY' 4 +23592 'ENER' 4 +23593 'ENSE' 4 +23594 'ENTS' 4 +23595 'ERIC' 4 +23596 'ESCO' 4 +23597 'EXEC' 4 +23598 'EXIT' 4 +23599 'Each' 4 +23600 'East' 4 +23601 'Easy' 4 +23602 'Echo' 4 +23603 'Edge' 4 +23604 'Edit' 4 +23605 'Educ' 4 +23606 'Elem' 4 +23607 'Else' 4 +23608 'Emer' 4 +23609 'Emit' 4 +23610 'Enum' 4 +23611 'Eric' 4 +23612 'Euro' 4 +23613 'Eval' 4 +23614 'Even' 4 +23615 'Ever' 4 +23616 'Exec' 4 +23617 'Exit' 4 +23618 'Expl' 4 +23619 'Expr' 4 +23620 'FACE' 4 +23621 'FAIL' 4 +23622 'FAST' 4 +23623 'FFER' 4 +23624 'FFFF' 4 +23625 'FILE' 4 +23626 'FLAG' 4 +23627 'FLOW' 4 +23628 'FONT' 4 +23629 'FORE' 4 +23630 'FORM' 4 +23631 'FREE' 4 +23632 'FROM' 4 +23633 'FULL' 4 +23634 'FUNC' 4 +23635 'Face' 4 +23636 'Fact' 4 +23637 'Fail' 4 +23638 'Fair' 4 +23639 'Fake' 4 +23640 'Fall' 4 +23641 'Farm' 4 +23642 'Fast' 4 +23643 'Feed' 4 +23644 'Feel' 4 +23645 'File' 4 +23646 'Fill' 4 +23647 'Film' 4 +23648 'Find' 4 +23649 'Fine' 4 +23650 'Fire' 4 +23651 'Fish' 4 +23652 'Five' 4 +23653 'Flag' 4 +23654 'Flat' 4 +23655 'Flex' 4 +23656 'Flip' 4 +23657 'Flor' 4 +23658 'Flow' 4 +23659 'Fold' 4 +23660 'Font' 4 +23661 'Food' 4 +23662 'Foot' 4 +23663 'Ford' 4 +23664 'Fore' 4 +23665 'Form' 4 +23666 'Fort' 4 +23667 'Four' 4 +23668 'Frag' 4 +23669 'Fran' 4 +23670 'Fred' 4 +23671 'Free' 4 +23672 'From' 4 +23673 'Fuck' 4 +23674 'Full' 4 +23675 'Func' 4 +23676 'Fund' 4 +23677 'Für' 4 +23678 'GPIO' 4 +23679 'GRAM' 4 +23680 'GUID' 4 +23681 'Gain' 4 +23682 'Game' 4 +23683 'Gary' 4 +23684 'Gate' 4 +23685 'Gene' 4 +23686 'Geom' 4 +23687 'Germ' 4 +23688 'Gest' 4 +23689 'Girl' 4 +23690 'Give' 4 +23691 'Glob' 4 +23692 'Goal' 4 +23693 'Gold' 4 +23694 'Good' 4 +23695 'Grab' 4 +23696 'Grad' 4 +23697 'Gram' 4 +23698 'Gran' 4 +23699 'Gray' 4 +23700 'Greg' 4 +23701 'Grid' 4 +23702 'Grow' 4 +23703 'Guid' 4 +23704 'HAND' 4 +23705 'HASH' 4 +23706 'HEAD' 4 +23707 'HERE' 4 +23708 'HIGH' 4 +23709 'HOME' 4 +23710 'HOST' 4 +23711 'HOUT' 4 +23712 'HTML' 4 +23713 'HTTP' 4 +23714 'Half' 4 +23715 'Hall' 4 +23716 'Hand' 4 +23717 'Hang' 4 +23718 'Hard' 4 +23719 'Hart' 4 +23720 'Hash' 4 +23721 'Have' 4 +23722 'Head' 4 +23723 'Heap' 4 +23724 'Heat' 4 +23725 'Hell' 4 +23726 'Help' 4 +23727 'Here' 4 +23728 'Hero' 4 +23729 'Hide' 4 +23730 'High' 4 +23731 'Hill' 4 +23732 'Hint' 4 +23733 'Hist' 4 +23734 'Hold' 4 +23735 'Holy' 4 +23736 'Home' 4 +23737 'Hong' 4 +23738 'Hook' 4 +23739 'Hope' 4 +23740 'Host' 4 +23741 'Hour' 4 +23742 'Html' 4 +23743 'Http' 4 +23744 'Hung' 4 +23745 'IBLE' 4 +23746 'IBUT' 4 +23747 'ICAL' 4 +23748 'ICAg' 4 +23749 'ICES' 4 +23750 'ICLE' 4 +23751 'ICON' 4 +23752 'IDER' 4 +23753 'IDTH' 4 +23754 'IEEE' 4 +23755 'IENT' 4 +23756 'IFIC' 4 +23757 'IGHT' 4 +23758 'ILED' 4 +23759 'ILLE' 4 +23760 'IMAL' 4 +23761 'IMIT' 4 +23762 'INCT' 4 +23763 'INES' 4 +23764 'INFO' 4 +23765 'INGS' 4 +23766 'INIT' 4 +23767 'INST' 4 +23768 'IONS' 4 +23769 'IOUS' 4 +23770 'IRED' 4 +23771 'IRST' 4 +23772 'ISBN' 4 +23773 'ISON' 4 +23774 'ISTR' 4 +23775 'ISTS' 4 +23776 'ITAL' 4 +23777 'ITCH' 4 +23778 'ITED' 4 +23779 'ITEM' 4 +23780 'ITER' 4 +23781 'ITES' 4 +23782 'ITLE' 4 +23783 'ITOR' 4 +23784 'IVER' 4 +23785 'IZED' 4 +23786 'IZER' 4 +23787 'Icon' 4 +23788 'Idle' 4 +23789 'Impl' 4 +23790 'Infl' 4 +23791 'Info' 4 +23792 'Init' 4 +23793 'Insp' 4 +23794 'Inst' 4 +23795 'Into' 4 +23796 'Iran' 4 +23797 'Iron' 4 +23798 'Ital' 4 +23799 'Item' 4 +23800 'Iter' 4 +23801 'IÓN' 4 +23802 'JECT' 4 +23803 'JOIN' 4 +23804 'JSON' 4 +23805 'JUST' 4 +23806 'Jack' 4 +23807 'Jane' 4 +23808 'Java' 4 +23809 'Jean' 4 +23810 'Jeff' 4 +23811 'Jess' 4 +23812 'Jobs' 4 +23813 'John' 4 +23814 'Join' 4 +23815 'Jose' 4 +23816 'Josh' 4 +23817 'Json' 4 +23818 'July' 4 +23819 'Jump' 4 +23820 'June' 4 +23821 'Just' 4 +23822 'KEEP' 4 +23823 'Kate' 4 +23824 'Keep' 4 +23825 'Kenn' 4 +23826 'Keys' 4 +23827 'Kill' 4 +23828 'Kind' 4 +23829 'King' 4 +23830 'Know' 4 +23831 'LAND' 4 +23832 'LANG' 4 +23833 'LAST' 4 +23834 'LDAP' 4 +23835 'LEAN' 4 +23836 'LEAR' 4 +23837 'LECT' 4 +23838 'LEFT' 4 +23839 'LETE' 4 +23840 'LINE' 4 +23841 'LINK' 4 +23842 'LIST' 4 +23843 'LOAD' 4 +23844 'LOAT' 4 +23845 'LOCK' 4 +23846 'LONG' 4 +23847 'LOOP' 4 +23848 'LSTM' 4 +23849 'Lady' 4 +23850 'Lake' 4 +23851 'Land' 4 +23852 'Lang' 4 +23853 'Last' 4 +23854 'Late' 4 +23855 'Lazy' 4 +23856 'Lead' 4 +23857 'Leaf' 4 +23858 'Lean' 4 +23859 'Lear' 4 +23860 'Left' 4 +23861 'Leon' 4 +23862 'Less' 4 +23863 'Life' 4 +23864 'Like' 4 +23865 'Line' 4 +23866 'Link' 4 +23867 'List' 4 +23868 'Lite' 4 +23869 'Live' 4 +23870 'Load' 4 +23871 'Lock' 4 +23872 'Logo' 4 +23873 'Long' 4 +23874 'Look' 4 +23875 'Loop' 4 +23876 'Lord' 4 +23877 'Loss' 4 +23878 'Lost' 4 +23879 'Love' 4 +23880 'Luke' 4 +23881 'MAIL' 4 +23882 'MAIN' 4 +23883 'MAKE' 4 +23884 'MARK' 4 +23885 'MASK' 4 +23886 'MBOL' 4 +23887 'MENT' 4 +23888 'MENU' 4 +23889 'MESS' 4 +23890 'META' 4 +23891 'MISS' 4 +23892 'MMMM' 4 +23893 'MODE' 4 +23894 'MORE' 4 +23895 'MULT' 4 +23896 'Mach' 4 +23897 'Made' 4 +23898 'Magn' 4 +23899 'Mail' 4 +23900 'Main' 4 +23901 'Make' 4 +23902 'Male' 4 +23903 'Many' 4 +23904 'Maps' 4 +23905 'Marc' 4 +23906 'Marg' 4 +23907 'Mark' 4 +23908 'Mart' 4 +23909 'Mary' 4 +23910 'Mask' 4 +23911 'Mass' 4 +23912 'Math' 4 +23913 'Matt' 4 +23914 'Mean' 4 +23915 'Meet' 4 +23916 'Memo' 4 +23917 'Menu' 4 +23918 'Merc' 4 +23919 'Mesh' 4 +23920 'Mess' 4 +23921 'Meta' 4 +23922 'Mich' 4 +23923 'Mike' 4 +23924 'Mill' 4 +23925 'Mind' 4 +23926 'Mini' 4 +23927 'Misc' 4 +23928 'Miss' 4 +23929 'Mock' 4 +23930 'Mode' 4 +23931 'Mont' 4 +23932 'Moon' 4 +23933 'More' 4 +23934 'Most' 4 +23935 'Move' 4 +23936 'Much' 4 +23937 'Mult' 4 +23938 'Must' 4 +23939 'NAME' 4 +23940 'NASA' 4 +23941 'NECT' 4 +23942 'NESS' 4 +23943 'NEWS' 4 +23944 'NEXT' 4 +23945 'NING' 4 +23946 'NODE' 4 +23947 'NONE' 4 +23948 'NOTE' 4 +23949 'NULL' 4 +23950 'Name' 4 +23951 'Near' 4 +23952 'Need' 4 +23953 'Neil' 4 +23954 'News' 4 +23955 'Next' 4 +23956 'Nice' 4 +23957 'Nick' 4 +23958 'Node' 4 +23959 'Nome' 4 +23960 'None' 4 +23961 'Norm' 4 +23962 'Note' 4 +23963 'Nova' 4 +23964 'Null' 4 +23965 'Não' 4 +23966 'ONES' 4 +23967 'ONLY' 4 +23968 'OPEN' 4 +23969 'OPER' 4 +23970 'ORIZ' 4 +23971 'OTAL' 4 +23972 'OUND' 4 +23973 'OVER' 4 +23974 'OWER' 4 +23975 'Ohio' 4 +23976 'Okay' 4 +23977 'Once' 4 +23978 'Only' 4 +23979 'Oops' 4 +23980 'Open' 4 +23981 'Oper' 4 +23982 'Opts' 4 +23983 'Orig' 4 +23984 'Over' 4 +23985 'PACK' 4 +23986 'PAGE' 4 +23987 'PART' 4 +23988 'PASS' 4 +23989 'PATH' 4 +23990 'PECT' 4 +23991 'PING' 4 +23992 'PLAY' 4 +23993 'PORT' 4 +23994 'POSE' 4 +23995 'POST' 4 +23996 'PRES' 4 +23997 'PROC' 4 +23998 'PROP' 4 +23999 'PUBL' 4 +24000 'Pack' 4 +24001 'Page' 4 +24002 'Pain' 4 +24003 'Pair' 4 +24004 'Pane' 4 +24005 'Para' 4 +24006 'Park' 4 +24007 'Part' 4 +24008 'Pass' 4 +24009 'Past' 4 +24010 'Path' 4 +24011 'Paul' 4 +24012 'Pear' 4 +24013 'Peer' 4 +24014 'Perm' 4 +24015 'Pers' 4 +24016 'Phil' 4 +24017 'Phot' 4 +24018 'Phys' 4 +24019 'Pick' 4 +24020 'Pier' 4 +24021 'Ping' 4 +24022 'Pipe' 4 +24023 'Plan' 4 +24024 'Play' 4 +24025 'Plot' 4 +24026 'Plug' 4 +24027 'Plus' 4 +24028 'Poll' 4 +24029 'Poly' 4 +24030 'Pont' 4 +24031 'Pool' 4 +24032 'Poor' 4 +24033 'Port' 4 +24034 'Pose' 4 +24035 'Poss' 4 +24036 'Post' 4 +24037 'Pour' 4 +24038 'Prec' 4 +24039 'Pred' 4 +24040 'Pref' 4 +24041 'Prem' 4 +24042 'Prep' 4 +24043 'Pres' 4 +24044 'Prev' 4 +24045 'Prim' 4 +24046 'Priv' 4 +24047 'Prob' 4 +24048 'Proc' 4 +24049 'Prod' 4 +24050 'Prof' 4 +24051 'Prog' 4 +24052 'Proj' 4 +24053 'Prom' 4 +24054 'Prop' 4 +24055 'Pros' 4 +24056 'Prot' 4 +24057 'Prov' 4 +24058 'Pull' 4 +24059 'Pure' 4 +24060 'Push' 4 +24061 'QUAL' 4 +24062 'Quad' 4 +24063 'Qual' 4 +24064 'Quit' 4 +24065 'Qué' 4 +24066 'RATE' 4 +24067 'READ' 4 +24068 'REAL' 4 +24069 'REAM' 4 +24070 'RECT' 4 +24071 'RENT' 4 +24072 'REPL' 4 +24073 'REQU' 4 +24074 'RESH' 4 +24075 'RESS' 4 +24076 'REST' 4 +24077 'RGBA' 4 +24078 'RIPT' 4 +24079 'RNAs' 4 +24080 'ROLE' 4 +24081 'ROLL' 4 +24082 'ROOT' 4 +24083 'ROUP' 4 +24084 'ROUT' 4 +24085 'Race' 4 +24086 'Radi' 4 +24087 'Rail' 4 +24088 'Rain' 4 +24089 'Rand' 4 +24090 'Rank' 4 +24091 'Rate' 4 +24092 'ReLU' 4 +24093 'Read' 4 +24094 'Real' 4 +24095 'Rece' 4 +24096 'Rect' 4 +24097 'Repo' 4 +24098 'Resp' 4 +24099 'Rest' 4 +24100 'Rich' 4 +24101 'Rick' 4 +24102 'Ring' 4 +24103 'Risk' 4 +24104 'Road' 4 +24105 'Rock' 4 +24106 'Role' 4 +24107 'Roll' 4 +24108 'Room' 4 +24109 'Root' 4 +24110 'Rose' 4 +24111 'Ross' 4 +24112 'Rout' 4 +24113 'Rows' 4 +24114 'Ruby' 4 +24115 'Rule' 4 +24116 'Russ' 4 +24117 'Ryan' 4 +24118 'SAME' 4 +24119 'SCAN' 4 +24120 'SELF' 4 +24121 'SENT' 4 +24122 'SEQU' 4 +24123 'SHOT' 4 +24124 'SIGN' 4 +24125 'SION' 4 +24126 'SIZE' 4 +24127 'SKIP' 4 +24128 'SMTP' 4 +24129 'SPEC' 4 +24130 'STAR' 4 +24131 'STAT' 4 +24132 'STEM' 4 +24133 'STEP' 4 +24134 'STER' 4 +24135 'STIT' 4 +24136 'STOP' 4 +24137 'STRU' 4 +24138 'Safe' 4 +24139 'Sale' 4 +24140 'Salt' 4 +24141 'Same' 4 +24142 'Sand' 4 +24143 'Sans' 4 +24144 'Save' 4 +24145 'Scal' 4 +24146 'Scan' 4 +24147 'Sche' 4 +24148 'Seed' 4 +24149 'Seek' 4 +24150 'Self' 4 +24151 'Sell' 4 +24152 'Send' 4 +24153 'Sent' 4 +24154 'Sept' 4 +24155 'Sequ' 4 +24156 'Serv' 4 +24157 'Sets' 4 +24158 'Shar' 4 +24159 'Sher' 4 +24160 'Ship' 4 +24161 'Shop' 4 +24162 'Shot' 4 +24163 'Show' 4 +24164 'Side' 4 +24165 'Sign' 4 +24166 'Sing' 4 +24167 'Sink' 4 +24168 'Site' 4 +24169 'Size' 4 +24170 'Skin' 4 +24171 'Skip' 4 +24172 'Slot' 4 +24173 'Slow' 4 +24174 'Snap' 4 +24175 'Snow' 4 +24176 'Soft' 4 +24177 'Sold' 4 +24178 'Some' 4 +24179 'Song' 4 +24180 'Sony' 4 +24181 'Soon' 4 +24182 'Sort' 4 +24183 'Soup' 4 +24184 'Span' 4 +24185 'Spec' 4 +24186 'Spin' 4 +24187 'Spot' 4 +24188 'Stan' 4 +24189 'Star' 4 +24190 'Stat' 4 +24191 'Stay' 4 +24192 'Step' 4 +24193 'Stmt' 4 +24194 'Stop' 4 +24195 'Stra' 4 +24196 'Stre' 4 +24197 'Stub' 4 +24198 'Stud' 4 +24199 'Such' 4 +24200 'Suit' 4 +24201 'Supp' 4 +24202 'Sure' 4 +24203 'Swap' 4 +24204 'Sync' 4 +24205 'TAIN' 4 +24206 'TASK' 4 +24207 'TEMP' 4 +24208 'TERN' 4 +24209 'TEST' 4 +24210 'TEXT' 4 +24211 'THER' 4 +24212 'THIS' 4 +24213 'THON' 4 +24214 'TIME' 4 +24215 'TING' 4 +24216 'TION' 4 +24217 'TODO' 4 +24218 'TOOL' 4 +24219 'TRAN' 4 +24220 'TRUE' 4 +24221 'TYPE' 4 +24222 'Tabs' 4 +24223 'Tags' 4 +24224 'Tail' 4 +24225 'Take' 4 +24226 'Talk' 4 +24227 'Tang' 4 +24228 'Task' 4 +24229 'Team' 4 +24230 'Tech' 4 +24231 'Tele' 4 +24232 'Tell' 4 +24233 'Temp' 4 +24234 'Term' 4 +24235 'Test' 4 +24236 'Text' 4 +24237 'Than' 4 +24238 'That' 4 +24239 'Then' 4 +24240 'Ther' 4 +24241 'They' 4 +24242 'This' 4 +24243 'Thus' 4 +24244 'Tick' 4 +24245 'Tile' 4 +24246 'Time' 4 +24247 'Tipo' 4 +24248 'Tips' 4 +24249 'Todo' 4 +24250 'Tony' 4 +24251 'Tool' 4 +24252 'Tour' 4 +24253 'Town' 4 +24254 'Trad' 4 +24255 'Tree' 4 +24256 'Trim' 4 +24257 'Trip' 4 +24258 'True' 4 +24259 'Tube' 4 +24260 'Turn' 4 +24261 'Type' 4 +24262 'Tên' 4 +24263 'UBLE' 4 +24264 'UILD' 4 +24265 'UINT' 4 +24266 'UInt' 4 +24267 'ULAR' 4 +24268 'UNIT' 4 +24269 'URAL' 4 +24270 'URES' 4 +24271 'USED' 4 +24272 'USER' 4 +24273 'UUID' 4 +24274 'Uint' 4 +24275 'Undo' 4 +24276 'Unit' 4 +24277 'Unix' 4 +24278 'Upon' 4 +24279 'Urls' 4 +24280 'Used' 4 +24281 'User' 4 +24282 'Util' 4 +24283 'VARI' 4 +24284 'VENT' 4 +24285 'VERS' 4 +24286 'VERT' 4 +24287 'VICE' 4 +24288 'VIEW' 4 +24289 'Vari' 4 +24290 'Vars' 4 +24291 'Verb' 4 +24292 'Vers' 4 +24293 'Vert' 4 +24294 'Very' 4 +24295 'Vict' 4 +24296 'Viet' 4 +24297 'View' 4 +24298 'Vill' 4 +24299 'Viol' 4 +24300 'Void' 4 +24301 'Vote' 4 +24302 'Vous' 4 +24303 'WAIT' 4 +24304 'WARD' 4 +24305 'WARE' 4 +24306 'WARN' 4 +24307 'WAYS' 4 +24308 'WEEN' 4 +24309 'WHAT' 4 +24310 'WISE' 4 +24311 'WITH' 4 +24312 'WORD' 4 +24313 'WORK' 4 +24314 'Wait' 4 +24315 'Walk' 4 +24316 'Wall' 4 +24317 'Wang' 4 +24318 'Want' 4 +24319 'Warn' 4 +24320 'Wave' 4 +24321 'Weak' 4 +24322 'Week' 4 +24323 'Well' 4 +24324 'Were' 4 +24325 'West' 4 +24326 'What' 4 +24327 'When' 4 +24328 'Whit' 4 +24329 'Wide' 4 +24330 'Wiki' 4 +24331 'Wild' 4 +24332 'Will' 4 +24333 'Wind' 4 +24334 'Wire' 4 +24335 'With' 4 +24336 'Wolf' 4 +24337 'Wood' 4 +24338 'Word' 4 +24339 'Work' 4 +24340 'Wrap' 4 +24341 'Writ' 4 +24342 'XXXX' 4 +24343 'YEAR' 4 +24344 'YYYY' 4 +24345 'Yang' 4 +24346 'Yeah' 4 +24347 'Year' 4 +24348 'York' 4 +24349 'Your' 4 +24350 'ZERO' 4 +24351 'ZONE' 4 +24352 'Zero' 4 +24353 'Zone' 4 +24354 'Zoom' 4 +24355 '\\\\\\\\' 4 +24356 '])))' 4 +24357 '])),' 4 +24358 ']));' 4 +24359 '^^^^' 4 +24360 '^−' 4 +24361 '__("' 4 +24362 '__()' 4 +24363 '____' 4 +24364 'aaaa' 4 +24365 'abad' 4 +24366 'abal' 4 +24367 'aban' 4 +24368 'abar' 4 +24369 'abbr' 4 +24370 'abcd' 4 +24371 'abei' 4 +24372 'abel' 4 +24373 'aben' 4 +24374 'aber' 4 +24375 'abet' 4 +24376 'abil' 4 +24377 'abin' 4 +24378 'abis' 4 +24379 'abit' 4 +24380 'abla' 4 +24381 'able' 4 +24382 'ablo' 4 +24383 'ably' 4 +24384 'abol' 4 +24385 'abor' 4 +24386 'abul' 4 +24387 'abus' 4 +24388 'abwe' 4 +24389 'acao' 4 +24390 'acas' 4 +24391 'acci' 4 +24392 'acco' 4 +24393 'acea' 4 +24394 'aced' 4 +24395 'acer' 4 +24396 'aces' 4 +24397 'acet' 4 +24398 'acey' 4 +24399 'acha' 4 +24400 'ache' 4 +24401 'achi' 4 +24402 'acho' 4 +24403 'acht' 4 +24404 'achu' 4 +24405 'achy' 4 +24406 'acia' 4 +24407 'acic' 4 +24408 'acid' 4 +24409 'acin' 4 +24410 'acio' 4 +24411 'acks' 4 +24412 'acle' 4 +24413 'acon' 4 +24414 'acos' 4 +24415 'acre' 4 +24416 'acro' 4 +24417 'acts' 4 +24418 'acus' 4 +24419 'ací' 4 +24420 'adal' 4 +24421 'adam' 4 +24422 'adan' 4 +24423 'adas' 4 +24424 'aday' 4 +24425 'addr' 4 +24426 'addy' 4 +24427 'aded' 4 +24428 'adel' 4 +24429 'adem' 4 +24430 'aden' 4 +24431 'ader' 4 +24432 'ades' 4 +24433 'adia' 4 +24434 'adic' 4 +24435 'adin' 4 +24436 'adir' 4 +24437 'adoc' 4 +24438 'ador' 4 +24439 'ados' 4 +24440 'adow' 4 +24441 'adó' 4 +24442 'aeda' 4 +24443 'afen' 4 +24444 'affe' 4 +24445 'afia' 4 +24446 'afka' 4 +24447 'afé' 4 +24448 'agan' 4 +24449 'agar' 4 +24450 'agas' 4 +24451 'aged' 4 +24452 'agem' 4 +24453 'agen' 4 +24454 'ager' 4 +24455 'ages' 4 +24456 'agic' 4 +24457 'agin' 4 +24458 'agit' 4 +24459 'agle' 4 +24460 'agli' 4 +24461 'agma' 4 +24462 'agna' 4 +24463 'agne' 4 +24464 'agog' 4 +24465 'agon' 4 +24466 'agos' 4 +24467 'agra' 4 +24468 'agua' 4 +24469 'ague' 4 +24470 'agus' 4 +24471 'ahan' 4 +24472 'ahoo' 4 +24473 'aign' 4 +24474 'ails' 4 +24475 'aily' 4 +24476 'aina' 4 +24477 'aine' 4 +24478 'ains' 4 +24479 'aint' 4 +24480 'aird' 4 +24481 'aire' 4 +24482 'airo' 4 +24483 'airs' 4 +24484 'airy' 4 +24485 'aise' 4 +24486 'aisy' 4 +24487 'ajan' 4 +24488 'ajas' 4 +24489 'ajax' 4 +24490 'ajes' 4 +24491 'ajor' 4 +24492 'ają' 4 +24493 'akan' 4 +24494 'aked' 4 +24495 'aken' 4 +24496 'aker' 4 +24497 'akes' 4 +24498 'akia' 4 +24499 'akin' 4 +24500 'akis' 4 +24501 'akov' 4 +24502 'alam' 4 +24503 'alan' 4 +24504 'alar' 4 +24505 'aldi' 4 +24506 'aldo' 4 +24507 'aleb' 4 +24508 'aled' 4 +24509 'alem' 4 +24510 'alen' 4 +24511 'aler' 4 +24512 'ales' 4 +24513 'alex' 4 +24514 'aley' 4 +24515 'alez' 4 +24516 'algo' 4 +24517 'alia' 4 +24518 'alin' 4 +24519 'alis' 4 +24520 'alla' 4 +24521 'alle' 4 +24522 'alli' 4 +24523 'allo' 4 +24524 'alls' 4 +24525 'ally' 4 +24526 'alog' 4 +24527 'alom' 4 +24528 'alon' 4 +24529 'alph' 4 +24530 'alsa' 4 +24531 'alse' 4 +24532 'also' 4 +24533 'alta' 4 +24534 'alth' 4 +24535 'alty' 4 +24536 'alus' 4 +24537 'amac' 4 +24538 'aman' 4 +24539 'amar' 4 +24540 'amas' 4 +24541 'amat' 4 +24542 'amaz' 4 +24543 'amba' 4 +24544 'ambi' 4 +24545 'ambo' 4 +24546 'amed' 4 +24547 'amel' 4 +24548 'amen' 4 +24549 'amer' 4 +24550 'ames' 4 +24551 'amic' 4 +24552 'amil' 4 +24553 'amin' 4 +24554 'amis' 4 +24555 'amma' 4 +24556 'amon' 4 +24557 'amos' 4 +24558 'ampa' 4 +24559 'ampl' 4 +24560 'amps' 4 +24561 'amus' 4 +24562 'anal' 4 +24563 'anan' 4 +24564 'anas' 4 +24565 'anca' 4 +24566 'ance' 4 +24567 'anch' 4 +24568 'anco' 4 +24569 'ancy' 4 +24570 'anda' 4 +24571 'ande' 4 +24572 'andi' 4 +24573 'ando' 4 +24574 'andr' 4 +24575 'ands' 4 +24576 'andy' 4 +24577 'aned' 4 +24578 'anel' 4 +24579 'anes' 4 +24580 'aney' 4 +24581 'anga' 4 +24582 'ange' 4 +24583 'angi' 4 +24584 'ango' 4 +24585 'angs' 4 +24586 'angu' 4 +24587 'ania' 4 +24588 'anic' 4 +24589 'anie' 4 +24590 'anim' 4 +24591 'anja' 4 +24592 'anje' 4 +24593 'anka' 4 +24594 'anke' 4 +24595 'anks' 4 +24596 'anna' 4 +24597 'anne' 4 +24598 'anni' 4 +24599 'anno' 4 +24600 'anny' 4 +24601 'anol' 4 +24602 'anon' 4 +24603 'anor' 4 +24604 'anos' 4 +24605 'anse' 4 +24606 'ansi' 4 +24607 'ansk' 4 +24608 'anst' 4 +24609 'answ' 4 +24610 'anta' 4 +24611 'ante' 4 +24612 'anth' 4 +24613 'anti' 4 +24614 'anto' 4 +24615 'ants' 4 +24616 'antz' 4 +24617 'anus' 4 +24618 'anut' 4 +24619 'anya' 4 +24620 'anye' 4 +24621 'anyl' 4 +24622 'anza' 4 +24623 'anç' 4 +24624 'apan' 4 +24625 'apat' 4 +24626 'aped' 4 +24627 'aper' 4 +24628 'apes' 4 +24629 'apid' 4 +24630 'apis' 4 +24631 'apon' 4 +24632 'apor' 4 +24633 'appa' 4 +24634 'appe' 4 +24635 'appl' 4 +24636 'apps' 4 +24637 'appy' 4 +24638 'apro' 4 +24639 'apse' 4 +24640 'apur' 4 +24641 'aque' 4 +24642 'arak' 4 +24643 'aram' 4 +24644 'aran' 4 +24645 'aras' 4 +24646 'arat' 4 +24647 'arch' 4 +24648 'arda' 4 +24649 'arde' 4 +24650 'ardi' 4 +24651 'ardo' 4 +24652 'ards' 4 +24653 'area' 4 +24654 'ared' 4 +24655 'arel' 4 +24656 'arem' 4 +24657 'aren' 4 +24658 'arer' 4 +24659 'ares' 4 +24660 'aret' 4 +24661 'arez' 4 +24662 'arga' 4 +24663 'arge' 4 +24664 'argo' 4 +24665 'args' 4 +24666 'argv' 4 +24667 'aria' 4 +24668 'arie' 4 +24669 'arin' 4 +24670 'ario' 4 +24671 'aris' 4 +24672 'arks' 4 +24673 'arlo' 4 +24674 'arly' 4 +24675 'arma' 4 +24676 'arms' 4 +24677 'arna' 4 +24678 'aron' 4 +24679 'aroo' 4 +24680 'arra' 4 +24681 'arri' 4 +24682 'arro' 4 +24683 'arry' 4 +24684 'arse' 4 +24685 'arta' 4 +24686 'arte' 4 +24687 'arth' 4 +24688 'arti' 4 +24689 'arto' 4 +24690 'arts' 4 +24691 'arty' 4 +24692 'artz' 4 +24693 'arum' 4 +24694 'arus' 4 +24695 'arya' 4 +24696 'aryl' 4 +24697 'ará' 4 +24698 'aré' 4 +24699 'arı' 4 +24700 'asan' 4 +24701 'asar' 4 +24702 'asci' 4 +24703 'asco' 4 +24704 'ased' 4 +24705 'aser' 4 +24706 'ases' 4 +24707 'aset' 4 +24708 'asha' 4 +24709 'ashi' 4 +24710 'asia' 4 +24711 'asic' 4 +24712 'asin' 4 +24713 'asio' 4 +24714 'asis' 4 +24715 'aska' 4 +24716 'asks' 4 +24717 'asma' 4 +24718 'ason' 4 +24719 'aspx' 4 +24720 'assa' 4 +24721 'asse' 4 +24722 'assi' 4 +24723 'asso' 4 +24724 'assy' 4 +24725 'asta' 4 +24726 'aste' 4 +24727 'asti' 4 +24728 'asto' 4 +24729 'astr' 4 +24730 'asts' 4 +24731 'asty' 4 +24732 'asus' 4 +24733 'atal' 4 +24734 'atan' 4 +24735 'atar' 4 +24736 'atas' 4 +24737 'atch' 4 +24738 'ated' 4 +24739 'ateg' 4 +24740 'atel' 4 +24741 'atem' 4 +24742 'aten' 4 +24743 'ater' 4 +24744 'ates' 4 +24745 'atex' 4 +24746 'atha' 4 +24747 'athe' 4 +24748 'athi' 4 +24749 'aths' 4 +24750 'athy' 4 +24751 'atia' 4 +24752 'atic' 4 +24753 'atie' 4 +24754 'atif' 4 +24755 'atin' 4 +24756 'atio' 4 +24757 'atis' 4 +24758 'ativ' 4 +24759 'atol' 4 +24760 'atom' 4 +24761 'aton' 4 +24762 'ator' 4 +24763 'atos' 4 +24764 'atra' 4 +24765 'atre' 4 +24766 'atri' 4 +24767 'atro' 4 +24768 'atsu' 4 +24769 'atta' 4 +24770 'atte' 4 +24771 'atti' 4 +24772 'attn' 4 +24773 'atto' 4 +24774 'attr' 4 +24775 'atts' 4 +24776 'atum' 4 +24777 'atur' 4 +24778 'atus' 4 +24779 'ató' 4 +24780 'ată' 4 +24781 'auch' 4 +24782 'audi' 4 +24783 'auer' 4 +24784 'auff' 4 +24785 'auge' 4 +24786 'augh' 4 +24787 'ault' 4 +24788 'aupt' 4 +24789 'aura' 4 +24790 'ause' 4 +24791 'auss' 4 +24792 'auth' 4 +24793 'auto' 4 +24794 'aval' 4 +24795 'avan' 4 +24796 'avar' 4 +24797 'avas' 4 +24798 'aved' 4 +24799 'avel' 4 +24800 'aven' 4 +24801 'aver' 4 +24802 'aves' 4 +24803 'avez' 4 +24804 'avia' 4 +24805 'avid' 4 +24806 'avig' 4 +24807 'avin' 4 +24808 'avis' 4 +24809 'avor' 4 +24810 'away' 4 +24811 'awks' 4 +24812 'axes' 4 +24813 'axis' 4 +24814 'axon' 4 +24815 'ayan' 4 +24816 'ayed' 4 +24817 'ayer' 4 +24818 'azar' 4 +24819 'azed' 4 +24820 'azer' 4 +24821 'azon' 4 +24822 'azzi' 4 +24823 'azzo' 4 +24824 'ază' 4 +24825 'aña' 4 +24826 'ała' 4 +24827 'ało' 4 +24828 'ały' 4 +24829 'baby' 4 +24830 'bach' 4 +24831 'back' 4 +24832 'bage' 4 +24833 'bags' 4 +24834 'ball' 4 +24835 'band' 4 +24836 'bane' 4 +24837 'bang' 4 +24838 'bank' 4 +24839 'bara' 4 +24840 'bard' 4 +24841 'bare' 4 +24842 'bars' 4 +24843 'bart' 4 +24844 'base' 4 +24845 'bash' 4 +24846 'bast' 4 +24847 'bath' 4 +24848 'baum' 4 +24849 'bbbb' 4 +24850 'bben' 4 +24851 'bbox' 4 +24852 'beam' 4 +24853 'bean' 4 +24854 'bear' 4 +24855 'beat' 4 +24856 'beck' 4 +24857 'been' 4 +24858 'beer' 4 +24859 'beit' 4 +24860 'bell' 4 +24861 'belt' 4 +24862 'bere' 4 +24863 'berg' 4 +24864 'bern' 4 +24865 'bers' 4 +24866 'bert' 4 +24867 'bery' 4 +24868 'best' 4 +24869 'beta' 4 +24870 'beth' 4 +24871 'bial' 4 +24872 'bian' 4 +24873 'bias' 4 +24874 'bies' 4 +24875 'bigg' 4 +24876 'bike' 4 +24877 'bild' 4 +24878 'bill' 4 +24879 'bilt' 4 +24880 'bind' 4 +24881 'bing' 4 +24882 'bins' 4 +24883 'bios' 4 +24884 'bird' 4 +24885 'bish' 4 +24886 'bits' 4 +24887 'bió' 4 +24888 'blah' 4 +24889 'bled' 4 +24890 'blem' 4 +24891 'bler' 4 +24892 'bles' 4 +24893 'blic' 4 +24894 'blob' 4 +24895 'blog' 4 +24896 'blue' 4 +24897 'blur' 4 +24898 'boat' 4 +24899 'body' 4 +24900 'bold' 4 +24901 'bole' 4 +24902 'bolt' 4 +24903 'bomb' 4 +24904 'bond' 4 +24905 'bone' 4 +24906 'bons' 4 +24907 'book' 4 +24908 'bool' 4 +24909 'boot' 4 +24910 'borg' 4 +24911 'born' 4 +24912 'boro' 4 +24913 'bose' 4 +24914 'boss' 4 +24915 'both' 4 +24916 'bour' 4 +24917 'bove' 4 +24918 'bows' 4 +24919 'boys' 4 +24920 'bral' 4 +24921 'bran' 4 +24922 'bras' 4 +24923 'bred' 4 +24924 'brew' 4 +24925 'brid' 4 +24926 'bris' 4 +24927 'brit' 4 +24928 'bron' 4 +24929 'brow' 4 +24930 'buch' 4 +24931 'buck' 4 +24932 'buff' 4 +24933 'bugs' 4 +24934 'bulk' 4 +24935 'bull' 4 +24936 'bund' 4 +24937 'burg' 4 +24938 'burn' 4 +24939 'bury' 4 +24940 'busy' 4 +24941 'byte' 4 +24942 'ból' 4 +24943 'cade' 4 +24944 'cake' 4 +24945 'calc' 4 +24946 'cale' 4 +24947 'call' 4 +24948 'came' 4 +24949 'camp' 4 +24950 'cano' 4 +24951 'cant' 4 +24952 'cape' 4 +24953 'caps' 4 +24954 'capt' 4 +24955 'carb' 4 +24956 'card' 4 +24957 'care' 4 +24958 'cars' 4 +24959 'cart' 4 +24960 'case' 4 +24961 'cash' 4 +24962 'cast' 4 +24963 'cate' 4 +24964 'cats' 4 +24965 'cccc' 4 +24966 'cdot' 4 +24967 'cean' 4 +24968 'ceed' 4 +24969 'ceil' 4 +24970 'cele' 4 +24971 'cell' 4 +24972 'cent' 4 +24973 'cept' 4 +24974 'cern' 4 +24975 'cers' 4 +24976 'cert' 4 +24977 'cery' 4 +24978 'ceso' 4 +24979 'cess' 4 +24980 'chal' 4 +24981 'chan' 4 +24982 'chap' 4 +24983 'char' 4 +24984 'chas' 4 +24985 'chat' 4 +24986 'ched' 4 +24987 'chel' 4 +24988 'chem' 4 +24989 'chen' 4 +24990 'cher' 4 +24991 'ches' 4 +24992 'chet' 4 +24993 'chev' 4 +24994 'chez' 4 +24995 'chia' 4 +24996 'chie' 4 +24997 'chin' 4 +24998 'chio' 4 +24999 'chip' 4 +25000 'chor' 4 +25001 'chos' 4 +25002 'chte' 4 +25003 'chts' 4 +25004 'chus' 4 +25005 'ché' 4 +25006 'cial' 4 +25007 'cias' 4 +25008 'cido' 4 +25009 'cies' 4 +25010 'cing' 4 +25011 'cion' 4 +25012 'cipl' 4 +25013 'circ' 4 +25014 'cite' 4 +25015 'city' 4 +25016 'cium' 4 +25017 'ció' 4 +25018 'cker' 4 +25019 'cket' 4 +25020 'ckpt' 4 +25021 'clam' 4 +25022 'clar' 4 +25023 'clas' 4 +25024 'cler' 4 +25025 'cles' 4 +25026 'clic' 4 +25027 'clin' 4 +25028 'clip' 4 +25029 'clos' 4 +25030 'club' 4 +25031 'clud' 4 +25032 'clus' 4 +25033 'coal' 4 +25034 'coat' 4 +25035 'cock' 4 +25036 'code' 4 +25037 'coef' 4 +25038 'coin' 4 +25039 'cola' 4 +25040 'cold' 4 +25041 'cole' 4 +25042 'coli' 4 +25043 'coll' 4 +25044 'colm' 4 +25045 'colo' 4 +25046 'cols' 4 +25047 'coma' 4 +25048 'comb' 4 +25049 'come' 4 +25050 'comm' 4 +25051 'como' 4 +25052 'comp' 4 +25053 'conc' 4 +25054 'cond' 4 +25055 'cone' 4 +25056 'conf' 4 +25057 'cong' 4 +25058 'coni' 4 +25059 'conj' 4 +25060 'conn' 4 +25061 'cono' 4 +25062 'cons' 4 +25063 'cont' 4 +25064 'conv' 4 +25065 'cook' 4 +25066 'cool' 4 +25067 'cope' 4 +25068 'copy' 4 +25069 'cord' 4 +25070 'core' 4 +25071 'corn' 4 +25072 'corp' 4 +25073 'corr' 4 +25074 'cost' 4 +25075 'cott' 4 +25076 'cour' 4 +25077 'cout' 4 +25078 'cred' 4 +25079 'cret' 4 +25080 'crib' 4 +25081 'crit' 4 +25082 'cron' 4 +25083 'crop' 4 +25084 'crow' 4 +25085 'csrf' 4 +25086 'ctic' 4 +25087 'ctor' 4 +25088 'ctrl' 4 +25089 'cube' 4 +25090 'cuda' 4 +25091 'cule' 4 +25092 'culo' 4 +25093 'cult' 4 +25094 'curl' 4 +25095 'curr' 4 +25096 'cuts' 4 +25097 'cyan' 4 +25098 'cycl' 4 +25099 'ców' 4 +25100 'dade' 4 +25101 'dain' 4 +25102 'dale' 4 +25103 'damn' 4 +25104 'dark' 4 +25105 'dash' 4 +25106 'data' 4 +25107 'date' 4 +25108 'days' 4 +25109 'dddd' 4 +25110 'dden' 4 +25111 'dead' 4 +25112 'deal' 4 +25113 'deck' 4 +25114 'decl' 4 +25115 'deen' 4 +25116 'deep' 4 +25117 'demo' 4 +25118 'dens' 4 +25119 'dent' 4 +25120 'dept' 4 +25121 'dera' 4 +25122 'dere' 4 +25123 'dern' 4 +25124 'derr' 4 +25125 'ders' 4 +25126 'desc' 4 +25127 'desk' 4 +25128 'dess' 4 +25129 'dest' 4 +25130 'diag' 4 +25131 'dial' 4 +25132 'dian' 4 +25133 'dice' 4 +25134 'dict' 4 +25135 'dies' 4 +25136 'diff' 4 +25137 'digo' 4 +25138 'dims' 4 +25139 'ding' 4 +25140 'dire' 4 +25141 'disc' 4 +25142 'disk' 4 +25143 'disp' 4 +25144 'diss' 4 +25145 'dist' 4 +25146 'doch' 4 +25147 'dock' 4 +25148 'docs' 4 +25149 'does' 4 +25150 'dogs' 4 +25151 'done' 4 +25152 'dong' 4 +25153 'dont' 4 +25154 'door' 4 +25155 'dorf' 4 +25156 'dose' 4 +25157 'dots' 4 +25158 'down' 4 +25159 'drag' 4 +25160 'draw' 4 +25161 'drop' 4 +25162 'drug' 4 +25163 'dual' 4 +25164 'duce' 4 +25165 'duct' 4 +25166 'duit' 4 +25167 'dule' 4 +25168 'dump' 4 +25169 'dust' 4 +25170 'duty' 4 +25171 'each' 4 +25172 'ears' 4 +25173 'east' 4 +25174 'easy' 4 +25175 'ebra' 4 +25176 'ecal' 4 +25177 'eced' 4 +25178 'eces' 4 +25179 'echa' 4 +25180 'echo' 4 +25181 'ects' 4 +25182 'edad' 4 +25183 'edar' 4 +25184 'eday' 4 +25185 'eded' 4 +25186 'edef' 4 +25187 'eden' 4 +25188 'eder' 4 +25189 'edes' 4 +25190 'edge' 4 +25191 'edia' 4 +25192 'edic' 4 +25193 'edin' 4 +25194 'edit' 4 +25195 'edly' 4 +25196 'edom' 4 +25197 'edor' 4 +25198 'educ' 4 +25199 'eeee' 4 +25200 'eful' 4 +25201 'egal' 4 +25202 'egan' 4 +25203 'egen' 4 +25204 'eger' 4 +25205 'egin' 4 +25206 'eing' 4 +25207 'eken' 4 +25208 'eker' 4 +25209 'eled' 4 +25210 'elem' 4 +25211 'elen' 4 +25212 'eler' 4 +25213 'eles' 4 +25214 'elia' 4 +25215 'elic' 4 +25216 'elif' 4 +25217 'elig' 4 +25218 'elim' 4 +25219 'elin' 4 +25220 'ella' 4 +25221 'elle' 4 +25222 'elli' 4 +25223 'ello' 4 +25224 'ells' 4 +25225 'ellt' 4 +25226 'elly' 4 +25227 'elon' 4 +25228 'elor' 4 +25229 'else' 4 +25230 'elta' 4 +25231 'elve' 4 +25232 'eman' 4 +25233 'emas' 4 +25234 'emat' 4 +25235 'emed' 4 +25236 'emen' 4 +25237 'emer' 4 +25238 'emes' 4 +25239 'emet' 4 +25240 'emia' 4 +25241 'emic' 4 +25242 'emin' 4 +25243 'emis' 4 +25244 'emit' 4 +25245 'emon' 4 +25246 'emos' 4 +25247 'empl' 4 +25248 'empt' 4 +25249 'enas' 4 +25250 'ence' 4 +25251 'ench' 4 +25252 'enci' 4 +25253 'ency' 4 +25254 'enda' 4 +25255 'ende' 4 +25256 'endi' 4 +25257 'endl' 4 +25258 'endo' 4 +25259 'ends' 4 +25260 'ened' 4 +25261 'eneg' 4 +25262 'enem' 4 +25263 'enen' 4 +25264 'ener' 4 +25265 'enes' 4 +25266 'enet' 4 +25267 'enez' 4 +25268 'enge' 4 +25269 'engl' 4 +25270 'engo' 4 +25271 'engu' 4 +25272 'enia' 4 +25273 'enic' 4 +25274 'enig' 4 +25275 'enis' 4 +25276 'enix' 4 +25277 'enko' 4 +25278 'enna' 4 +25279 'enne' 4 +25280 'enny' 4 +25281 'enos' 4 +25282 'ensa' 4 +25283 'ense' 4 +25284 'enso' 4 +25285 'enta' 4 +25286 'ente' 4 +25287 'enth' 4 +25288 'enti' 4 +25289 'ento' 4 +25290 'entr' 4 +25291 'ents' 4 +25292 'enty' 4 +25293 'enum' 4 +25294 'enza' 4 +25295 'enç' 4 +25296 'ení' 4 +25297 'eous' 4 +25298 'epad' 4 +25299 'eper' 4 +25300 'eral' 4 +25301 'eras' 4 +25302 'erca' 4 +25303 'erce' 4 +25304 'erea' 4 +25305 'ered' 4 +25306 'eree' 4 +25307 'ereg' 4 +25308 'erek' 4 +25309 'eren' 4 +25310 'erer' 4 +25311 'eres' 4 +25312 'erez' 4 +25313 'erge' 4 +25314 'ergy' 4 +25315 'eria' 4 +25316 'eric' 4 +25317 'erie' 4 +25318 'ermo' 4 +25319 'erna' 4 +25320 'erne' 4 +25321 'erno' 4 +25322 'eron' 4 +25323 'eros' 4 +25324 'erra' 4 +25325 'erre' 4 +25326 'erro' 4 +25327 'erry' 4 +25328 'erta' 4 +25329 'erte' 4 +25330 'erto' 4 +25331 'erts' 4 +25332 'erty' 4 +25333 'erva' 4 +25334 'erve' 4 +25335 'esan' 4 +25336 'esar' 4 +25337 'esch' 4 +25338 'esen' 4 +25339 'eses' 4 +25340 'esis' 4 +25341 'eson' 4 +25342 'essa' 4 +25343 'esse' 4 +25344 'esso' 4 +25345 'esta' 4 +25346 'este' 4 +25347 'esti' 4 +25348 'esto' 4 +25349 'estr' 4 +25350 'ests' 4 +25351 'esty' 4 +25352 'etag' 4 +25353 'etal' 4 +25354 'etas' 4 +25355 'etch' 4 +25356 'eted' 4 +25357 'eten' 4 +25358 'eter' 4 +25359 'etes' 4 +25360 'ethe' 4 +25361 'etic' 4 +25362 'eton' 4 +25363 'etra' 4 +25364 'etro' 4 +25365 'etry' 4 +25366 'etta' 4 +25367 'ette' 4 +25368 'etti' 4 +25369 'etto' 4 +25370 'etur' 4 +25371 'etus' 4 +25372 'etzt' 4 +25373 'età' 4 +25374 'eurs' 4 +25375 'eval' 4 +25376 'even' 4 +25377 'ever' 4 +25378 'evil' 4 +25379 'evin' 4 +25380 'eway' 4 +25381 'exam' 4 +25382 'exec' 4 +25383 'exit' 4 +25384 'expl' 4 +25385 'expr' 4 +25386 'extr' 4 +25387 'eyed' 4 +25388 'eyer' 4 +25389 'face' 4 +25390 'fact' 4 +25391 'fade' 4 +25392 'fail' 4 +25393 'fair' 4 +25394 'fake' 4 +25395 'fall' 4 +25396 'fang' 4 +25397 'fant' 4 +25398 'fare' 4 +25399 'farm' 4 +25400 'fast' 4 +25401 'feas' 4 +25402 'feat' 4 +25403 'fect' 4 +25404 'feed' 4 +25405 'feel' 4 +25406 'feit' 4 +25407 'feld' 4 +25408 'felt' 4 +25409 'fern' 4 +25410 'fers' 4 +25411 'fert' 4 +25412 'fest' 4 +25413 'ffee' 4 +25414 'ffen' 4 +25415 'ffer' 4 +25416 'ffff' 4 +25417 'ffic' 4 +25418 'fica' 4 +25419 'fico' 4 +25420 'file' 4 +25421 'fill' 4 +25422 'film' 4 +25423 'find' 4 +25424 'fine' 4 +25425 'fire' 4 +25426 'firm' 4 +25427 'fish' 4 +25428 'fits' 4 +25429 'five' 4 +25430 'flag' 4 +25431 'flat' 4 +25432 'flex' 4 +25433 'flip' 4 +25434 'flix' 4 +25435 'flow' 4 +25436 'flux' 4 +25437 'foil' 4 +25438 'fois' 4 +25439 'fold' 4 +25440 'folk' 4 +25441 'fono' 4 +25442 'font' 4 +25443 'fony' 4 +25444 'food' 4 +25445 'foot' 4 +25446 'ford' 4 +25447 'fore' 4 +25448 'fork' 4 +25449 'form' 4 +25450 'fort' 4 +25451 'four' 4 +25452 'frac' 4 +25453 'frag' 4 +25454 'frak' 4 +25455 'fram' 4 +25456 'fred' 4 +25457 'free' 4 +25458 'freq' 4 +25459 'frey' 4 +25460 'from' 4 +25461 'ften' 4 +25462 'fter' 4 +25463 'fuel' 4 +25464 'full' 4 +25465 'func' 4 +25466 'fund' 4 +25467 'furt' 4 +25468 'fusc' 4 +25469 'fuse' 4 +25470 'fér' 4 +25471 'för' 4 +25472 'füg' 4 +25473 'füh' 4 +25474 'für' 4 +25475 'gado' 4 +25476 'gage' 4 +25477 'gain' 4 +25478 'game' 4 +25479 'gang' 4 +25480 'gard' 4 +25481 'gart' 4 +25482 'gary' 4 +25483 'gate' 4 +25484 'gear' 4 +25485 'geme' 4 +25486 'gems' 4 +25487 'gend' 4 +25488 'gene' 4 +25489 'gens' 4 +25490 'gent' 4 +25491 'geom' 4 +25492 'geon' 4 +25493 'gers' 4 +25494 'gery' 4 +25495 'gest' 4 +25496 'getX' 4 +25497 'gets' 4 +25498 'gett' 4 +25499 'gger' 4 +25500 'ggle' 4 +25501 'ghan' 4 +25502 'gian' 4 +25503 'gift' 4 +25504 'ging' 4 +25505 'gins' 4 +25506 'ginx' 4 +25507 'girl' 4 +25508 'gium' 4 +25509 'give' 4 +25510 'glob' 4 +25511 'glut' 4 +25512 'goal' 4 +25513 'gold' 4 +25514 'gone' 4 +25515 'good' 4 +25516 'goog' 4 +25517 'goto' 4 +25518 'gpio' 4 +25519 'grab' 4 +25520 'grad' 4 +25521 'gram' 4 +25522 'gran' 4 +25523 'grat' 4 +25524 'grav' 4 +25525 'gray' 4 +25526 'gree' 4 +25527 'greg' 4 +25528 'gren' 4 +25529 'grep' 4 +25530 'gres' 4 +25531 'grey' 4 +25532 'grid' 4 +25533 'grow' 4 +25534 'gré' 4 +25535 'gså' 4 +25536 'guid' 4 +25537 'guns' 4 +25538 'gypt' 4 +25539 'gzip' 4 +25540 'habi' 4 +25541 'hack' 4 +25542 'haft' 4 +25543 'hair' 4 +25544 'halb' 4 +25545 'half' 4 +25546 'hall' 4 +25547 'halt' 4 +25548 'hand' 4 +25549 'hang' 4 +25550 'hani' 4 +25551 'hape' 4 +25552 'happ' 4 +25553 'haps' 4 +25554 'hard' 4 +25555 'hare' 4 +25556 'harm' 4 +25557 'hart' 4 +25558 'hash' 4 +25559 'hatt' 4 +25560 'haul' 4 +25561 'haus' 4 +25562 'have' 4 +25563 'havi' 4 +25564 'hbar' 4 +25565 'hbox' 4 +25566 'head' 4 +25567 'heal' 4 +25568 'heap' 4 +25569 'heat' 4 +25570 'heck' 4 +25571 'heed' 4 +25572 'heel' 4 +25573 'heet' 4 +25574 'heid' 4 +25575 'heim' 4 +25576 'heit' 4 +25577 'held' 4 +25578 'helf' 4 +25579 'hell' 4 +25580 'helm' 4 +25581 'help' 4 +25582 'hend' 4 +25583 'hene' 4 +25584 'heng' 4 +25585 'hens' 4 +25586 'here' 4 +25587 'hern' 4 +25588 'hero' 4 +25589 'hers' 4 +25590 'hest' 4 +25591 'heur' 4 +25592 'hide' 4 +25593 'hift' 4 +25594 'high' 4 +25595 'hill' 4 +25596 'hind' 4 +25597 'hing' 4 +25598 'hint' 4 +25599 'hips' 4 +25600 'hire' 4 +25601 'hist' 4 +25602 'hive' 4 +25603 'hlen' 4 +25604 'hler' 4 +25605 'hoff' 4 +25606 'hold' 4 +25607 'hole' 4 +25608 'holm' 4 +25609 'home' 4 +25610 'hood' 4 +25611 'hook' 4 +25612 'hope' 4 +25613 'hora' 4 +25614 'horn' 4 +25615 'hors' 4 +25616 'hort' 4 +25617 'host' 4 +25618 'hots' 4 +25619 'hour' 4 +25620 'href' 4 +25621 'html' 4 +25622 'hton' 4 +25623 'http' 4 +25624 'hung' 4 +25625 'hydr' 4 +25626 'hyth' 4 +25627 'ház' 4 +25628 'hés' 4 +25629 'hör' 4 +25630 'iada' 4 +25631 'iage' 4 +25632 'iais' 4 +25633 'iale' 4 +25634 'ials' 4 +25635 'iami' 4 +25636 'iamo' 4 +25637 'iams' 4 +25638 'iana' 4 +25639 'iane' 4 +25640 'iang' 4 +25641 'iani' 4 +25642 'iano' 4 +25643 'ians' 4 +25644 'iant' 4 +25645 'iary' 4 +25646 'iasm' 4 +25647 'iate' 4 +25648 'iał' 4 +25649 'ibal' 4 +25650 'iban' 4 +25651 'ibel' 4 +25652 'iben' 4 +25653 'iber' 4 +25654 'ibia' 4 +25655 'ibil' 4 +25656 'ible' 4 +25657 'ibli' 4 +25658 'ibly' 4 +25659 'ibus' 4 +25660 'ical' 4 +25661 'ican' 4 +25662 'icar' 4 +25663 'icas' 4 +25664 'iced' 4 +25665 'icer' 4 +25666 'ices' 4 +25667 'icha' 4 +25668 'iche' 4 +25669 'ichi' 4 +25670 'icho' 4 +25671 'icht' 4 +25672 'icia' 4 +25673 'icio' 4 +25674 'icip' 4 +25675 'icit' 4 +25676 'icki' 4 +25677 'icks' 4 +25678 'icky' 4 +25679 'icle' 4 +25680 'icol' 4 +25681 'icon' 4 +25682 'icos' 4 +25683 'icro' 4 +25684 'icts' 4 +25685 'icul' 4 +25686 'icum' 4 +25687 'icus' 4 +25688 'icut' 4 +25689 'ică' 4 +25690 'idad' 4 +25691 'idae' 4 +25692 'idal' 4 +25693 'idan' 4 +25694 'idas' 4 +25695 'iday' 4 +25696 'iddy' 4 +25697 'idea' 4 +25698 'ided' 4 +25699 'idel' 4 +25700 'iden' 4 +25701 'ideo' 4 +25702 'ider' 4 +25703 'ides' 4 +25704 'idge' 4 +25705 'idia' 4 +25706 'idin' 4 +25707 'idis' 4 +25708 'idle' 4 +25709 'idor' 4 +25710 'idos' 4 +25711 'idth' 4 +25712 'idé' 4 +25713 'iece' 4 +25714 'iego' 4 +25715 'ield' 4 +25716 'iele' 4 +25717 'iels' 4 +25718 'iene' 4 +25719 'iens' 4 +25720 'ient' 4 +25721 'iera' 4 +25722 'iere' 4 +25723 'ieri' 4 +25724 'iero' 4 +25725 'iers' 4 +25726 'iert' 4 +25727 'iese' 4 +25728 'iest' 4 +25729 'iets' 4 +25730 'iety' 4 +25731 'ieur' 4 +25732 'ieux' 4 +25733 'ieve' 4 +25734 'ieß' 4 +25735 'ież' 4 +25736 'ifar' 4 +25737 'ifax' 4 +25738 'ifen' 4 +25739 'ifer' 4 +25740 'iffe' 4 +25741 'iffs' 4 +25742 'ific' 4 +25743 'ifie' 4 +25744 'ifik' 4 +25745 'ifle' 4 +25746 'ifth' 4 +25747 'ifts' 4 +25748 'ifty' 4 +25749 'iful' 4 +25750 'igan' 4 +25751 'igar' 4 +25752 'igen' 4 +25753 'iger' 4 +25754 'iges' 4 +25755 'ighb' 4 +25756 'ight' 4 +25757 'igin' 4 +25758 'igma' 4 +25759 'igne' 4 +25760 'igon' 4 +25761 'igor' 4 +25762 'igos' 4 +25763 'igua' 4 +25764 'igue' 4 +25765 'ihad' 4 +25766 'ikal' 4 +25767 'ikan' 4 +25768 'iked' 4 +25769 'ikel' 4 +25770 'iken' 4 +25771 'iker' 4 +25772 'ikes' 4 +25773 'ikit' 4 +25774 'ikon' 4 +25775 'ikov' 4 +25776 'ilar' 4 +25777 'ilda' 4 +25778 'ilde' 4 +25779 'iled' 4 +25780 'ilee' 4 +25781 'ilen' 4 +25782 'iler' 4 +25783 'iles' 4 +25784 'ilet' 4 +25785 'iley' 4 +25786 'ilia' 4 +25787 'ilib' 4 +25788 'ilic' 4 +25789 'ilin' 4 +25790 'ilio' 4 +25791 'ilis' 4 +25792 'ilit' 4 +25793 'illa' 4 +25794 'ille' 4 +25795 'illi' 4 +25796 'illo' 4 +25797 'ills' 4 +25798 'illy' 4 +25799 'iloc' 4 +25800 'ilog' 4 +25801 'ilon' 4 +25802 'ilor' 4 +25803 'ilos' 4 +25804 'ilot' 4 +25805 'ilst' 4 +25806 'ilty' 4 +25807 'ilus' 4 +25808 'ilyn' 4 +25809 'ilà' 4 +25810 'imag' 4 +25811 'imal' 4 +25812 'iman' 4 +25813 'imap' 4 +25814 'imar' 4 +25815 'imas' 4 +25816 'imat' 4 +25817 'imed' 4 +25818 'imen' 4 +25819 'imer' 4 +25820 'imes' 4 +25821 'imet' 4 +25822 'imin' 4 +25823 'imir' 4 +25824 'imit' 4 +25825 'imon' 4 +25826 'imos' 4 +25827 'impl' 4 +25828 'imum' 4 +25829 'imus' 4 +25830 'inae' 4 +25831 'inal' 4 +25832 'inar' 4 +25833 'inas' 4 +25834 'ince' 4 +25835 'inch' 4 +25836 'inci' 4 +25837 'incl' 4 +25838 'inct' 4 +25839 'inda' 4 +25840 'inde' 4 +25841 'indi' 4 +25842 'indo' 4 +25843 'inds' 4 +25844 'indu' 4 +25845 'indy' 4 +25846 'inea' 4 +25847 'ined' 4 +25848 'inee' 4 +25849 'inel' 4 +25850 'inem' 4 +25851 'inen' 4 +25852 'iner' 4 +25853 'ines' 4 +25854 'inet' 4 +25855 'inez' 4 +25856 'infl' 4 +25857 'info' 4 +25858 'inge' 4 +25859 'ingo' 4 +25860 'ings' 4 +25861 'ingt' 4 +25862 'ingu' 4 +25863 'inha' 4 +25864 'inho' 4 +25865 'inia' 4 +25866 'inic' 4 +25867 'inin' 4 +25868 'inis' 4 +25869 'init' 4 +25870 'iniz' 4 +25871 'inja' 4 +25872 'inka' 4 +25873 'inki' 4 +25874 'inks' 4 +25875 'inky' 4 +25876 'inoa' 4 +25877 'inos' 4 +25878 'inqu' 4 +25879 'insi' 4 +25880 'insk' 4 +25881 'insn' 4 +25882 'insp' 4 +25883 'inst' 4 +25884 'inta' 4 +25885 'inte' 4 +25886 'inth' 4 +25887 'into' 4 +25888 'intr' 4 +25889 'ints' 4 +25890 'inue' 4 +25891 'inus' 4 +25892 'inux' 4 +25893 'iné' 4 +25894 'iona' 4 +25895 'ione' 4 +25896 'ioni' 4 +25897 'ions' 4 +25898 'iors' 4 +25899 'ioso' 4 +25900 'iota' 4 +25901 'iour' 4 +25902 'ious' 4 +25903 'ipal' 4 +25904 'iped' 4 +25905 'ipeg' 4 +25906 'ipel' 4 +25907 'iper' 4 +25908 'ipes' 4 +25909 'iple' 4 +25910 'ippi' 4 +25911 'ippy' 4 +25912 'ipro' 4 +25913 'ipse' 4 +25914 'ique' 4 +25915 'iral' 4 +25916 'iran' 4 +25917 'iras' 4 +25918 'irds' 4 +25919 'ired' 4 +25920 'iren' 4 +25921 'ires' 4 +25922 'irez' 4 +25923 'irie' 4 +25924 'iris' 4 +25925 'irit' 4 +25926 'irms' 4 +25927 'iron' 4 +25928 'iros' 4 +25929 'irse' 4 +25930 'irst' 4 +25931 'irth' 4 +25932 'irts' 4 +25933 'irty' 4 +25934 'irus' 4 +25935 'irá' 4 +25936 'isan' 4 +25937 'isas' 4 +25938 'isch' 4 +25939 'isco' 4 +25940 'ised' 4 +25941 'isel' 4 +25942 'isen' 4 +25943 'iser' 4 +25944 'ises' 4 +25945 'iset' 4 +25946 'isha' 4 +25947 'ishi' 4 +25948 'isia' 4 +25949 'isin' 4 +25950 'isis' 4 +25951 'iska' 4 +25952 'iske' 4 +25953 'isko' 4 +25954 'isks' 4 +25955 'isle' 4 +25956 'isma' 4 +25957 'isme' 4 +25958 'ismo' 4 +25959 'isms' 4 +25960 'isol' 4 +25961 'ison' 4 +25962 'isor' 4 +25963 'issa' 4 +25964 'isse' 4 +25965 'issy' 4 +25966 'ista' 4 +25967 'iste' 4 +25968 'isti' 4 +25969 'isto' 4 +25970 'istr' 4 +25971 'ists' 4 +25972 'isty' 4 +25973 'isé' 4 +25974 'ital' 4 +25975 'itan' 4 +25976 'itar' 4 +25977 'itas' 4 +25978 'itat' 4 +25979 'itch' 4 +25980 'ited' 4 +25981 'itel' 4 +25982 'item' 4 +25983 'iten' 4 +25984 'iter' 4 +25985 'ites' 4 +25986 'itet' 4 +25987 'ithe' 4 +25988 'itia' 4 +25989 'itic' 4 +25990 'itin' 4 +25991 'itis' 4 +25992 'itle' 4 +25993 'itol' 4 +25994 'iton' 4 +25995 'itor' 4 +25996 'itos' 4 +25997 'itro' 4 +25998 'itsu' 4 +25999 'itta' 4 +26000 'itte' 4 +26001 'itti' 4 +26002 'itto' 4 +26003 'itty' 4 +26004 'itud' 4 +26005 'itus' 4 +26006 'ità' 4 +26007 'itä' 4 +26008 'ité' 4 +26009 'ită' 4 +26010 'ival' 4 +26011 'ivan' 4 +26012 'ivar' 4 +26013 'ivas' 4 +26014 'ived' 4 +26015 'ivel' 4 +26016 'iven' 4 +26017 'iver' 4 +26018 'ives' 4 +26019 'ivia' 4 +26020 'ivic' 4 +26021 'ivid' 4 +26022 'ivil' 4 +26023 'ivir' 4 +26024 'ivos' 4 +26025 'ivot' 4 +26026 'ixed' 4 +26027 'ixel' 4 +26028 'ixin' 4 +26029 'ixon' 4 +26030 'izar' 4 +26031 'ized' 4 +26032 'izen' 4 +26033 'izer' 4 +26034 'izes' 4 +26035 'izia' 4 +26036 'izin' 4 +26037 'izio' 4 +26038 'izon' 4 +26039 'izza' 4 +26040 'ião' 4 +26041 'iça' 4 +26042 'ién' 4 +26043 'ión' 4 +26044 'jack' 4 +26045 'jang' 4 +26046 'java' 4 +26047 'jdbc' 4 +26048 'ject' 4 +26049 'jest' 4 +26050 'jets' 4 +26051 'jian' 4 +26052 'jing' 4 +26053 'jira' 4 +26054 'jobs' 4 +26055 'john' 4 +26056 'join' 4 +26057 'jong' 4 +26058 'jour' 4 +26059 'jpeg' 4 +26060 'json' 4 +26061 'jump' 4 +26062 'jury' 4 +26063 'just' 4 +26064 'ják' 4 +26065 'ján' 4 +26066 'ját' 4 +26067 'jär' 4 +26068 'jön' 4 +26069 'jör' 4 +26070 'jąc' 4 +26071 'kań' 4 +26072 'keep' 4 +26073 'kees' 4 +26074 'kehr' 4 +26075 'keit' 4 +26076 'kern' 4 +26077 'kers' 4 +26078 'keys' 4 +26079 'kick' 4 +26080 'kids' 4 +26081 'kill' 4 +26082 'kind' 4 +26083 'king' 4 +26084 'kins' 4 +26085 'know' 4 +26086 'krit' 4 +26087 'ktop' 4 +26088 'ktor' 4 +26089 'któ' 4 +26090 'ków' 4 +26091 'lace' 4 +26092 'lage' 4 +26093 'laim' 4 +26094 'lain' 4 +26095 'lake' 4 +26096 'land' 4 +26097 'lane' 4 +26098 'lang' 4 +26099 'larg' 4 +26100 'lash' 4 +26101 'lass' 4 +26102 'last' 4 +26103 'late' 4 +26104 'laus' 4 +26105 'laws' 4 +26106 'lazy' 4 +26107 'ldap' 4 +26108 'lder' 4 +26109 'lead' 4 +26110 'leaf' 4 +26111 'lean' 4 +26112 'lear' 4 +26113 'leck' 4 +26114 'lect' 4 +26115 'leen' 4 +26116 'leep' 4 +26117 'leet' 4 +26118 'left' 4 +26119 'lege' 4 +26120 'lein' 4 +26121 'lems' 4 +26122 'lene' 4 +26123 'lens' 4 +26124 'leon' 4 +26125 'lers' 4 +26126 'lesh' 4 +26127 'less' 4 +26128 'lest' 4 +26129 'lete' 4 +26130 'lets' 4 +26131 'lett' 4 +26132 'leur' 4 +26133 'leys' 4 +26134 'libc' 4 +26135 'libs' 4 +26136 'lica' 4 +26137 'lice' 4 +26138 'lich' 4 +26139 'lick' 4 +26140 'lict' 4 +26141 'lied' 4 +26142 'lier' 4 +26143 'lies' 4 +26144 'life' 4 +26145 'lift' 4 +26146 'liga' 4 +26147 'ligt' 4 +26148 'like' 4 +26149 'lime' 4 +26150 'line' 4 +26151 'ling' 4 +26152 'link' 4 +26153 'lint' 4 +26154 'lion' 4 +26155 'liqu' 4 +26156 'lish' 4 +26157 'list' 4 +26158 'lite' 4 +26159 'live' 4 +26160 'ller' 4 +26161 'lles' 4 +26162 'llvm' 4 +26163 'load' 4 +26164 'loan' 4 +26165 'loat' 4 +26166 'lock' 4 +26167 'logo' 4 +26168 'logs' 4 +26169 'loid' 4 +26170 'long' 4 +26171 'lood' 4 +26172 'look' 4 +26173 'loop' 4 +26174 'loor' 4 +26175 'lord' 4 +26176 'lose' 4 +26177 'loss' 4 +26178 'lost' 4 +26179 'lots' 4 +26180 'love' 4 +26181 'loyd' 4 +26182 'luck' 4 +26183 'lund' 4 +26184 'lung' 4 +26185 'lymp' 4 +26186 'lyph' 4 +26187 'lán' 4 +26188 'lär' 4 +26189 'läu' 4 +26190 'lès' 4 +26191 'lés' 4 +26192 'lês' 4 +26193 'mach' 4 +26194 'made' 4 +26195 'mage' 4 +26196 'magn' 4 +26197 'maid' 4 +26198 'mail' 4 +26199 'main' 4 +26200 'make' 4 +26201 'male' 4 +26202 'mall' 4 +26203 'mana' 4 +26204 'mand' 4 +26205 'mani' 4 +26206 'mann' 4 +26207 'mans' 4 +26208 'mant' 4 +26209 'many' 4 +26210 'maps' 4 +26211 'mare' 4 +26212 'mark' 4 +26213 'mars' 4 +26214 'mart' 4 +26215 'mary' 4 +26216 'mask' 4 +26217 'mass' 4 +26218 'mast' 4 +26219 'mate' 4 +26220 'math' 4 +26221 'maze' 4 +26222 'mber' 4 +26223 'mbox' 4 +26224 'meal' 4 +26225 'mean' 4 +26226 'meas' 4 +26227 'medi' 4 +26228 'meet' 4 +26229 'mega' 4 +26230 'memb' 4 +26231 'memo' 4 +26232 'meno' 4 +26233 'mens' 4 +26234 'ment' 4 +26235 'menu' 4 +26236 'merc' 4 +26237 'mere' 4 +26238 'mers' 4 +26239 'mesh' 4 +26240 'mess' 4 +26241 'meta' 4 +26242 'meth' 4 +26243 'midi' 4 +26244 'midt' 4 +26245 'mile' 4 +26246 'mill' 4 +26247 'mime' 4 +26248 'mina' 4 +26249 'mind' 4 +26250 'mine' 4 +26251 'ming' 4 +26252 'mini' 4 +26253 'mino' 4 +26254 'mins' 4 +26255 'mint' 4 +26256 'misc' 4 +26257 'mise' 4 +26258 'miss' 4 +26259 'mist' 4 +26260 'mite' 4 +26261 'mith' 4 +26262 'mits' 4 +26263 'mitt' 4 +26264 'mium' 4 +26265 'mlin' 4 +26266 'mock' 4 +26267 'mode' 4 +26268 'moil' 4 +26269 'mond' 4 +26270 'mong' 4 +26271 'mono' 4 +26272 'mons' 4 +26273 'mont' 4 +26274 'mony' 4 +26275 'moon' 4 +26276 'more' 4 +26277 'mort' 4 +26278 'most' 4 +26279 'move' 4 +26280 'mpeg' 4 +26281 'msgs' 4 +26282 'much' 4 +26283 'mult' 4 +26284 'mund' 4 +26285 'must' 4 +26286 'mute' 4 +26287 'nail' 4 +26288 'nals' 4 +26289 'nama' 4 +26290 'name' 4 +26291 'nant' 4 +26292 'nbsp' 4 +26293 'ncia' 4 +26294 'ndef' 4 +26295 'nder' 4 +26296 'ndim' 4 +26297 'near' 4 +26298 'neau' 4 +26299 'neck' 4 +26300 'nect' 4 +26301 'need' 4 +26302 'nego' 4 +26303 'nell' 4 +26304 'nels' 4 +26305 'nerg' 4 +26306 'ners' 4 +26307 'ness' 4 +26308 'nest' 4 +26309 'nets' 4 +26310 'nett' 4 +26311 'neum' 4 +26312 'neur' 4 +26313 'neut' 4 +26314 'news' 4 +26315 'next' 4 +26316 'neys' 4 +26317 'nger' 4 +26318 'nice' 4 +26319 'nick' 4 +26320 'nier' 4 +26321 'nine' 4 +26322 'ning' 4 +26323 'nist' 4 +26324 'nię' 4 +26325 'node' 4 +26326 'nome' 4 +26327 'none' 4 +26328 'noon' 4 +26329 'noop' 4 +26330 'norm' 4 +26331 'nose' 4 +26332 'nost' 4 +26333 'note' 4 +26334 'noun' 4 +26335 'nova' 4 +26336 'nown' 4 +26337 'nsic' 4 +26338 'nten' 4 +26339 'nton' 4 +26340 'null' 4 +26341 'nung' 4 +26342 'nuts' 4 +26343 'née' 4 +26344 'nés' 4 +26345 'ník' 4 +26346 'ním' 4 +26347 'oard' 4 +26348 'obal' 4 +26349 'obar' 4 +26350 'obby' 4 +26351 'ober' 4 +26352 'obia' 4 +26353 'obic' 4 +26354 'obil' 4 +26355 'oble' 4 +26356 'obox' 4 +26357 'obra' 4 +26358 'obre' 4 +26359 'obuf' 4 +26360 'ocal' 4 +26361 'ocar' 4 +26362 'occo' 4 +26363 'oche' 4 +26364 'ocks' 4 +26365 'ocoa' 4 +26366 'ocol' 4 +26367 'ocom' 4 +26368 'ocon' 4 +26369 'ocre' 4 +26370 'ocus' 4 +26371 'ocê' 4 +26372 'odal' 4 +26373 'oday' 4 +26374 'oded' 4 +26375 'odel' 4 +26376 'odem' 4 +26377 'oden' 4 +26378 'oder' 4 +26379 'odes' 4 +26380 'odge' 4 +26381 'odia' 4 +26382 'odic' 4 +26383 'odom' 4 +26384 'odon' 4 +26385 'odor' 4 +26386 'odos' 4 +26387 'odot' 4 +26388 'odox' 4 +26389 'odus' 4 +26390 'offs' 4 +26391 'ogan' 4 +26392 'ogel' 4 +26393 'ogen' 4 +26394 'ogle' 4 +26395 'ogly' 4 +26396 'ogne' 4 +26397 'ogon' 4 +26398 'ogra' 4 +26399 'ogue' 4 +26400 'ohan' 4 +26401 'oids' 4 +26402 'oine' 4 +26403 'oint' 4 +26404 'oire' 4 +26405 'oise' 4 +26406 'oked' 4 +26407 'oken' 4 +26408 'oker' 4 +26409 'okes' 4 +26410 'okia' 4 +26411 'okie' 4 +26412 'okin' 4 +26413 'olan' 4 +26414 'olar' 4 +26415 'olas' 4 +26416 'olds' 4 +26417 'oled' 4 +26418 'olem' 4 +26419 'olen' 4 +26420 'oler' 4 +26421 'oles' 4 +26422 'oley' 4 +26423 'olia' 4 +26424 'olic' 4 +26425 'olid' 4 +26426 'olin' 4 +26427 'olip' 4 +26428 'olis' 4 +26429 'olit' 4 +26430 'olla' 4 +26431 'ollo' 4 +26432 'olly' 4 +26433 'olog' 4 +26434 'olon' 4 +26435 'olor' 4 +26436 'olph' 4 +26437 'olta' 4 +26438 'olve' 4 +26439 'omal' 4 +26440 'oman' 4 +26441 'omas' 4 +26442 'omat' 4 +26443 'ombo' 4 +26444 'omed' 4 +26445 'omen' 4 +26446 'omer' 4 +26447 'omes' 4 +26448 'omet' 4 +26449 'omez' 4 +26450 'omic' 4 +26451 'omin' 4 +26452 'omit' 4 +26453 'omon' 4 +26454 'onal' 4 +26455 'onas' 4 +26456 'once' 4 +26457 'onda' 4 +26458 'onde' 4 +26459 'ondo' 4 +26460 'onds' 4 +26461 'oned' 4 +26462 'onel' 4 +26463 'onen' 4 +26464 'oner' 4 +26465 'ones' 4 +26466 'onet' 4 +26467 'oney' 4 +26468 'onga' 4 +26469 'onge' 4 +26470 'ongo' 4 +26471 'ongs' 4 +26472 'onia' 4 +26473 'onic' 4 +26474 'onio' 4 +26475 'onis' 4 +26476 'only' 4 +26477 'onna' 4 +26478 'onne' 4 +26479 'onom' 4 +26480 'onse' 4 +26481 'onso' 4 +26482 'onte' 4 +26483 'onto' 4 +26484 'onym' 4 +26485 'ooks' 4 +26486 'ools' 4 +26487 'oons' 4 +26488 'oooo' 4 +26489 'oops' 4 +26490 'ooth' 4 +26491 'opal' 4 +26492 'oped' 4 +26493 'open' 4 +26494 'oper' 4 +26495 'opes' 4 +26496 'opez' 4 +26497 'ophe' 4 +26498 'ophy' 4 +26499 'opia' 4 +26500 'opic' 4 +26501 'opin' 4 +26502 'ople' 4 +26503 'opol' 4 +26504 'opor' 4 +26505 'opot' 4 +26506 'oppy' 4 +26507 'opro' 4 +26508 'opsy' 4 +26509 'opts' 4 +26510 'opus' 4 +26511 'oque' 4 +26512 'oral' 4 +26513 'oran' 4 +26514 'oras' 4 +26515 'orce' 4 +26516 'orch' 4 +26517 'orde' 4 +26518 'ordo' 4 +26519 'ords' 4 +26520 'orea' 4 +26521 'ored' 4 +26522 'orem' 4 +26523 'oren' 4 +26524 'orer' 4 +26525 'ores' 4 +26526 'oret' 4 +26527 'orge' 4 +26528 'oria' 4 +26529 'oric' 4 +26530 'orie' 4 +26531 'orig' 4 +26532 'orin' 4 +26533 'orio' 4 +26534 'oris' 4 +26535 'orks' 4 +26536 'orld' 4 +26537 'orna' 4 +26538 'orne' 4 +26539 'orno' 4 +26540 'orns' 4 +26541 'oron' 4 +26542 'orph' 4 +26543 'orro' 4 +26544 'orry' 4 +26545 'orse' 4 +26546 'orsi' 4 +26547 'orsk' 4 +26548 'orst' 4 +26549 'orta' 4 +26550 'orte' 4 +26551 'orth' 4 +26552 'orts' 4 +26553 'orum' 4 +26554 'orus' 4 +26555 'osal' 4 +26556 'osas' 4 +26557 'osed' 4 +26558 'osen' 4 +26559 'oser' 4 +26560 'oses' 4 +26561 'osex' 4 +26562 'oshi' 4 +26563 'osin' 4 +26564 'osis' 4 +26565 'osit' 4 +26566 'osos' 4 +26567 'osph' 4 +26568 'ossa' 4 +26569 'osse' 4 +26570 'osta' 4 +26571 'oste' 4 +26572 'osti' 4 +26573 'osto' 4 +26574 'otal' 4 +26575 'oted' 4 +26576 'oten' 4 +26577 'oter' 4 +26578 'otes' 4 +26579 'othe' 4 +26580 'otho' 4 +26581 'othy' 4 +26582 'otic' 4 +26583 'otin' 4 +26584 'otle' 4 +26585 'otom' 4 +26586 'oton' 4 +26587 'otor' 4 +26588 'otos' 4 +26589 'otta' 4 +26590 'otte' 4 +26591 'otti' 4 +26592 'otto' 4 +26593 'otyp' 4 +26594 'ouch' 4 +26595 'oufl' 4 +26596 'ough' 4 +26597 'ould' 4 +26598 'ound' 4 +26599 'ount' 4 +26600 'oupe' 4 +26601 'ourd' 4 +26602 'oure' 4 +26603 'ourg' 4 +26604 'ouri' 4 +26605 'ourn' 4 +26606 'ours' 4 +26607 'ourt' 4 +26608 'ouse' 4 +26609 'ouss' 4 +26610 'oust' 4 +26611 'oute' 4 +26612 'outh' 4 +26613 'outs' 4 +26614 'ouve' 4 +26615 'oval' 4 +26616 'ovan' 4 +26617 'oved' 4 +26618 'oven' 4 +26619 'over' 4 +26620 'oves' 4 +26621 'ovic' 4 +26622 'ovie' 4 +26623 'ová' 4 +26624 'ové' 4 +26625 'ový' 4 +26626 'ově' 4 +26627 'owan' 4 +26628 'owed' 4 +26629 'owel' 4 +26630 'ower' 4 +26631 'ową' 4 +26632 'oxel' 4 +26633 'oxic' 4 +26634 'oxid' 4 +26635 'oyal' 4 +26636 'oyer' 4 +26637 'oyle' 4 +26638 'pace' 4 +26639 'pack' 4 +26640 'page' 4 +26641 'paid' 4 +26642 'pain' 4 +26643 'pair' 4 +26644 'pand' 4 +26645 'para' 4 +26646 'pard' 4 +26647 'pare' 4 +26648 'park' 4 +26649 'pars' 4 +26650 'part' 4 +26651 'pass' 4 +26652 'past' 4 +26653 'path' 4 +26654 'pdev' 4 +26655 'peak' 4 +26656 'pear' 4 +26657 'peat' 4 +26658 'pect' 4 +26659 'peed' 4 +26660 'peek' 4 +26661 'peer' 4 +26662 'pell' 4 +26663 'pend' 4 +26664 'pent' 4 +26665 'perc' 4 +26666 'perf' 4 +26667 'peri' 4 +26668 'perl' 4 +26669 'perm' 4 +26670 'perp' 4 +26671 'pers' 4 +26672 'pert' 4 +26673 'phal' 4 +26674 'phan' 4 +26675 'phas' 4 +26676 'phen' 4 +26677 'pher' 4 +26678 'phia' 4 +26679 'phil' 4 +26680 'phin' 4 +26681 'phis' 4 +26682 'phon' 4 +26683 'phot' 4 +26684 'phys' 4 +26685 'pick' 4 +26686 'pies' 4 +26687 'pile' 4 +26688 'pine' 4 +26689 'ping' 4 +26690 'pink' 4 +26691 'pins' 4 +26692 'pipe' 4 +26693 'pire' 4 +26694 'pite' 4 +26695 'plan' 4 +26696 'plat' 4 +26697 'play' 4 +26698 'pled' 4 +26699 'pler' 4 +26700 'ples' 4 +26701 'plet' 4 +26702 'plex' 4 +26703 'plic' 4 +26704 'plit' 4 +26705 'plot' 4 +26706 'ploy' 4 +26707 'plug' 4 +26708 'plus' 4 +26709 'pmod' 4 +26710 'poke' 4 +26711 'pole' 4 +26712 'poll' 4 +26713 'poly' 4 +26714 'pond' 4 +26715 'pone' 4 +26716 'pong' 4 +26717 'pons' 4 +26718 'pool' 4 +26719 'poon' 4 +26720 'pora' 4 +26721 'port' 4 +26722 'pose' 4 +26723 'poss' 4 +26724 'post' 4 +26725 'pour' 4 +26726 'pped' 4 +26727 'ppen' 4 +26728 'pper' 4 +26729 'prec' 4 +26730 'pred' 4 +26731 'pref' 4 +26732 'prem' 4 +26733 'prep' 4 +26734 'pres' 4 +26735 'pret' 4 +26736 'prev' 4 +26737 'pril' 4 +26738 'prim' 4 +26739 'prit' 4 +26740 'priv' 4 +26741 'prob' 4 +26742 'proc' 4 +26743 'prod' 4 +26744 'prof' 4 +26745 'prog' 4 +26746 'proj' 4 +26747 'prom' 4 +26748 'pron' 4 +26749 'prop' 4 +26750 'prot' 4 +26751 'prov' 4 +26752 'prox' 4 +26753 'prus' 4 +26754 'prü' 4 +26755 'pson' 4 +26756 'ptic' 4 +26757 'pton' 4 +26758 'publ' 4 +26759 'pull' 4 +26760 'punk' 4 +26761 'pure' 4 +26762 'push' 4 +26763 'pute' 4 +26764 'qing' 4 +26765 'quad' 4 +26766 'qual' 4 +26767 'quan' 4 +26768 'quar' 4 +26769 'quat' 4 +26770 'quee' 4 +26771 'quel' 4 +26772 'quer' 4 +26773 'ques' 4 +26774 'quet' 4 +26775 'quez' 4 +26776 'quia' 4 +26777 'quin' 4 +26778 'quir' 4 +26779 'quis' 4 +26780 'quit' 4 +26781 'quiz' 4 +26782 'quot' 4 +26783 'qué' 4 +26784 'race' 4 +26785 'rack' 4 +26786 'ract' 4 +26787 'rada' 4 +26788 'rade' 4 +26789 'radi' 4 +26790 'rado' 4 +26791 'rael' 4 +26792 'raft' 4 +26793 'rage' 4 +26794 'raid' 4 +26795 'rail' 4 +26796 'rain' 4 +26797 'rais' 4 +26798 'rait' 4 +26799 'rale' 4 +26800 'rama' 4 +26801 'rame' 4 +26802 'rams' 4 +26803 'rand' 4 +26804 'rane' 4 +26805 'rang' 4 +26806 'rank' 4 +26807 'rano' 4 +26808 'rans' 4 +26809 'rant' 4 +26810 'raph' 4 +26811 'rare' 4 +26812 'rary' 4 +26813 'rase' 4 +26814 'rast' 4 +26815 'rate' 4 +26816 'rats' 4 +26817 'raud' 4 +26818 'rawl' 4 +26819 'rawn' 4 +26820 'rays' 4 +26821 'read' 4 +26822 'reak' 4 +26823 'real' 4 +26824 'ream' 4 +26825 'reas' 4 +26826 'reat' 4 +26827 'rece' 4 +26828 'reci' 4 +26829 'reck' 4 +26830 'rect' 4 +26831 'recv' 4 +26832 'rede' 4 +26833 'redi' 4 +26834 'redo' 4 +26835 'redu' 4 +26836 'reed' 4 +26837 'reek' 4 +26838 'reen' 4 +26839 'rees' 4 +26840 'reet' 4 +26841 'refs' 4 +26842 'regn' 4 +26843 'regs' 4 +26844 'reib' 4 +26845 'rein' 4 +26846 'rell' 4 +26847 'rels' 4 +26848 'relu' 4 +26849 'reme' 4 +26850 'rena' 4 +26851 'rend' 4 +26852 'rene' 4 +26853 'reno' 4 +26854 'rens' 4 +26855 'rent' 4 +26856 'reon' 4 +26857 'repo' 4 +26858 'repr' 4 +26859 'requ' 4 +26860 'rera' 4 +26861 'rero' 4 +26862 'resa' 4 +26863 'rese' 4 +26864 'resh' 4 +26865 'reso' 4 +26866 'resp' 4 +26867 'ress' 4 +26868 'rest' 4 +26869 'reta' 4 +26870 'rete' 4 +26871 'rets' 4 +26872 'rett' 4 +26873 'reve' 4 +26874 'rgba' 4 +26875 'riad' 4 +26876 'rial' 4 +26877 'rian' 4 +26878 'rias' 4 +26879 'rica' 4 +26880 'rice' 4 +26881 'rich' 4 +26882 'rick' 4 +26883 'rico' 4 +26884 'rics' 4 +26885 'rict' 4 +26886 'ride' 4 +26887 'ried' 4 +26888 'rief' 4 +26889 'riel' 4 +26890 'rien' 4 +26891 'rier' 4 +26892 'ries' 4 +26893 'riet' 4 +26894 'rift' 4 +26895 'rika' 4 +26896 'rike' 4 +26897 'rile' 4 +26898 'rimp' 4 +26899 'rina' 4 +26900 'rine' 4 +26901 'ring' 4 +26902 'rink' 4 +26903 'rint' 4 +26904 'rior' 4 +26905 'rios' 4 +26906 'riot' 4 +26907 'ripp' 4 +26908 'ript' 4 +26909 'rire' 4 +26910 'rise' 4 +26911 'rish' 4 +26912 'risk' 4 +26913 'rist' 4 +26914 'rite' 4 +26915 'rito' 4 +26916 'ritt' 4 +26917 'ritz' 4 +26918 'rium' 4 +26919 'rive' 4 +26920 'rió' 4 +26921 'road' 4 +26922 'robe' 4 +26923 'rock' 4 +26924 'rodu' 4 +26925 'roid' 4 +26926 'rois' 4 +26927 'roit' 4 +26928 'roke' 4 +26929 'role' 4 +26930 'roll' 4 +26931 'roma' 4 +26932 'rome' 4 +26933 'romy' 4 +26934 'rone' 4 +26935 'rong' 4 +26936 'rons' 4 +26937 'ront' 4 +26938 'room' 4 +26939 'root' 4 +26940 'roph' 4 +26941 'rops' 4 +26942 'ropy' 4 +26943 'rors' 4 +26944 'rose' 4 +26945 'ross' 4 +26946 'rost' 4 +26947 'rote' 4 +26948 'rots' 4 +26949 'rott' 4 +26950 'roup' 4 +26951 'rous' 4 +26952 'rout' 4 +26953 'rove' 4 +26954 'rown' 4 +26955 'rows' 4 +26956 'rror' 4 +26957 'ruby' 4 +26958 'ruce' 4 +26959 'ruck' 4 +26960 'ruct' 4 +26961 'ruit' 4 +26962 'rule' 4 +26963 'runs' 4 +26964 'rupt' 4 +26965 'rust' 4 +26966 'ryan' 4 +26967 'rypt' 4 +26968 'rás' 4 +26969 'rän' 4 +26970 'rès' 4 +26971 'rée' 4 +26972 'rés' 4 +26973 'rét' 4 +26974 'ría' 4 +26975 'ród' 4 +26976 'rón' 4 +26977 'safe' 4 +26978 'said' 4 +26979 'sale' 4 +26980 'salt' 4 +26981 'same' 4 +26982 'samp' 4 +26983 'sand' 4 +26984 'sans' 4 +26985 'save' 4 +26986 'scal' 4 +26987 'scan' 4 +26988 'scar' 4 +26989 'sche' 4 +26990 'scre' 4 +26991 'scri' 4 +26992 'seat' 4 +26993 'seau' 4 +26994 'sect' 4 +26995 'seed' 4 +26996 'seek' 4 +26997 'seen' 4 +26998 'sein' 4 +26999 'self' 4 +27000 'sell' 4 +27001 'semb' 4 +27002 'semi' 4 +27003 'send' 4 +27004 'sens' 4 +27005 'sent' 4 +27006 'sequ' 4 +27007 'sers' 4 +27008 'sert' 4 +27009 'serv' 4 +27010 'sess' 4 +27011 'sets' 4 +27012 'sett' 4 +27013 'seud' 4 +27014 'shal' 4 +27015 'shan' 4 +27016 'shaw' 4 +27017 'ship' 4 +27018 'shit' 4 +27019 'shop' 4 +27020 'shot' 4 +27021 'show' 4 +27022 'shut' 4 +27023 'side' 4 +27024 'sign' 4 +27025 'sime' 4 +27026 'simp' 4 +27027 'sing' 4 +27028 'sink' 4 +27029 'site' 4 +27030 'size' 4 +27031 'skin' 4 +27032 'skip' 4 +27033 'ská' 4 +27034 'ské' 4 +27035 'ský' 4 +27036 'ską' 4 +27037 'slot' 4 +27038 'slow' 4 +27039 'slug' 4 +27040 'smtp' 4 +27041 'snap' 4 +27042 'snow' 4 +27043 'soap' 4 +27044 'sock' 4 +27045 'soft' 4 +27046 'sold' 4 +27047 'sole' 4 +27048 'some' 4 +27049 'song' 4 +27050 'sono' 4 +27051 'soon' 4 +27052 'sort' 4 +27053 'soup' 4 +27054 'spam' 4 +27055 'span' 4 +27056 'spar' 4 +27057 'spec' 4 +27058 'spin' 4 +27059 'spir' 4 +27060 'spot' 4 +27061 'sqrt' 4 +27062 'sson' 4 +27063 'stab' 4 +27064 'stad' 4 +27065 'stag' 4 +27066 'stal' 4 +27067 'stan' 4 +27068 'star' 4 +27069 'stat' 4 +27070 'stay' 4 +27071 'sted' 4 +27072 'stem' 4 +27073 'sten' 4 +27074 'step' 4 +27075 'ster' 4 +27076 'stic' 4 +27077 'stim' 4 +27078 'stit' 4 +27079 'stmt' 4 +27080 'ston' 4 +27081 'stop' 4 +27082 'stor' 4 +27083 'stra' 4 +27084 'stre' 4 +27085 'stri' 4 +27086 'stro' 4 +27087 'stru' 4 +27088 'stry' 4 +27089 'stub' 4 +27090 'stud' 4 +27091 'stä' 4 +27092 'stå' 4 +27093 'subs' 4 +27094 'succ' 4 +27095 'such' 4 +27096 'sudo' 4 +27097 'suit' 4 +27098 'summ' 4 +27099 'supp' 4 +27100 'sure' 4 +27101 'surf' 4 +27102 'swap' 4 +27103 'swer' 4 +27104 'sync' 4 +27105 'ség' 4 +27106 'tabs' 4 +27107 'tage' 4 +27108 'tags' 4 +27109 'tail' 4 +27110 'tain' 4 +27111 'tait' 4 +27112 'take' 4 +27113 'talk' 4 +27114 'tang' 4 +27115 'tanh' 4 +27116 'tank' 4 +27117 'task' 4 +27118 'tawa' 4 +27119 'tał' 4 +27120 'team' 4 +27121 'tech' 4 +27122 'teen' 4 +27123 'tegr' 4 +27124 'teil' 4 +27125 'tein' 4 +27126 'tele' 4 +27127 'tell' 4 +27128 'temp' 4 +27129 'tent' 4 +27130 'tera' 4 +27131 'tere' 4 +27132 'term' 4 +27133 'tern' 4 +27134 'tero' 4 +27135 'ters' 4 +27136 'tery' 4 +27137 'test' 4 +27138 'tesy' 4 +27139 'text' 4 +27140 'thal' 4 +27141 'than' 4 +27142 'that' 4 +27143 'thel' 4 +27144 'them' 4 +27145 'then' 4 +27146 'ther' 4 +27147 'thes' 4 +27148 'they' 4 +27149 'thin' 4 +27150 'this' 4 +27151 'thon' 4 +27152 'thor' 4 +27153 'thro' 4 +27154 'thur' 4 +27155 'thus' 4 +27156 'tica' 4 +27157 'tick' 4 +27158 'tico' 4 +27159 'tics' 4 +27160 'tier' 4 +27161 'ties' 4 +27162 'tiff' 4 +27163 'tikz' 4 +27164 'tile' 4 +27165 'time' 4 +27166 'ting' 4 +27167 'tiny' 4 +27168 'tion' 4 +27169 'tipo' 4 +27170 'tips' 4 +27171 'toBe' 4 +27172 'todo' 4 +27173 'tone' 4 +27174 'tons' 4 +27175 'took' 4 +27176 'tool' 4 +27177 'toon' 4 +27178 'tour' 4 +27179 'tout' 4 +27180 'town' 4 +27181 'trac' 4 +27182 'trad' 4 +27183 'trak' 4 +27184 'tran' 4 +27185 'trap' 4 +27186 'tras' 4 +27187 'tree' 4 +27188 'tres' 4 +27189 'trib' 4 +27190 'trie' 4 +27191 'trig' 4 +27192 'trim' 4 +27193 'trip' 4 +27194 'tron' 4 +27195 'true' 4 +27196 'ttes' 4 +27197 'tube' 4 +27198 'ture' 4 +27199 'turn' 4 +27200 'type' 4 +27201 'uala' 4 +27202 'uali' 4 +27203 'uant' 4 +27204 'uart' 4 +27205 'uary' 4 +27206 'uate' 4 +27207 'ubar' 4 +27208 'uben' 4 +27209 'uber' 4 +27210 'ubes' 4 +27211 'ubic' 4 +27212 'uble' 4 +27213 'ubre' 4 +27214 'ucci' 4 +27215 'uced' 4 +27216 'ucer' 4 +27217 'uces' 4 +27218 'ucha' 4 +27219 'uche' 4 +27220 'uchi' 4 +27221 'uchs' 4 +27222 'ucht' 4 +27223 'ucid' 4 +27224 'ucks' 4 +27225 'ucky' 4 +27226 'ucle' 4 +27227 'udad' 4 +27228 'uded' 4 +27229 'uden' 4 +27230 'uder' 4 +27231 'udes' 4 +27232 'udge' 4 +27233 'udio' 4 +27234 'udos' 4 +27235 'uego' 4 +27236 'ueil' 4 +27237 'uela' 4 +27238 'uels' 4 +27239 'uent' 4 +27240 'uers' 4 +27241 'uese' 4 +27242 'uest' 4 +27243 'ueur' 4 +27244 'ufen' 4 +27245 'uffs' 4 +27246 'uffy' 4 +27247 'ugal' 4 +27248 'ugar' 4 +27249 'ugby' 4 +27250 'ugen' 4 +27251 'ught' 4 +27252 'ugin' 4 +27253 'uild' 4 +27254 'uilt' 4 +27255 'uing' 4 +27256 'uins' 4 +27257 'uint' 4 +27258 'uish' 4 +27259 'uite' 4 +27260 'uits' 4 +27261 'uity' 4 +27262 'ují' 4 +27263 'ują' 4 +27264 'ukes' 4 +27265 'ular' 4 +27266 'ulas' 4 +27267 'uled' 4 +27268 'ulen' 4 +27269 'uler' 4 +27270 'ules' 4 +27271 'ulet' 4 +27272 'ulia' 4 +27273 'ulin' 4 +27274 'ulis' 4 +27275 'ulla' 4 +27276 'ulle' 4 +27277 'ulli' 4 +27278 'ulls' 4 +27279 'ully' 4 +27280 'ulos' 4 +27281 'ulpt' 4 +27282 'ulse' 4 +27283 'ulti' 4 +27284 'ults' 4 +27285 'ulty' 4 +27286 'ultz' 4 +27287 'ului' 4 +27288 'ulum' 4 +27289 'ulus' 4 +27290 'umab' 4 +27291 'uman' 4 +27292 'umar' 4 +27293 'umas' 4 +27294 'umat' 4 +27295 'umbn' 4 +27296 'umbo' 4 +27297 'umbs' 4 +27298 'umed' 4 +27299 'umen' 4 +27300 'umer' 4 +27301 'umes' 4 +27302 'umin' 4 +27303 'ummy' 4 +27304 'umni' 4 +27305 'umor' 4 +27306 'umph' 4 +27307 'umps' 4 +27308 'umpy' 4 +27309 'unal' 4 +27310 'unar' 4 +27311 'unas' 4 +27312 'unce' 4 +27313 'unch' 4 +27314 'unci' 4 +27315 'unct' 4 +27316 'unda' 4 +27317 'unde' 4 +27318 'undo' 4 +27319 'unds' 4 +27320 'undy' 4 +27321 'uned' 4 +27322 'uner' 4 +27323 'unes' 4 +27324 'unge' 4 +27325 'ungs' 4 +27326 'unic' 4 +27327 'unik' 4 +27328 'uniq' 4 +27329 'unit' 4 +27330 'unix' 4 +27331 'unks' 4 +27332 'unkt' 4 +27333 'unos' 4 +27334 'unta' 4 +27335 'unte' 4 +27336 'unto' 4 +27337 'unts' 4 +27338 'untu' 4 +27339 'unya' 4 +27340 'uous' 4 +27341 'upal' 4 +27342 'uper' 4 +27343 'upid' 4 +27344 'uple' 4 +27345 'upon' 4 +27346 'urai' 4 +27347 'ural' 4 +27348 'uran' 4 +27349 'uras' 4 +27350 'urch' 4 +27351 'urdy' 4 +27352 'ured' 4 +27353 'uren' 4 +27354 'urer' 4 +27355 'ures' 4 +27356 'uria' 4 +27357 'uris' 4 +27358 'urls' 4 +27359 'uron' 4 +27360 'urop' 4 +27361 'urre' 4 +27362 'urry' 4 +27363 'urse' 4 +27364 'urst' 4 +27365 'urus' 4 +27366 'usal' 4 +27367 'usat' 4 +27368 'usch' 4 +27369 'used' 4 +27370 'user' 4 +27371 'uses' 4 +27372 'uset' 4 +27373 'ushi' 4 +27374 'usic' 4 +27375 'ussy' 4 +27376 'usta' 4 +27377 'usto' 4 +27378 'ustr' 4 +27379 'utan' 4 +27380 'utar' 4 +27381 'utch' 4 +27382 'uted' 4 +27383 'uten' 4 +27384 'uter' 4 +27385 'utes' 4 +27386 'util' 4 +27387 'utor' 4 +27388 'utos' 4 +27389 'utra' 4 +27390 'utta' 4 +27391 'utto' 4 +27392 'uuid' 4 +27393 'uvre' 4 +27394 'uzzi' 4 +27395 'uzzy' 4 +27396 'ués' 4 +27397 'vais' 4 +27398 'vale' 4 +27399 'vals' 4 +27400 'valu' 4 +27401 'vana' 4 +27402 'vant' 4 +27403 'vard' 4 +27404 'vare' 4 +27405 'vari' 4 +27406 'vars' 4 +27407 'vecs' 4 +27408 'vect' 4 +27409 'veis' 4 +27410 'vell' 4 +27411 'velt' 4 +27412 'vely' 4 +27413 'vens' 4 +27414 'vent' 4 +27415 'verb' 4 +27416 'vere' 4 +27417 'vern' 4 +27418 'vers' 4 +27419 'vert' 4 +27420 'very' 4 +27421 'vest' 4 +27422 'vice' 4 +27423 'vict' 4 +27424 'vide' 4 +27425 'vier' 4 +27426 'view' 4 +27427 'vill' 4 +27428 'vine' 4 +27429 'ving' 4 +27430 'viol' 4 +27431 'virt' 4 +27432 'vity' 4 +27433 'vić' 4 +27434 'vlan' 4 +27435 'void' 4 +27436 'voir' 4 +27437 'voke' 4 +27438 'volt' 4 +27439 'vote' 4 +27440 'vous' 4 +27441 'vron' 4 +27442 'ván' 4 +27443 'vés' 4 +27444 'wait' 4 +27445 'wake' 4 +27446 'wald' 4 +27447 'walk' 4 +27448 'wall' 4 +27449 'wand' 4 +27450 'wang' 4 +27451 'want' 4 +27452 'ward' 4 +27453 'ware' 4 +27454 'warf' 4 +27455 'warm' 4 +27456 'warn' 4 +27457 'wart' 4 +27458 'warz' 4 +27459 'wash' 4 +27460 'wave' 4 +27461 'ways' 4 +27462 'weak' 4 +27463 'wear' 4 +27464 'weed' 4 +27465 'week' 4 +27466 'ween' 4 +27467 'weep' 4 +27468 'weet' 4 +27469 'well' 4 +27470 'wend' 4 +27471 'went' 4 +27472 'were' 4 +27473 'wers' 4 +27474 'wert' 4 +27475 'west' 4 +27476 'what' 4 +27477 'whel' 4 +27478 'when' 4 +27479 'wich' 4 +27480 'wick' 4 +27481 'wide' 4 +27482 'wife' 4 +27483 'wifi' 4 +27484 'wiki' 4 +27485 'wild' 4 +27486 'will' 4 +27487 'wind' 4 +27488 'wine' 4 +27489 'wing' 4 +27490 'wire' 4 +27491 'wise' 4 +27492 'wish' 4 +27493 'with' 4 +27494 'witz' 4 +27495 'wią' 4 +27496 'wię' 4 +27497 'wner' 4 +27498 'wolf' 4 +27499 'wood' 4 +27500 'word' 4 +27501 'work' 4 +27502 'worm' 4 +27503 'wort' 4 +27504 'wrap' 4 +27505 'writ' 4 +27506 'wär' 4 +27507 'wür' 4 +27508 'xico' 4 +27509 'ximo' 4 +27510 'xlim' 4 +27511 'xlsx' 4 +27512 'xmax' 4 +27513 'xton' 4 +27514 'xxxx' 4 +27515 'yaml' 4 +27516 'yang' 4 +27517 'yard' 4 +27518 'ycle' 4 +27519 'ydia' 4 +27520 'ydro' 4 +27521 'year' 4 +27522 'yect' 4 +27523 'yers' 4 +27524 'ygon' 4 +27525 'ying' 4 +27526 'ylan' 4 +27527 'yles' 4 +27528 'ylim' 4 +27529 'ylon' 4 +27530 'ylum' 4 +27531 'ymax' 4 +27532 'ymph' 4 +27533 'ynam' 4 +27534 'ynch' 4 +27535 'ynes' 4 +27536 'yond' 4 +27537 'your' 4 +27538 'yout' 4 +27539 'ypes' 4 +27540 'yrus' 4 +27541 'yses' 4 +27542 'ysis' 4 +27543 'yson' 4 +27544 'ysql' 4 +27545 'ytic' 4 +27546 'yyyy' 4 +27547 'zahl' 4 +27548 'zech' 4 +27549 'zeit' 4 +27550 'zens' 4 +27551 'zent' 4 +27552 'zero' 4 +27553 'zeta' 4 +27554 'zeug' 4 +27555 'zeń' 4 +27556 'ześ' 4 +27557 'zhen' 4 +27558 'zhou' 4 +27559 'zial' 4 +27560 'ziel' 4 +27561 'zier' 4 +27562 'zing' 4 +27563 'ził' 4 +27564 'zone' 4 +27565 'zoom' 4 +27566 'zung' 4 +27567 'zyme' 4 +27568 'zyć' 4 +27569 'zyż' 4 +27570 'zzle' 4 +27571 'zés' 4 +27572 'zös' 4 +27573 'ząd' 4 +27574 'ząt' 4 +27575 '}}' 5 +32856 '="../' 5 +32857 '=====' 5 +32858 'ABASE' 5 +32859 'ACION' 5 +32860 'ACTER' 5 +32861 'ADMIN' 5 +32862 'ALIGN' 5 +32863 'ALLOW' 5 +32864 'ALTER' 5 +32865 'AMPLE' 5 +32866 'ANNEL' 5 +32867 'ANTLR' 5 +32868 'APTER' 5 +32869 'ARGET' 5 +32870 'ARRAY' 5 +32871 'ASCII' 5 +32872 'ATING' 5 +32873 'ATION' 5 +32874 'ATIVE' 5 +32875 'ATURE' 5 +32876 'About' 5 +32877 'Above' 5 +32878 'Activ' 5 +32879 'Actor' 5 +32880 'Added' 5 +32881 'Addon' 5 +32882 'Admin' 5 +32883 'After' 5 +32884 'Again' 5 +32885 'Agent' 5 +32886 'Alarm' 5 +32887 'Album' 5 +32888 'Alert' 5 +32889 'Alias' 5 +32890 'Alice' 5 +32891 'Align' 5 +32892 'Alive' 5 +32893 'Allen' 5 +32894 'Alloc' 5 +32895 'Allow' 5 +32896 'Along' 5 +32897 'Alpha' 5 +32898 'Alter' 5 +32899 'Among' 5 +32900 'Analy' 5 +32901 'Andre' 5 +32902 'Angel' 5 +32903 'Angle' 5 +32904 'Apart' 5 +32905 'Apple' 5 +32906 'Apply' 5 +32907 'Appro' 5 +32908 'April' 5 +32909 'Arena' 5 +32910 'Arial' 5 +32911 'Armor' 5 +32912 'Array' 5 +32913 'Arrow' 5 +32914 'Asian' 5 +32915 'Asked' 5 +32916 'Asset' 5 +32917 'Async' 5 +32918 'Atlas' 5 +32919 'Attrs' 5 +32920 'Audio' 5 +32921 'Audit' 5 +32922 'Autom' 5 +32923 'Aware' 5 +32924 'Azure' 5 +32925 'BEGIN' 5 +32926 'BLACK' 5 +32927 'BLOCK' 5 +32928 'BOARD' 5 +32929 'BOOST' 5 +32930 'BUILD' 5 +32931 'Based' 5 +32932 'Basic' 5 +32933 'Batch' 5 +32934 'Beans' 5 +32935 'Begin' 5 +32936 'Being' 5 +32937 'Below' 5 +32938 'Berry' 5 +32939 'Billy' 5 +32940 'Birth' 5 +32941 'Black' 5 +32942 'Blank' 5 +32943 'Block' 5 +32944 'Blood' 5 +32945 'Board' 5 +32946 'Bonus' 5 +32947 'Books' 5 +32948 'Boost' 5 +32949 'Bound' 5 +32950 'Brain' 5 +32951 'Brand' 5 +32952 'Break' 5 +32953 'Brian' 5 +32954 'Brien' 5 +32955 'Bring' 5 +32956 'Broad' 5 +32957 'Brown' 5 +32958 'Brush' 5 +32959 'Build' 5 +32960 'Built' 5 +32961 'Bytes' 5 +32962 'Bạn' 5 +32963 'CACHE' 5 +32964 'CCESS' 5 +32965 'CDATA' 5 +32966 'CHANT' 5 +32967 'CHECK' 5 +32968 'CLAIM' 5 +32969 'CLASS' 5 +32970 'CLEAR' 5 +32971 'CLUDE' 5 +32972 'COLOR' 5 +32973 'CONST' 5 +32974 'COUNT' 5 +32975 'COVID' 5 +32976 'CRIPT' 5 +32977 'CRYPT' 5 +32978 'CTION' 5 +32979 'CTYPE' 5 +32980 'Cache' 5 +32981 'Calls' 5 +32982 'Carol' 5 +32983 'Catal' 5 +32984 'Catch' 5 +32985 'Cause' 5 +32986 'Cells' 5 +32987 'Chain' 5 +32988 'Chang' 5 +32989 'Chars' 5 +32990 'Chart' 5 +32991 'Check' 5 +32992 'Chief' 5 +32993 'Child' 5 +32994 'China' 5 +32995 'Chris' 5 +32996 'Chunk' 5 +32997 'Civil' 5 +32998 'Claim' 5 +32999 'Class' 5 +33000 'Clean' 5 +33001 'Clear' 5 +33002 'Click' 5 +33003 'Clock' 5 +33004 'Clone' 5 +33005 'Close' 5 +33006 'Cloud' 5 +33007 'Codec' 5 +33008 'Codes' 5 +33009 'Color' 5 +33010 'Combo' 5 +33011 'Compl' 5 +33012 'Const' 5 +33013 'Contr' 5 +33014 'Coord' 5 +33015 'Could' 5 +33016 'Count' 5 +33017 'Court' 5 +33018 'Cover' 5 +33019 'Craft' 5 +33020 'Creat' 5 +33021 'Cross' 5 +33022 'Crypt' 5 +33023 'Curve' 5 +33024 'Cycle' 5 +33025 'Cómo' 5 +33026 'DEBUG' 5 +33027 'DELAY' 5 +33028 'DEPTH' 5 +33029 'Daily' 5 +33030 'Dates' 5 +33031 'Datum' 5 +33032 'David' 5 +33033 'Davis' 5 +33034 'Death' 5 +33035 'Debug' 5 +33036 'Decor' 5 +33037 'Delay' 5 +33038 'Deleg' 5 +33039 'Delta' 5 +33040 'Dense' 5 +33041 'Depth' 5 +33042 'Digit' 5 +33043 'Dirty' 5 +33044 'Domin' 5 +33045 'Draft' 5 +33046 'Dream' 5 +33047 'Drive' 5 +33048 'Dummy' 5 +33049 'EMAIL' 5 +33050 'EMBER' 5 +33051 'EMENT' 5 +33052 'EMPTY' 5 +33053 'ENAME' 5 +33054 'ENCES' 5 +33055 'ENDER' 5 +33056 'ENGTH' 5 +33057 'ENTER' 5 +33058 'ENTRY' 5 +33059 'EQUAL' 5 +33060 'ERROR' 5 +33061 'ETHER' 5 +33062 'ETHOD' 5 +33063 'EVENT' 5 +33064 'EXIST' 5 +33065 'Early' 5 +33066 'Earth' 5 +33067 'Edges' 5 +33068 'Eight' 5 +33069 'Elect' 5 +33070 'Email' 5 +33071 'Embed' 5 +33072 'Emily' 5 +33073 'Empty' 5 +33074 'Enjoy' 5 +33075 'Enter' 5 +33076 'Entry' 5 +33077 'Epoch' 5 +33078 'Equal' 5 +33079 'Error' 5 +33080 'Estim' 5 +33081 'Evalu' 5 +33082 'Event' 5 +33083 'Every' 5 +33084 'Exact' 5 +33085 'Excel' 5 +33086 'Exist' 5 +33087 'Extra' 5 +33088 'FALSE' 5 +33089 'FAULT' 5 +33090 'FIELD' 5 +33091 'FILES' 5 +33092 'FIRST' 5 +33093 'FIXME' 5 +33094 'FLAGS' 5 +33095 'FLOAT' 5 +33096 'FOUND' 5 +33097 'FRAME' 5 +33098 'Faces' 5 +33099 'False' 5 +33100 'Fatal' 5 +33101 'Fault' 5 +33102 'Fetch' 5 +33103 'Field' 5 +33104 'Files' 5 +33105 'Final' 5 +33106 'First' 5 +33107 'Fixed' 5 +33108 'Flags' 5 +33109 'Flash' 5 +33110 'Float' 5 +33111 'Floor' 5 +33112 'Flush' 5 +33113 'Focus' 5 +33114 'Force' 5 +33115 'Forms' 5 +33116 'Forum' 5 +33117 'Found' 5 +33118 'Frame' 5 +33119 'Franc' 5 +33120 'Frank' 5 +33121 'Fresh' 5 +33122 'Front' 5 +33123 'GENER' 5 +33124 'GRAPH' 5 +33125 'GREEN' 5 +33126 'GRESS' 5 +33127 'GROUP' 5 +33128 'Games' 5 +33129 'Gamma' 5 +33130 'Gener' 5 +33131 'Genre' 5 +33132 'Georg' 5 +33133 'Getty' 5 +33134 'Ghost' 5 +33135 'Given' 5 +33136 'Glyph' 5 +33137 'Going' 5 +33138 'Grade' 5 +33139 'Grand' 5 +33140 'Grant' 5 +33141 'Graph' 5 +33142 'Great' 5 +33143 'Greek' 5 +33144 'Green' 5 +33145 'Group' 5 +33146 'Guard' 5 +33147 'Guest' 5 +33148 'Guide' 5 +33149 'Guild' 5 +33150 'HTTPS' 5 +33151 'Happy' 5 +33152 'Harry' 5 +33153 'Heart' 5 +33154 'Heavy' 5 +33155 'Hello' 5 +33156 'Henry' 5 +33157 'Hotel' 5 +33158 'Hours' 5 +33159 'House' 5 +33160 'Hover' 5 +33161 'Human' 5 +33162 'Hydro' 5 +33163 'Hyper' 5 +33164 'IDDEN' 5 +33165 'IDDLE' 5 +33166 'IDENT' 5 +33167 'IFIED' 5 +33168 'ILITY' 5 +33169 'IMAGE' 5 +33170 'IMARY' 5 +33171 'INDEX' 5 +33172 'INESS' 5 +33173 'INPUT' 5 +33174 'INTER' 5 +33175 'ISHED' 5 +33176 'ISING' 5 +33177 'ISION' 5 +33178 'ISTER' 5 +33179 'ITIES' 5 +33180 'ITION' 5 +33181 'IVATE' 5 +33182 'IVERS' 5 +33183 'Icons' 5 +33184 'Ident' 5 +33185 'Image' 5 +33186 'Impro' 5 +33187 'Incre' 5 +33188 'Index' 5 +33189 'India' 5 +33190 'Infos' 5 +33191 'Inner' 5 +33192 'Input' 5 +33193 'Instr' 5 +33194 'Intel' 5 +33195 'Inter' 5 +33196 'Intro' 5 +33197 'Islam' 5 +33198 'Issue' 5 +33199 'Items' 5 +33200 'Jacob' 5 +33201 'James' 5 +33202 'Japan' 5 +33203 'Jason' 5 +33204 'Jesus' 5 +33205 'Jimmy' 5 +33206 'Joint' 5 +33207 'Jones' 5 +33208 'Judge' 5 +33209 'KNOWN' 5 +33210 'Kelly' 5 +33211 'Kevin' 5 +33212 'Known' 5 +33213 'Krist' 5 +33214 'LABEL' 5 +33215 'LEASE' 5 +33216 'LEVEL' 5 +33217 'LIGHT' 5 +33218 'LIMIT' 5 +33219 'LOBAL' 5 +33220 'LOCAL' 5 +33221 'LOGIN' 5 +33222 'Label' 5 +33223 'Labor' 5 +33224 'Large' 5 +33225 'Later' 5 +33226 'Latin' 5 +33227 'Laura' 5 +33228 'Layer' 5 +33229 'Leaks' 5 +33230 'Learn' 5 +33231 'Leave' 5 +33232 'Legal' 5 +33233 'Lemma' 5 +33234 'Level' 5 +33235 'Lewis' 5 +33236 'Lexer' 5 +33237 'Light' 5 +33238 'Limit' 5 +33239 'Lines' 5 +33240 'Links' 5 +33241 'Linux' 5 +33242 'Lists' 5 +33243 'Liter' 5 +33244 'Local' 5 +33245 'Logic' 5 +33246 'Login' 5 +33247 'Looks' 5 +33248 'Louis' 5 +33249 'Lower' 5 +33250 'MATCH' 5 +33251 'MENTS' 5 +33252 'MODEL' 5 +33253 'MONTH' 5 +33254 'Macro' 5 +33255 'Magic' 5 +33256 'Major' 5 +33257 'Maker' 5 +33258 'March' 5 +33259 'Marco' 5 +33260 'Maria' 5 +33261 'Marie' 5 +33262 'Mario' 5 +33263 'Match' 5 +33264 'Maybe' 5 +33265 'Mayor' 5 +33266 'Means' 5 +33267 'Media' 5 +33268 'Merge' 5 +33269 'Metal' 5 +33270 'Meter' 5 +33271 'Miami' 5 +33272 'Micro' 5 +33273 'Minor' 5 +33274 'Mixed' 5 +33275 'Mixin' 5 +33276 'Modal' 5 +33277 'Model' 5 +33278 'Modes' 5 +33279 'Money' 5 +33280 'Mongo' 5 +33281 'Month' 5 +33282 'Motor' 5 +33283 'Mount' 5 +33284 'Mouse' 5 +33285 'Movie' 5 +33286 'Multi' 5 +33287 'Music' 5 +33288 'MySQL' 5 +33289 'Named' 5 +33290 'Names' 5 +33291 'Neill' 5 +33292 'Never' 5 +33293 'Night' 5 +33294 'Nodes' 5 +33295 'Noise' 5 +33296 'North' 5 +33297 'Notes' 5 +33298 'Numer' 5 +33299 'OAuth' 5 +33300 'ODULE' 5 +33301 'ORDER' 5 +33302 'ORMAL' 5 +33303 'OTHER' 5 +33304 'OURCE' 5 +33305 'Obama' 5 +33306 'Occup' 5 +33307 'Offer' 5 +33308 'Olymp' 5 +33309 'Omega' 5 +33310 'Optim' 5 +33311 'Order' 5 +33312 'Organ' 5 +33313 'Other' 5 +33314 'Outer' 5 +33315 'Owner' 5 +33316 'PARAM' 5 +33317 'PATCH' 5 +33318 'PLIED' 5 +33319 'POINT' 5 +33320 'PRESS' 5 +33321 'PRINT' 5 +33322 'PROTO' 5 +33323 'Pager' 5 +33324 'Pages' 5 +33325 'Paint' 5 +33326 'Panel' 5 +33327 'Paper' 5 +33328 'Param' 5 +33329 'Paris' 5 +33330 'Parse' 5 +33331 'Parts' 5 +33332 'Party' 5 +33333 'Paste' 5 +33334 'Patch' 5 +33335 'Paths' 5 +33336 'Pause' 5 +33337 'Peter' 5 +33338 'Phase' 5 +33339 'Phone' 5 +33340 'Photo' 5 +33341 'Piece' 5 +33342 'Pitch' 5 +33343 'Pixel' 5 +33344 'Place' 5 +33345 'Plain' 5 +33346 'Plane' 5 +33347 'Plant' 5 +33348 'Plate' 5 +33349 'Point' 5 +33350 'Polit' 5 +33351 'Popup' 5 +33352 'Posts' 5 +33353 'Power' 5 +33354 'Press' 5 +33355 'Price' 5 +33356 'Prime' 5 +33357 'Print' 5 +33358 'Prior' 5 +33359 'Probe' 5 +33360 'Produ' 5 +33361 'Proof' 5 +33362 'Props' 5 +33363 'Proto' 5 +33364 'Proxy' 5 +33365 'Psych' 5 +33366 'QUERY' 5 +33367 'QUEST' 5 +33368 'Quant' 5 +33369 'Queen' 5 +33370 'Query' 5 +33371 'Quest' 5 +33372 'Queue' 5 +33373 'Quick' 5 +33374 'Quote' 5 +33375 'READY' 5 +33376 'REATE' 5 +33377 'RESET' 5 +33378 'RIGHT' 5 +33379 'ROUND' 5 +33380 'Radio' 5 +33381 'Raise' 5 +33382 'Range' 5 +33383 'Ratio' 5 +33384 'React' 5 +33385 'Ready' 5 +33386 'Refer' 5 +33387 'Regex' 5 +33388 'Reply' 5 +33389 'Reset' 5 +33390 'Retry' 5 +33391 'Right' 5 +33392 'River' 5 +33393 'Robin' 5 +33394 'Robot' 5 +33395 'Roger' 5 +33396 'Roles' 5 +33397 'Roman' 5 +33398 'Round' 5 +33399 'Route' 5 +33400 'Royal' 5 +33401 'Rules' 5 +33402 'SHIFT' 5 +33403 'SHORT' 5 +33404 'SPACE' 5 +33405 'SSION' 5 +33406 'STAND' 5 +33407 'START' 5 +33408 'STATE' 5 +33409 'STORE' 5 +33410 'STYLE' 5 +33411 'Saint' 5 +33412 'Sales' 5 +33413 'Santa' 5 +33414 'Sarah' 5 +33415 'Saved' 5 +33416 'Scale' 5 +33417 'Scene' 5 +33418 'Sched' 5 +33419 'Scope' 5 +33420 'Score' 5 +33421 'Scott' 5 +33422 'Sense' 5 +33423 'Separ' 5 +33424 'Setup' 5 +33425 'Seven' 5 +33426 'Shape' 5 +33427 'Share' 5 +33428 'Sharp' 5 +33429 'Sheet' 5 +33430 'Shell' 5 +33431 'Shift' 5 +33432 'Short' 5 +33433 'Sigma' 5 +33434 'Simon' 5 +33435 'Since' 5 +33436 'Sizer' 5 +33437 'Skill' 5 +33438 'Sleep' 5 +33439 'Slice' 5 +33440 'Slide' 5 +33441 'Small' 5 +33442 'Smart' 5 +33443 'Smith' 5 +33444 'Solar' 5 +33445 'Solid' 5 +33446 'Songs' 5 +33447 'Sorry' 5 +33448 'Sound' 5 +33449 'South' 5 +33450 'Space' 5 +33451 'Spain' 5 +33452 'Spark' 5 +33453 'Spawn' 5 +33454 'Spect' 5 +33455 'Speed' 5 +33456 'Spell' 5 +33457 'Split' 5 +33458 'Sport' 5 +33459 'Stack' 5 +33460 'Staff' 5 +33461 'Stage' 5 +33462 'Stamp' 5 +33463 'Stand' 5 +33464 'Stars' 5 +33465 'Start' 5 +33466 'State' 5 +33467 'Stats' 5 +33468 'Steps' 5 +33469 'Steve' 5 +33470 'Still' 5 +33471 'Stock' 5 +33472 'Stone' 5 +33473 'Store' 5 +33474 'Storm' 5 +33475 'Story' 5 +33476 'Strip' 5 +33477 'Study' 5 +33478 'Style' 5 +33479 'Suite' 5 +33480 'Super' 5 +33481 'Susan' 5 +33482 'Sweet' 5 +33483 'Swift' 5 +33484 'TABLE' 5 +33485 'TEGER' 5 +33486 'TITLE' 5 +33487 'TOKEN' 5 +33488 'TRACE' 5 +33489 'TRACK' 5 +33490 'TRACT' 5 +33491 'TRAIN' 5 +33492 'TRANS' 5 +33493 'TYPES' 5 +33494 'Table' 5 +33495 'Taken' 5 +33496 'Tasks' 5 +33497 'Techn' 5 +33498 'Terms' 5 +33499 'Tests' 5 +33500 'Texas' 5 +33501 'Thank' 5 +33502 'Their' 5 +33503 'Theme' 5 +33504 'There' 5 +33505 'These' 5 +33506 'Theta' 5 +33507 'Thing' 5 +33508 'Think' 5 +33509 'Third' 5 +33510 'Those' 5 +33511 'Three' 5 +33512 'Throw' 5 +33513 'Thumb' 5 +33514 'Thêm' 5 +33515 'Tiles' 5 +33516 'Timer' 5 +33517 'Times' 5 +33518 'Title' 5 +33519 'ToOne' 5 +33520 'Today' 5 +33521 'Token' 5 +33522 'Tools' 5 +33523 'Topic' 5 +33524 'Total' 5 +33525 'Touch' 5 +33526 'Trace' 5 +33527 'Track' 5 +33528 'Trade' 5 +33529 'Train' 5 +33530 'Trait' 5 +33531 'Trans' 5 +33532 'Trial' 5 +33533 'Trump' 5 +33534 'Trust' 5 +33535 'Truth' 5 +33536 'Tuple' 5 +33537 'Tweet' 5 +33538 'Typed' 5 +33539 'Types' 5 +33540 'UMENT' 5 +33541 'USTOM' 5 +33542 'UTERS' 5 +33543 'UTION' 5 +33544 'Unary' 5 +33545 'Under' 5 +33546 'Union' 5 +33547 'Units' 5 +33548 'Unity' 5 +33549 'Until' 5 +33550 'Upper' 5 +33551 'Urban' 5 +33552 'Usage' 5 +33553 'Users' 5 +33554 'Using' 5 +33555 'Utils' 5 +33556 'VALID' 5 +33557 'VALUE' 5 +33558 'VIDEO' 5 +33559 'VIDIA' 5 +33560 'Valid' 5 +33561 'Valor' 5 +33562 'Value' 5 +33563 'Video' 5 +33564 'Views' 5 +33565 'Visit' 5 +33566 'Você' 5 +33567 'Voice' 5 +33568 'WHERE' 5 +33569 'WHITE' 5 +33570 'WIDTH' 5 +33571 'WRITE' 5 +33572 'Watch' 5 +33573 'Water' 5 +33574 'Wheel' 5 +33575 'Where' 5 +33576 'Which' 5 +33577 'While' 5 +33578 'White' 5 +33579 'Whole' 5 +33580 'Width' 5 +33581 'Women' 5 +33582 'Words' 5 +33583 'Works' 5 +33584 'World' 5 +33585 'Would' 5 +33586 'Write' 5 +33587 'Years' 5 +33588 'Young' 5 +33589 '[:,:,' 5 +33590 '[…]' 5 +33591 '\\":\\"' 5 +33592 '^−^' 5 +33593 'abama' 5 +33594 'abase' 5 +33595 'abbit' 5 +33596 'abeth' 5 +33597 'abled' 5 +33598 'ables' 5 +33599 'abort' 5 +33600 'about' 5 +33601 'above' 5 +33602 'abric' 5 +33603 'accum' 5 +33604 'accur' 5 +33605 'aceae' 5 +33606 'acent' 5 +33607 'acerb' 5 +33608 'aceut' 5 +33609 'ached' 5 +33610 'achel' 5 +33611 'achen' 5 +33612 'acher' 5 +33613 'aches' 5 +33614 'acial' 5 +33615 'acies' 5 +33616 'acing' 5 +33617 'acion' 5 +33618 'acity' 5 +33619 'ació' 5 +33620 'ację' 5 +33621 'acked' 5 +33622 'acker' 5 +33623 'acket' 5 +33624 'acles' 5 +33625 'acons' 5 +33626 'acted' 5 +33627 'acter' 5 +33628 'actic' 5 +33629 'activ' 5 +33630 'actly' 5 +33631 'actor' 5 +33632 'actus' 5 +33633 'acute' 5 +33634 'adapt' 5 +33635 'adata' 5 +33636 'adays' 5 +33637 'addTo' 5 +33638 'added' 5 +33639 'adder' 5 +33640 'addle' 5 +33641 'addon' 5 +33642 'adena' 5 +33643 'adeon' 5 +33644 'adequ' 5 +33645 'aders' 5 +33646 'adesh' 5 +33647 'adian' 5 +33648 'adier' 5 +33649 'adies' 5 +33650 'ading' 5 +33651 'adium' 5 +33652 'admin' 5 +33653 'adoop' 5 +33654 'adora' 5 +33655 'adors' 5 +33656 'adows' 5 +33657 'adult' 5 +33658 'adém' 5 +33659 'afety' 5 +33660 'affer' 5 +33661 'after' 5 +33662 'again' 5 +33663 'agara' 5 +33664 'agens' 5 +33665 'agent' 5 +33666 'agers' 5 +33667 'agged' 5 +33668 'agger' 5 +33669 'aggio' 5 +33670 'agher' 5 +33671 'agine' 5 +33672 'aging' 5 +33673 'agles' 5 +33674 'agner' 5 +33675 'agnet' 5 +33676 'agram' 5 +33677 'agree' 5 +33678 'agrid' 5 +33679 'agues' 5 +33680 'ahead' 5 +33681 'ahoma' 5 +33682 'ahren' 5 +33683 'aient' 5 +33684 'ailed' 5 +33685 'aille' 5 +33686 'ained' 5 +33687 'ainen' 5 +33688 'ainer' 5 +33689 'aines' 5 +33690 'aired' 5 +33691 'aires' 5 +33692 'aiser' 5 +33693 'aises' 5 +33694 'aison' 5 +33695 'ając' 5 +33696 'akers' 5 +33697 'aking' 5 +33698 'akter' 5 +33699 'aland' 5 +33700 'alarm' 5 +33701 'album' 5 +33702 'alert' 5 +33703 'ależ' 5 +33704 'algia' 5 +33705 'alian' 5 +33706 'alias' 5 +33707 'alice' 5 +33708 'alien' 5 +33709 'align' 5 +33710 'aline' 5 +33711 'aling' 5 +33712 'alion' 5 +33713 'alist' 5 +33714 'ality' 5 +33715 'alive' 5 +33716 'alkyl' 5 +33717 'allah' 5 +33718 'allas' 5 +33719 'alled' 5 +33720 'allel' 5 +33721 'allen' 5 +33722 'aller' 5 +33723 'alles' 5 +33724 'allet' 5 +33725 'allic' 5 +33726 'alloc' 5 +33727 'allow' 5 +33728 'alone' 5 +33729 'along' 5 +33730 'alore' 5 +33731 'alous' 5 +33732 'alpha' 5 +33733 'alter' 5 +33734 'amate' 5 +33735 'ambda' 5 +33736 'amber' 5 +33737 'ambia' 5 +33738 'ambig' 5 +33739 'amble' 5 +33740 'amboo' 5 +33741 'ament' 5 +33742 'amera' 5 +33743 'amide' 5 +33744 'amily' 5 +33745 'amina' 5 +33746 'amine' 5 +33747 'aming' 5 +33748 'amino' 5 +33749 'amins' 5 +33750 'ammad' 5 +33751 'ammed' 5 +33752 'ammer' 5 +33753 'among' 5 +33754 'amoto' 5 +33755 'amour' 5 +33756 'amous' 5 +33757 'amped' 5 +33758 'ample' 5 +33759 'amura' 5 +33760 'analy' 5 +33761 'anced' 5 +33762 'ancel' 5 +33763 'ancer' 5 +33764 'ances' 5 +33765 'anche' 5 +33766 'ancia' 5 +33767 'andal' 5 +33768 'andan' 5 +33769 'andas' 5 +33770 'anded' 5 +33771 'andel' 5 +33772 'anden' 5 +33773 'ander' 5 +33774 'andez' 5 +33775 'andid' 5 +33776 'andin' 5 +33777 'andle' 5 +33778 'andom' 5 +33779 'andon' 5 +33780 'andra' 5 +33781 'andre' 5 +33782 'andro' 5 +33783 'andum' 5 +33784 'anean' 5 +33785 'anese' 5 +33786 'angan' 5 +33787 'anged' 5 +33788 'angel' 5 +33789 'angen' 5 +33790 'anger' 5 +33791 'anges' 5 +33792 'angle' 5 +33793 'anian' 5 +33794 'anine' 5 +33795 'aning' 5 +33796 'anish' 5 +33797 'anity' 5 +33798 'anium' 5 +33799 'anked' 5 +33800 'anmar' 5 +33801 'annah' 5 +33802 'anned' 5 +33803 'annel' 5 +33804 'anner' 5 +33805 'annes' 5 +33806 'annie' 5 +33807 'annon' 5 +33808 'annot' 5 +33809 'anova' 5 +33810 'ansas' 5 +33811 'ansen' 5 +33812 'ansom' 5 +33813 'anson' 5 +33814 'antal' 5 +33815 'antan' 5 +33816 'anted' 5 +33817 'anten' 5 +33818 'anter' 5 +33819 'antes' 5 +33820 'antha' 5 +33821 'antic' 5 +33822 'antis' 5 +33823 'antly' 5 +33824 'antom' 5 +33825 'anton' 5 +33826 'antry' 5 +33827 'anuts' 5 +33828 'anyon' 5 +33829 'ança' 5 +33830 'apers' 5 +33831 'apest' 5 +33832 'apeut' 5 +33833 'aping' 5 +33834 'apons' 5 +33835 'apore' 5 +33836 'apped' 5 +33837 'appen' 5 +33838 'apper' 5 +33839 'apple' 5 +33840 'apply' 5 +33841 'appro' 5 +33842 'apsed' 5 +33843 'apses' 5 +33844 'apter' 5 +33845 'aptic' 5 +33846 'aptop' 5 +33847 'arant' 5 +33848 'archy' 5 +33849 'arded' 5 +33850 'arden' 5 +33851 'ardin' 5 +33852 'ardon' 5 +33853 'areas' 5 +33854 'arena' 5 +33855 'arent' 5 +33856 'arest' 5 +33857 'areth' 5 +33858 'argar' 5 +33859 'arger' 5 +33860 'arget' 5 +33861 'argin' 5 +33862 'argon' 5 +33863 'arial' 5 +33864 'arian' 5 +33865 'arias' 5 +33866 'ariat' 5 +33867 'aries' 5 +33868 'arily' 5 +33869 'arine' 5 +33870 'aring' 5 +33871 'arios' 5 +33872 'arith' 5 +33873 'arity' 5 +33874 'arium' 5 +33875 'arius' 5 +33876 'arked' 5 +33877 'arker' 5 +33878 'armac' 5 +33879 'armed' 5 +33880 'armor' 5 +33881 'array' 5 +33882 'arrow' 5 +33883 'arser' 5 +33884 'arten' 5 +33885 'arter' 5 +33886 'arthy' 5 +33887 'artic' 5 +33888 'arton' 5 +33889 'arxiv' 5 +33890 'aría' 5 +33891 'asaki' 5 +33892 'asant' 5 +33893 'ascal' 5 +33894 'ascii' 5 +33895 'ascus' 5 +33896 'asers' 5 +33897 'ashed' 5 +33898 'ashes' 5 +33899 'asian' 5 +33900 'aside' 5 +33901 'asing' 5 +33902 'asion' 5 +33903 'asive' 5 +33904 'asket' 5 +33905 'asons' 5 +33906 'asper' 5 +33907 'assed' 5 +33908 'assen' 5 +33909 'asser' 5 +33910 'asses' 5 +33911 'asset' 5 +33912 'assic' 5 +33913 'assin' 5 +33914 'assis' 5 +33915 'assoc' 5 +33916 'asted' 5 +33917 'aster' 5 +33918 'astes' 5 +33919 'astic' 5 +33920 'aston' 5 +33921 'astro' 5 +33922 'asure' 5 +33923 'asury' 5 +33924 'async' 5 +33925 'ataka' 5 +33926 'atche' 5 +33927 'ategy' 5 +33928 'ately' 5 +33929 'atern' 5 +33930 'aters' 5 +33931 'atest' 5 +33932 'ateur' 5 +33933 'atham' 5 +33934 'athan' 5 +33935 'athed' 5 +33936 'ather' 5 +33937 'athom' 5 +33938 'athon' 5 +33939 'atial' 5 +33940 'atica' 5 +33941 'atics' 5 +33942 'atile' 5 +33943 'ating' 5 +33944 'ation' 5 +33945 'atisf' 5 +33946 'atism' 5 +33947 'ativa' 5 +33948 'ative' 5 +33949 'ativo' 5 +33950 'atoes' 5 +33951 'atoms' 5 +33952 'atomy' 5 +33953 'atore' 5 +33954 'atori' 5 +33955 'ators' 5 +33956 'atory' 5 +33957 'atrix' 5 +33958 'atted' 5 +33959 'atten' 5 +33960 'atter' 5 +33961 'attle' 5 +33962 'attrs' 5 +33963 'atura' 5 +33964 'ature' 5 +33965 'atype' 5 +33966 'atég' 5 +33967 'audio' 5 +33968 'audit' 5 +33969 'aught' 5 +33970 'aukee' 5 +33971 'aurus' 5 +33972 'ausal' 5 +33973 'aused' 5 +33974 'auses' 5 +33975 'autom' 5 +33976 'autor' 5 +33977 'autos' 5 +33978 'autre' 5 +33979 'auté' 5 +33980 'avage' 5 +33981 'avail' 5 +33982 'avery' 5 +33983 'avian' 5 +33984 'avier' 5 +33985 'aving' 5 +33986 'avoid' 5 +33987 'avoir' 5 +33988 'avors' 5 +33989 'avour' 5 +33990 'await' 5 +33991 'award' 5 +33992 'aware' 5 +33993 'aways' 5 +33994 'axter' 5 +33995 'ayers' 5 +33996 'aying' 5 +33997 'aylor' 5 +33998 'ayout' 5 +33999 'azard' 5 +34000 'azine' 5 +34001 'azing' 5 +34002 'azole' 5 +34003 'azure' 5 +34004 'babel' 5 +34005 'bably' 5 +34006 'backs' 5 +34007 'badge' 5 +34008 'balls' 5 +34009 'bands' 5 +34010 'banks' 5 +34011 'based' 5 +34012 'basic' 5 +34013 'basis' 5 +34014 'batch' 5 +34015 'beans' 5 +34016 'becca' 5 +34017 'becue' 5 +34018 'begin' 5 +34019 'being' 5 +34020 'below' 5 +34021 'bench' 5 +34022 'benef' 5 +34023 'beros' 5 +34024 'berra' 5 +34025 'berry' 5 +34026 'berta' 5 +34027 'berto' 5 +34028 'binom' 5 +34029 'birds' 5 +34030 'birth' 5 +34031 'bject' 5 +34032 'black' 5 +34033 'blade' 5 +34034 'blank' 5 +34035 'blast' 5 +34036 'blems' 5 +34037 'blind' 5 +34038 'bling' 5 +34039 'block' 5 +34040 'blogs' 5 +34041 'blood' 5 +34042 'boBox' 5 +34043 'board' 5 +34044 'bones' 5 +34045 'books' 5 +34046 'boost' 5 +34047 'borne' 5 +34048 'bound' 5 +34049 'bourg' 5 +34050 'boxes' 5 +34051 'brace' 5 +34052 'brain' 5 +34053 'brand' 5 +34054 'brane' 5 +34055 'bread' 5 +34056 'break' 5 +34057 'brevi' 5 +34058 'brief' 5 +34059 'bring' 5 +34060 'broad' 5 +34061 'brook' 5 +34062 'brown' 5 +34063 'brush' 5 +34064 'bráz' 5 +34065 'bsite' 5 +34066 'bucks' 5 +34067 'build' 5 +34068 'built' 5 +34069 'buntu' 5 +34070 'burgh' 5 +34071 'burst' 5 +34072 'byter' 5 +34073 'bytes' 5 +34074 'cache' 5 +34075 'caffe' 5 +34076 'calls' 5 +34077 'camel' 5 +34078 'cards' 5 +34079 'caret' 5 +34080 'carry' 5 +34081 'cases' 5 +34082 'casts' 5 +34083 'catal' 5 +34084 'catch' 5 +34085 'cause' 5 +34086 'ccess' 5 +34087 'ccion' 5 +34088 'cció' 5 +34089 'ccoli' 5 +34090 'cdnjs' 5 +34091 'cdots' 5 +34092 'ceans' 5 +34093 'cedes' 5 +34094 'ceive' 5 +34095 'cells' 5 +34096 'cence' 5 +34097 'cents' 5 +34098 'cerpt' 5 +34099 'cesso' 5 +34100 'chaft' 5 +34101 'chain' 5 +34102 'chair' 5 +34103 'chang' 5 +34104 'chant' 5 +34105 'charg' 5 +34106 'chars' 5 +34107 'chart' 5 +34108 'check' 5 +34109 'chell' 5 +34110 'chemy' 5 +34111 'cheon' 5 +34112 'chers' 5 +34113 'chest' 5 +34114 'chief' 5 +34115 'child' 5 +34116 'ching' 5 +34117 'chini' 5 +34118 'chlor' 5 +34119 'chool' 5 +34120 'chrom' 5 +34121 'chron' 5 +34122 'chten' 5 +34123 'chter' 5 +34124 'chunk' 5 +34125 'cible' 5 +34126 'cient' 5 +34127 'civil' 5 +34128 'ción' 5 +34129 'cknow' 5 +34130 'ckså' 5 +34131 'claim' 5 +34132 'clair' 5 +34133 'clamp' 5 +34134 'clang' 5 +34135 'class' 5 +34136 'clave' 5 +34137 'clean' 5 +34138 'clear' 5 +34139 'click' 5 +34140 'cline' 5 +34141 'cling' 5 +34142 'clock' 5 +34143 'clone' 5 +34144 'close' 5 +34145 'cloth' 5 +34146 'cloud' 5 +34147 'clude' 5 +34148 'clust' 5 +34149 'coach' 5 +34150 'codec' 5 +34151 'coded' 5 +34152 'coder' 5 +34153 'codes' 5 +34154 'coeff' 5 +34155 'cohol' 5 +34156 'coins' 5 +34157 'colon' 5 +34158 'color' 5 +34159 'combe' 5 +34160 'combo' 5 +34161 'comed' 5 +34162 'comes' 5 +34163 'comic' 5 +34164 'comma' 5 +34165 'compl' 5 +34166 'conda' 5 +34167 'conde' 5 +34168 'conom' 5 +34169 'const' 5 +34170 'contr' 5 +34171 'coord' 5 +34172 'cores' 5 +34173 'could' 5 +34174 'count' 5 +34175 'court' 5 +34176 'cover' 5 +34177 'craft' 5 +34178 'crawl' 5 +34179 'creat' 5 +34180 'creen' 5 +34181 'crete' 5 +34182 'crets' 5 +34183 'cribe' 5 +34184 'crime' 5 +34185 'cript' 5 +34186 'crire' 5 +34187 'croft' 5 +34188 'cross' 5 +34189 'crypt' 5 +34190 'ctica' 5 +34191 'ction' 5 +34192 'ctors' 5 +34193 'ctype' 5 +34194 'cubic' 5 +34195 'cular' 5 +34196 'cules' 5 +34197 'culos' 5 +34198 'culus' 5 +34199 'curve' 5 +34200 'cycle' 5 +34201 'daily' 5 +34202 'datab' 5 +34203 'datas' 5 +34204 'datat' 5 +34205 'dated' 5 +34206 'dater' 5 +34207 'dates' 5 +34208 'datum' 5 +34209 'death' 5 +34210 'debug' 5 +34211 'decay' 5 +34212 'decor' 5 +34213 'defer' 5 +34214 'defin' 5 +34215 'delay' 5 +34216 'deleg' 5 +34217 'delta' 5 +34218 'denly' 5 +34219 'dense' 5 +34220 'depth' 5 +34221 'deque' 5 +34222 'deriv' 5 +34223 'descr' 5 +34224 'devel' 5 +34225 'dfrac' 5 +34226 'digit' 5 +34227 'dimen' 5 +34228 'dings' 5 +34229 'dirty' 5 +34230 'doesn' 5 +34231 'doing' 5 +34232 'domin' 5 +34233 'doors' 5 +34234 'draft' 5 +34235 'dream' 5 +34236 'drive' 5 +34237 'dtype' 5 +34238 'duced' 5 +34239 'ducer' 5 +34240 'duino' 5 +34241 'dummy' 5 +34242 'earch' 5 +34243 'early' 5 +34244 'earth' 5 +34245 'ebook' 5 +34246 'ecess' 5 +34247 'ectar' 5 +34248 'ected' 5 +34249 'ector' 5 +34250 'edges' 5 +34251 'eding' 5 +34252 'eenth' 5 +34253 'eeper' 5 +34254 'efore' 5 +34255 'eigen' 5 +34256 'eight' 5 +34257 'eking' 5 +34258 'eland' 5 +34259 'elect' 5 +34260 'eless' 5 +34261 'elfth' 5 +34262 'elian' 5 +34263 'elijk' 5 +34264 'eline' 5 +34265 'eling' 5 +34266 'elist' 5 +34267 'elius' 5 +34268 'ellan' 5 +34269 'ellar' 5 +34270 'elled' 5 +34271 'ellen' 5 +34272 'eller' 5 +34273 'elles' 5 +34274 'ellig' 5 +34275 'ellij' 5 +34276 'ellow' 5 +34277 'elman' 5 +34278 'elong' 5 +34279 'elope' 5 +34280 'elsen' 5 +34281 'elson' 5 +34282 'elter' 5 +34283 'elves' 5 +34284 'email' 5 +34285 'emale' 5 +34286 'emann' 5 +34287 'emark' 5 +34288 'embed' 5 +34289 'ember' 5 +34290 'emble' 5 +34291 'embre' 5 +34292 'embro' 5 +34293 'ement' 5 +34294 'emies' 5 +34295 'emoji' 5 +34296 'emory' 5 +34297 'emplo' 5 +34298 'empor' 5 +34299 'empre' 5 +34300 'empty' 5 +34301 'emás' 5 +34302 'ename' 5 +34303 'enant' 5 +34304 'enary' 5 +34305 'enced' 5 +34306 'encer' 5 +34307 'ences' 5 +34308 'encia' 5 +34309 'encil' 5 +34310 'endar' 5 +34311 'endas' 5 +34312 'ended' 5 +34313 'enden' 5 +34314 'ender' 5 +34315 'endez' 5 +34316 'endif' 5 +34317 'endix' 5 +34318 'endor' 5 +34319 'endra' 5 +34320 'endum' 5 +34321 'eners' 5 +34322 'enery' 5 +34323 'eness' 5 +34324 'enger' 5 +34325 'ength' 5 +34326 'ening' 5 +34327 'enium' 5 +34328 'ennen' 5 +34329 'ennes' 5 +34330 'ennis' 5 +34331 'ensch' 5 +34332 'ensed' 5 +34333 'ensen' 5 +34334 'enser' 5 +34335 'enses' 5 +34336 'ensis' 5 +34337 'enson' 5 +34338 'ensor' 5 +34339 'ensus' 5 +34340 'ental' 5 +34341 'ented' 5 +34342 'enter' 5 +34343 'entes' 5 +34344 'entic' 5 +34345 'entin' 5 +34346 'ently' 5 +34347 'enton' 5 +34348 'entre' 5 +34349 'entry' 5 +34350 'enzie' 5 +34351 'ença' 5 +34352 'epend' 5 +34353 'eping' 5 +34354 'epoch' 5 +34355 'equal' 5 +34356 'equip' 5 +34357 'equiv' 5 +34358 'erala' 5 +34359 'erald' 5 +34360 'erals' 5 +34361 'erase' 5 +34362 'erate' 5 +34363 'ereum' 5 +34364 'ergic' 5 +34365 'ergus' 5 +34366 'erial' 5 +34367 'eries' 5 +34368 'ering' 5 +34369 'erior' 5 +34370 'ermal' 5 +34371 'erman' 5 +34372 'ernal' 5 +34373 'ernel' 5 +34374 'erner' 5 +34375 'errno' 5 +34376 'error' 5 +34377 'ersen' 5 +34378 'erset' 5 +34379 'erson' 5 +34380 'erten' 5 +34381 'erton' 5 +34382 'erved' 5 +34383 'erver' 5 +34384 'erves' 5 +34385 'esian' 5 +34386 'esity' 5 +34387 'esium' 5 +34388 'esome' 5 +34389 'espan' 5 +34390 'esper' 5 +34391 'essed' 5 +34392 'essel' 5 +34393 'essen' 5 +34394 'esser' 5 +34395 'esses' 5 +34396 'essim' 5 +34397 'essor' 5 +34398 'ested' 5 +34399 'ester' 5 +34400 'estic' 5 +34401 'estim' 5 +34402 'eston' 5 +34403 'estre' 5 +34404 'estro' 5 +34405 'etary' 5 +34406 'eteor' 5 +34407 'eters' 5 +34408 'ether' 5 +34409 'ethod' 5 +34410 'ethyl' 5 +34411 'etics' 5 +34412 'eties' 5 +34413 'etime' 5 +34414 'etine' 5 +34415 'eting' 5 +34416 'etric' 5 +34417 'ettel' 5 +34418 'etter' 5 +34419 'ettes' 5 +34420 'ettle' 5 +34421 'etype' 5 +34422 'evalu' 5 +34423 'event' 5 +34424 'every' 5 +34425 'ewnę' 5 +34426 'exact' 5 +34427 'excel' 5 +34428 'exist' 5 +34429 'exper' 5 +34430 'explo' 5 +34431 'extra' 5 +34432 'faces' 5 +34433 'facts' 5 +34434 'faith' 5 +34435 'falls' 5 +34436 'false' 5 +34437 'fasta' 5 +34438 'fatal' 5 +34439 'fault' 5 +34440 'favor' 5 +34441 'fetch' 5 +34442 'ffect' 5 +34443 'ffiti' 5 +34444 'ffset' 5 +34445 'fiber' 5 +34446 'field' 5 +34447 'fight' 5 +34448 'filer' 5 +34449 'files' 5 +34450 'filtr' 5 +34451 'final' 5 +34452 'fires' 5 +34453 'first' 5 +34454 'fixed' 5 +34455 'flags' 5 +34456 'flake' 5 +34457 'flare' 5 +34458 'flash' 5 +34459 'flies' 5 +34460 'float' 5 +34461 'floor' 5 +34462 'flows' 5 +34463 'fluid' 5 +34464 'fluor' 5 +34465 'flush' 5 +34466 'fname' 5 +34467 'focus' 5 +34468 'folio' 5 +34469 'fonts' 5 +34470 'force' 5 +34471 'forge' 5 +34472 'forma' 5 +34473 'forme' 5 +34474 'forms' 5 +34475 'forth' 5 +34476 'forum' 5 +34477 'found' 5 +34478 'frame' 5 +34479 'fresh' 5 +34480 'frica' 5 +34481 'fried' 5 +34482 'front' 5 +34483 'fruit' 5 +34484 'ftime' 5 +34485 'ftype' 5 +34486 'fully' 5 +34487 'führ' 5 +34488 'gaard' 5 +34489 'gable' 5 +34490 'games' 5 +34491 'gamma' 5 +34492 'gauge' 5 +34493 'geant' 5 +34494 'geben' 5 +34495 'gebra' 5 +34496 'gence' 5 +34497 'gency' 5 +34498 'gende' 5 +34499 'gener' 5 +34500 'genes' 5 +34501 'genic' 5 +34502 'genre' 5 +34503 'geois' 5 +34504 'geons' 5 +34505 'gesch' 5 +34506 'getId' 5 +34507 'giene' 5 +34508 'given' 5 +34509 'glass' 5 +34510 'glyph' 5 +34511 'gmail' 5 +34512 'gment' 5 +34513 'goals' 5 +34514 'going' 5 +34515 'grade' 5 +34516 'grams' 5 +34517 'grand' 5 +34518 'grant' 5 +34519 'graph' 5 +34520 'grass' 5 +34521 'grave' 5 +34522 'great' 5 +34523 'green' 5 +34524 'gress' 5 +34525 'group' 5 +34526 'grown' 5 +34527 'grund' 5 +34528 'guard' 5 +34529 'guess' 5 +34530 'guest' 5 +34531 'guide' 5 +34532 'guild' 5 +34533 'gunta' 5 +34534 'habit' 5 +34535 'hagen' 5 +34536 'hands' 5 +34537 'happy' 5 +34538 'hardt' 5 +34539 'harma' 5 +34540 'ható' 5 +34541 'haust' 5 +34542 'haven' 5 +34543 'heads' 5 +34544 'heard' 5 +34545 'heart' 5 +34546 'heast' 5 +34547 'heavy' 5 +34548 'heets' 5 +34549 'heits' 5 +34550 'hello' 5 +34551 'hemat' 5 +34552 'hemer' 5 +34553 'henyl' 5 +34554 'heres' 5 +34555 'herty' 5 +34556 'heses' 5 +34557 'hesia' 5 +34558 'hesis' 5 +34559 'heter' 5 +34560 'hetic' 5 +34561 'hetti' 5 +34562 'hetto' 5 +34563 'heure' 5 +34564 'hibit' 5 +34565 'hicle' 5 +34566 'hline' 5 +34567 'holds' 5 +34568 'holes' 5 +34569 'homme' 5 +34570 'hooks' 5 +34571 'hores' 5 +34572 'horse' 5 +34573 'hosts' 5 +34574 'hotel' 5 +34575 'hours' 5 +34576 'house' 5 +34577 'hover' 5 +34578 'hower' 5 +34579 'https' 5 +34580 'human' 5 +34581 'hurst' 5 +34582 'hydro' 5 +34583 'hyper' 5 +34584 'hält' 5 +34585 'häng' 5 +34586 'hões' 5 +34587 'iable' 5 +34588 'ially' 5 +34589 'ialog' 5 +34590 'iance' 5 +34591 'iasis' 5 +34592 'iated' 5 +34593 'iates' 5 +34594 'iator' 5 +34595 'iała' 5 +34596 'ibaba' 5 +34597 'ibile' 5 +34598 'ibles' 5 +34599 'iből' 5 +34600 'icago' 5 +34601 'icals' 5 +34602 'icana' 5 +34603 'icans' 5 +34604 'icate' 5 +34605 'ichen' 5 +34606 'icher' 5 +34607 'ichte' 5 +34608 'icial' 5 +34609 'ician' 5 +34610 'icide' 5 +34611 'icine' 5 +34612 'icing' 5 +34613 'icion' 5 +34614 'icios' 5 +34615 'icism' 5 +34616 'icity' 5 +34617 'ició' 5 +34618 'icked' 5 +34619 'icken' 5 +34620 'icker' 5 +34621 'icket' 5 +34622 'ická' 5 +34623 'ické' 5 +34624 'ický' 5 +34625 'icles' 5 +34626 'icode' 5 +34627 'icons' 5 +34628 'icted' 5 +34629 'ictor' 5 +34630 'icult' 5 +34631 'idade' 5 +34632 'idase' 5 +34633 'idata' 5 +34634 'idden' 5 +34635 'iddle' 5 +34636 'ideal' 5 +34637 'ident' 5 +34638 'ideos' 5 +34639 'iders' 5 +34640 'idget' 5 +34641 'idian' 5 +34642 'idine' 5 +34643 'iding' 5 +34644 'idity' 5 +34645 'idium' 5 +34646 'idual' 5 +34647 'idée' 5 +34648 'iedad' 5 +34649 'ieder' 5 +34650 'iegel' 5 +34651 'ielle' 5 +34652 'ience' 5 +34653 'iency' 5 +34654 'iendo' 5 +34655 'ienen' 5 +34656 'ienna' 5 +34657 'ienne' 5 +34658 'iente' 5 +34659 'iento' 5 +34660 'ients' 5 +34661 'ienza' 5 +34662 'ieren' 5 +34663 'ierno' 5 +34664 'ieron' 5 +34665 'ierra' 5 +34666 'ierre' 5 +34667 'ierte' 5 +34668 'ierto' 5 +34669 'iesel' 5 +34670 'iesen' 5 +34671 'ieurs' 5 +34672 'ieval' 5 +34673 'ieved' 5 +34674 'ieves' 5 +34675 'iface' 5 +34676 'ifact' 5 +34677 'ifdef' 5 +34678 'ifest' 5 +34679 'iffer' 5 +34680 'ifica' 5 +34681 'ifice' 5 +34682 'ified' 5 +34683 'ifier' 5 +34684 'ifies' 5 +34685 'ifié' 5 +34686 'ifold' 5 +34687 'iform' 5 +34688 'iforn' 5 +34689 'ifter' 5 +34690 'igate' 5 +34691 'igent' 5 +34692 'igest' 5 +34693 'igger' 5 +34694 'ighed' 5 +34695 'ighth' 5 +34696 'ights' 5 +34697 'igion' 5 +34698 'igmat' 5 +34699 'igned' 5 +34700 'igner' 5 +34701 'ignon' 5 +34702 'igram' 5 +34703 'igung' 5 +34704 'ijing' 5 +34705 'ikawa' 5 +34706 'ikers' 5 +34707 'iking' 5 +34708 'ilage' 5 +34709 'iland' 5 +34710 'ilder' 5 +34711 'ilent' 5 +34712 'ilers' 5 +34713 'ilian' 5 +34714 'iliar' 5 +34715 'ilies' 5 +34716 'iline' 5 +34717 'iling' 5 +34718 'ilion' 5 +34719 'ility' 5 +34720 'illac' 5 +34721 'illar' 5 +34722 'illas' 5 +34723 'illed' 5 +34724 'iller' 5 +34725 'illes' 5 +34726 'illet' 5 +34727 'illin' 5 +34728 'illon' 5 +34729 'illus' 5 +34730 'illé' 5 +34731 'ilogy' 5 +34732 'ilton' 5 +34733 'image' 5 +34734 'imals' 5 +34735 'imate' 5 +34736 'imens' 5 +34737 'iment' 5 +34738 'imgur' 5 +34739 'imits' 5 +34740 'imize' 5 +34741 'immer' 5 +34742 'imony' 5 +34743 'imore' 5 +34744 'imoto' 5 +34745 'imper' 5 +34746 'imple' 5 +34747 'impro' 5 +34748 'imuth' 5 +34749 'inals' 5 +34750 'iname' 5 +34751 'inand' 5 +34752 'inant' 5 +34753 'inary' 5 +34754 'inate' 5 +34755 'inces' 5 +34756 'incip' 5 +34757 'incre' 5 +34758 'inden' 5 +34759 'inder' 5 +34760 'index' 5 +34761 'indic' 5 +34762 'indle' 5 +34763 'indow' 5 +34764 'indre' 5 +34765 'inear' 5 +34766 'inees' 5 +34767 'inely' 5 +34768 'inent' 5 +34769 'iners' 5 +34770 'inery' 5 +34771 'inese' 5 +34772 'iness' 5 +34773 'infer' 5 +34774 'infra' 5 +34775 'infty' 5 +34776 'ingen' 5 +34777 'inger' 5 +34778 'inges' 5 +34779 'ingle' 5 +34780 'ingly' 5 +34781 'inian' 5 +34782 'ining' 5 +34783 'inion' 5 +34784 'inite' 5 +34785 'inity' 5 +34786 'inkel' 5 +34787 'inker' 5 +34788 'inkle' 5 +34789 'inned' 5 +34790 'innen' 5 +34791 'inner' 5 +34792 'inode' 5 +34793 'inois' 5 +34794 'inous' 5 +34795 'input' 5 +34796 'inset' 5 +34797 'insic' 5 +34798 'inski' 5 +34799 'insky' 5 +34800 'inson' 5 +34801 'instr' 5 +34802 'intel' 5 +34803 'inter' 5 +34804 'inton' 5 +34805 'intro' 5 +34806 'inté' 5 +34807 'iolet' 5 +34808 'ional' 5 +34809 'ioned' 5 +34810 'iones' 5 +34811 'ionic' 5 +34812 'iosis' 5 +34813 'iotic' 5 +34814 'ioxid' 5 +34815 'ipart' 5 +34816 'ipers' 5 +34817 'ipher' 5 +34818 'iples' 5 +34819 'ipped' 5 +34820 'ipper' 5 +34821 'ippet' 5 +34822 'ipple' 5 +34823 'ipzig' 5 +34824 'iques' 5 +34825 'iquid' 5 +34826 'iqué' 5 +34827 'ircle' 5 +34828 'irect' 5 +34829 'iring' 5 +34830 'irmed' 5 +34831 'irror' 5 +34832 'isans' 5 +34833 'iscal' 5 +34834 'ische' 5 +34835 'isers' 5 +34836 'ished' 5 +34837 'isher' 5 +34838 'ishes' 5 +34839 'ishly' 5 +34840 'ishop' 5 +34841 'ising' 5 +34842 'ision' 5 +34843 'isman' 5 +34844 'ismic' 5 +34845 'ismus' 5 +34846 'isnan' 5 +34847 'isode' 5 +34848 'isons' 5 +34849 'issan' 5 +34850 'issen' 5 +34851 'isser' 5 +34852 'isses' 5 +34853 'isset' 5 +34854 'isson' 5 +34855 'issue' 5 +34856 'istan' 5 +34857 'istar' 5 +34858 'istas' 5 +34859 'isted' 5 +34860 'istem' 5 +34861 'isten' 5 +34862 'ister' 5 +34863 'istes' 5 +34864 'istic' 5 +34865 'istik' 5 +34866 'istle' 5 +34867 'istol' 5 +34868 'iston' 5 +34869 'istor' 5 +34870 'istra' 5 +34871 'istro' 5 +34872 'istry' 5 +34873 'istä' 5 +34874 'isure' 5 +34875 'isée' 5 +34876 'isés' 5 +34877 'itage' 5 +34878 'itals' 5 +34879 'itant' 5 +34880 'itary' 5 +34881 'itate' 5 +34882 'itect' 5 +34883 'itely' 5 +34884 'items' 5 +34885 'iterr' 5 +34886 'ither' 5 +34887 'ithub' 5 +34888 'itial' 5 +34889 'ities' 5 +34890 'itime' 5 +34891 'iting' 5 +34892 'ition' 5 +34893 'itive' 5 +34894 'itié' 5 +34895 'itled' 5 +34896 'itles' 5 +34897 'itone' 5 +34898 'itore' 5 +34899 'itori' 5 +34900 'itors' 5 +34901 'itory' 5 +34902 'itsch' 5 +34903 'itted' 5 +34904 'ittee' 5 +34905 'itten' 5 +34906 'itter' 5 +34907 'ittle' 5 +34908 'itude' 5 +34909 'itung' 5 +34910 'iture' 5 +34911 'itzer' 5 +34912 'ität' 5 +34913 'ités' 5 +34914 'ivals' 5 +34915 'ivari' 5 +34916 'ivate' 5 +34917 'iveau' 5 +34918 'ively' 5 +34919 'ivent' 5 +34920 'ivers' 5 +34921 'ivery' 5 +34922 'iving' 5 +34923 'ivism' 5 +34924 'ivist' 5 +34925 'ivity' 5 +34926 'ixels' 5 +34927 'izada' 5 +34928 'izado' 5 +34929 'izard' 5 +34930 'izens' 5 +34931 'izers' 5 +34932 'izing' 5 +34933 'izons' 5 +34934 'izont' 5 +34935 'izoph' 5 +34936 'ième' 5 +34937 'ière' 5 +34938 'jamin' 5 +34939 'jango' 5 +34940 'javax' 5 +34941 'jiang' 5 +34942 'joint' 5 +34943 'jours' 5 +34944 'juana' 5 +34945 'judge' 5 +34946 'junit' 5 +34947 'juven' 5 +34948 'jähr' 5 +34949 'jší' 5 +34950 'kappa' 5 +34951 'keley' 5 +34952 'keras' 5 +34953 'klass' 5 +34954 'klär' 5 +34955 'known' 5 +34956 'ktion' 5 +34957 'ként' 5 +34958 'label' 5 +34959 'labor' 5 +34960 'laden' 5 +34961 'lando' 5 +34962 'lands' 5 +34963 'lapse' 5 +34964 'large' 5 +34965 'ları' 5 +34966 'lated' 5 +34967 'later' 5 +34968 'latex' 5 +34969 'latin' 5 +34970 'layer' 5 +34971 'ldots' 5 +34972 'leans' 5 +34973 'learn' 5 +34974 'lease' 5 +34975 'least' 5 +34976 'leave' 5 +34977 'ledge' 5 +34978 'legal' 5 +34979 'legen' 5 +34980 'leich' 5 +34981 'leigh' 5 +34982 'leman' 5 +34983 'lemen' 5 +34984 'lemma' 5 +34985 'letal' 5 +34986 'leted' 5 +34987 'letes' 5 +34988 'letic' 5 +34989 'leton' 5 +34990 'lette' 5 +34991 'level' 5 +34992 'lexer' 5 +34993 'lical' 5 +34994 'lices' 5 +34995 'liche' 5 +34996 'licht' 5 +34997 'licit' 5 +34998 'lickr' 5 +34999 'lient' 5 +35000 'liers' 5 +35001 'liest' 5 +35002 'ließ' 5 +35003 'light' 5 +35004 'ligne' 5 +35005 'liked' 5 +35006 'limit' 5 +35007 'lined' 5 +35008 'liner' 5 +35009 'lines' 5 +35010 'lings' 5 +35011 'linha' 5 +35012 'links' 5 +35013 'linux' 5 +35014 'lique' 5 +35015 'lista' 5 +35016 'lists' 5 +35017 'liter' 5 +35018 'lived' 5 +35019 'liver' 5 +35020 'loads' 5 +35021 'lobal' 5 +35022 'local' 5 +35023 'locks' 5 +35024 'logic' 5 +35025 'login' 5 +35026 'loops' 5 +35027 'lopen' 5 +35028 'lords' 5 +35029 'lotte' 5 +35030 'lover' 5 +35031 'lower' 5 +35032 'luent' 5 +35033 'lycer' 5 +35034 'lying' 5 +35035 'länd' 5 +35036 'macro' 5 +35037 'magic' 5 +35038 'mails' 5 +35039 'maint' 5 +35040 'major' 5 +35041 'maker' 5 +35042 'makes' 5 +35043 'mania' 5 +35044 'mares' 5 +35045 'marks' 5 +35046 'ması' 5 +35047 'match' 5 +35048 'mates' 5 +35049 'matic' 5 +35050 'maven' 5 +35051 'maxim' 5 +35052 'maybe' 5 +35053 'means' 5 +35054 'media' 5 +35055 'mente' 5 +35056 'ments' 5 +35057 'merce' 5 +35058 'merge' 5 +35059 'meric' 5 +35060 'metal' 5 +35061 'meter' 5 +35062 'metic' 5 +35063 'metro' 5 +35064 'metry' 5 +35065 'micro' 5 +35066 'might' 5 +35067 'miner' 5 +35068 'minim' 5 +35069 'minor' 5 +35070 'minus' 5 +35071 'mixed' 5 +35072 'mkdir' 5 +35073 'modal' 5 +35074 'model' 5 +35075 'modes' 5 +35076 'money' 5 +35077 'mongo' 5 +35078 'monic' 5 +35079 'month' 5 +35080 'morph' 5 +35081 'motor' 5 +35082 'mount' 5 +35083 'mouse' 5 +35084 'mouth' 5 +35085 'movie' 5 +35086 'multi' 5 +35087 'music' 5 +35088 'mutex' 5 +35089 'mysql' 5 +35090 'même' 5 +35091 'nabla' 5 +35092 'nable' 5 +35093 'naire' 5 +35094 'named' 5 +35095 'names' 5 +35096 'nants' 5 +35097 'natal' 5 +35098 'neath' 5 +35099 'needs' 5 +35100 'negie' 5 +35101 'nelle' 5 +35102 'nergy' 5 +35103 'nesty' 5 +35104 'nette' 5 +35105 'never' 5 +35106 'nginx' 5 +35107 'night' 5 +35108 'nikov' 5 +35109 'nings' 5 +35110 'nodes' 5 +35111 'noise' 5 +35112 'nonce' 5 +35113 'north' 5 +35114 'notes' 5 +35115 'notin' 5 +35116 'nucle' 5 +35117 'numer' 5 +35118 'numpy' 5 +35119 'nyder' 5 +35120 'nées' 5 +35121 'ného' 5 +35122 'ních' 5 +35123 'ního' 5 +35124 'ných' 5 +35125 'oauth' 5 +35126 'obile' 5 +35127 'obody' 5 +35128 'ocado' 5 +35129 'ocamp' 5 +35130 'ocard' 5 +35131 'ocate' 5 +35132 'occup' 5 +35133 'occur' 5 +35134 'occus' 5 +35135 'ocene' 5 +35136 'ocent' 5 +35137 'ocese' 5 +35138 'ochem' 5 +35139 'ocial' 5 +35140 'ocide' 5 +35141 'ocity' 5 +35142 'ocker' 5 +35143 'ocket' 5 +35144 'ockey' 5 +35145 'ocode' 5 +35146 'ocrat' 5 +35147 'ocyan' 5 +35148 'ocyte' 5 +35149 'odies' 5 +35150 'oding' 5 +35151 'odium' 5 +35152 'odont' 5 +35153 'odore' 5 +35154 'odule' 5 +35155 'offee' 5 +35156 'offer' 5 +35157 'offic' 5 +35158 'often' 5 +35159 'ogene' 5 +35160 'ogens' 5 +35161 'oggle' 5 +35162 'oglob' 5 +35163 'ograf' 5 +35164 'ogram' 5 +35165 'ograp' 5 +35166 'ográ' 5 +35167 'oidal' 5 +35168 'okers' 5 +35169 'oking' 5 +35170 'okrat' 5 +35171 'oland' 5 +35172 'olars' 5 +35173 'olate' 5 +35174 'older' 5 +35175 'olean' 5 +35176 'olics' 5 +35177 'olina' 5 +35178 'oline' 5 +35179 'oling' 5 +35180 'olini' 5 +35181 'olith' 5 +35182 'ollah' 5 +35183 'ollar' 5 +35184 'ollen' 5 +35185 'oller' 5 +35186 'ollow' 5 +35187 'ology' 5 +35188 'olson' 5 +35189 'olulu' 5 +35190 'olute' 5 +35191 'olved' 5 +35192 'olver' 5 +35193 'olves' 5 +35194 'ológ' 5 +35195 'omain' 5 +35196 'omaly' 5 +35197 'ombie' 5 +35198 'omega' 5 +35199 'oment' 5 +35200 'omers' 5 +35201 'omial' 5 +35202 'omics' 5 +35203 'oming' 5 +35204 'ommen' 5 +35205 'omnia' 5 +35206 'omore' 5 +35207 'områ' 5 +35208 'onald' 5 +35209 'onaut' 5 +35210 'onces' 5 +35211 'oncé' 5 +35212 'onder' 5 +35213 'ondon' 5 +35214 'onent' 5 +35215 'onial' 5 +35216 'onian' 5 +35217 'onica' 5 +35218 'onies' 5 +35219 'oning' 5 +35220 'onium' 5 +35221 'onomy' 5 +35222 'onset' 5 +35223 'onyms' 5 +35224 'ookie' 5 +35225 'ooter' 5 +35226 'opard' 5 +35227 'opath' 5 +35228 'openh' 5 +35229 'opens' 5 +35230 'opher' 5 +35231 'ophil' 5 +35232 'ophys' 5 +35233 'opian' 5 +35234 'oping' 5 +35235 'oplan' 5 +35236 'oples' 5 +35237 'oplus' 5 +35238 'opoly' 5 +35239 'oprop' 5 +35240 'opsis' 5 +35241 'opter' 5 +35242 'optic' 5 +35243 'optim' 5 +35244 'orage' 5 +35245 'orama' 5 +35246 'orate' 5 +35247 'orbit' 5 +35248 'ordan' 5 +35249 'orden' 5 +35250 'order' 5 +35251 'ordin' 5 +35252 'ordon' 5 +35253 'oreal' 5 +35254 'orean' 5 +35255 'orest' 5 +35256 'organ' 5 +35257 'orgen' 5 +35258 'orget' 5 +35259 'orial' 5 +35260 'orian' 5 +35261 'ories' 5 +35262 'oring' 5 +35263 'ority' 5 +35264 'ormal' 5 +35265 'orman' 5 +35266 'orney' 5 +35267 'orous' 5 +35268 'orpor' 5 +35269 'orrow' 5 +35270 'ortal' 5 +35271 'orted' 5 +35272 'orter' 5 +35273 'ortex' 5 +35274 'ortho' 5 +35275 'orthy' 5 +35276 'ortic' 5 +35277 'orton' 5 +35278 'ortun' 5 +35279 'osaic' 5 +35280 'osaur' 5 +35281 'osing' 5 +35282 'osion' 5 +35283 'osite' 5 +35284 'osity' 5 +35285 'oslav' 5 +35286 'osome' 5 +35287 'ospel' 5 +35288 'ossip' 5 +35289 'ostat' 5 +35290 'osten' 5 +35291 'oster' 5 +35292 'ostic' 5 +35293 'oston' 5 +35294 'oteca' 5 +35295 'otech' 5 +35296 'oters' 5 +35297 'other' 5 +35298 'otics' 5 +35299 'otide' 5 +35300 'otine' 5 +35301 'oting' 5 +35302 'otion' 5 +35303 'otive' 5 +35304 'otomy' 5 +35305 'otrop' 5 +35306 'otted' 5 +35307 'otten' 5 +35308 'ottom' 5 +35309 'otype' 5 +35310 'ouble' 5 +35311 'ought' 5 +35312 'oulos' 5 +35313 'ounce' 5 +35314 'ounds' 5 +35315 'ounge' 5 +35316 'ounty' 5 +35317 'ource' 5 +35318 'oured' 5 +35319 'ourse' 5 +35320 'oused' 5 +35321 'ousel' 5 +35322 'ouses' 5 +35323 'ously' 5 +35324 'ousse' 5 +35325 'outer' 5 +35326 'ouver' 5 +35327 'overn' 5 +35328 'overs' 5 +35329 'overy' 5 +35330 'ovich' 5 +35331 'oving' 5 +35332 'ović' 5 +35333 'ovsky' 5 +35334 'ować' 5 +35335 'ował' 5 +35336 'owell' 5 +35337 'owing' 5 +35338 'owitz' 5 +35339 'owler' 5 +35340 'owned' 5 +35341 'owner' 5 +35342 'ownik' 5 +35343 'owski' 5 +35344 'oxide' 5 +35345 'ozzá' 5 +35346 'ości' 5 +35347 'paced' 5 +35348 'paces' 5 +35349 'pages' 5 +35350 'paint' 5 +35351 'pairs' 5 +35352 'panel' 5 +35353 'panic' 5 +35354 'paper' 5 +35355 'param' 5 +35356 'paras' 5 +35357 'paren' 5 +35358 'parse' 5 +35359 'parts' 5 +35360 'party' 5 +35361 'paste' 5 +35362 'patch' 5 +35363 'paths' 5 +35364 'pathy' 5 +35365 'pause' 5 +35366 'peace' 5 +35367 'pedia' 5 +35368 'peech' 5 +35369 'pered' 5 +35370 'peria' 5 +35371 'peror' 5 +35372 'perse' 5 +35373 'perty' 5 +35374 'phalt' 5 +35375 'phant' 5 +35376 'phase' 5 +35377 'pherd' 5 +35378 'phere' 5 +35379 'phins' 5 +35380 'phinx' 5 +35381 'phone' 5 +35382 'phony' 5 +35383 'photo' 5 +35384 'piece' 5 +35385 'pires' 5 +35386 'pitch' 5 +35387 'pivot' 5 +35388 'pixel' 5 +35389 'place' 5 +35390 'plain' 5 +35391 'plane' 5 +35392 'plant' 5 +35393 'plate' 5 +35394 'platz' 5 +35395 'plays' 5 +35396 'pless' 5 +35397 'plete' 5 +35398 'plets' 5 +35399 'plica' 5 +35400 'plied' 5 +35401 'plier' 5 +35402 'plies' 5 +35403 'pline' 5 +35404 'pling' 5 +35405 'plist' 5 +35406 'pload' 5 +35407 'plots' 5 +35408 'point' 5 +35409 'polar' 5 +35410 'polit' 5 +35411 'ponse' 5 +35412 'poons' 5 +35413 'popup' 5 +35414 'porte' 5 +35415 'ports' 5 +35416 'posal' 5 +35417 'posed' 5 +35418 'poser' 5 +35419 'poses' 5 +35420 'posit' 5 +35421 'posix' 5 +35422 'posta' 5 +35423 'posts' 5 +35424 'pound' 5 +35425 'power' 5 +35426 'ppers' 5 +35427 'pping' 5 +35428 'pread' 5 +35429 'press' 5 +35430 'price' 5 +35431 'prime' 5 +35432 'pring' 5 +35433 'print' 5 +35434 'prior' 5 +35435 'prise' 5 +35436 'probe' 5 +35437 'produ' 5 +35438 'promo' 5 +35439 'proof' 5 +35440 'props' 5 +35441 'prote' 5 +35442 'proto' 5 +35443 'prove' 5 +35444 'proxy' 5 +35445 'près' 5 +35446 'prés' 5 +35447 'psych' 5 +35448 'ptide' 5 +35449 'ption' 5 +35450 'ptive' 5 +35451 'ptune' 5 +35452 'pulse' 5 +35453 'punkt' 5 +35454 'puted' 5 +35455 'puter' 5 +35456 'pués' 5 +35457 'qquad' 5 +35458 'quake' 5 +35459 'quant' 5 +35460 'quare' 5 +35461 'quart' 5 +35462 'queda' 5 +35463 'quent' 5 +35464 'query' 5 +35465 'quest' 5 +35466 'queue' 5 +35467 'quick' 5 +35468 'quier' 5 +35469 'quiet' 5 +35470 'quipe' 5 +35471 'quire' 5 +35472 'quiry' 5 +35473 'quist' 5 +35474 'quite' 5 +35475 'quito' 5 +35476 'quivo' 5 +35477 'quota' 5 +35478 'quote' 5 +35479 'rades' 5 +35480 'radio' 5 +35481 'rador' 5 +35482 'ragon' 5 +35483 'raham' 5 +35484 'rails' 5 +35485 'raine' 5 +35486 'rains' 5 +35487 'raint' 5 +35488 'raise' 5 +35489 'raits' 5 +35490 'ramer' 5 +35491 'ramid' 5 +35492 'rance' 5 +35493 'ranch' 5 +35494 'range' 5 +35495 'rapid' 5 +35496 'rases' 5 +35497 'rated' 5 +35498 'rates' 5 +35499 'ratio' 5 +35500 'ravel' 5 +35501 'razil' 5 +35502 'reach' 5 +35503 'react' 5 +35504 'reads' 5 +35505 'ready' 5 +35506 'realm' 5 +35507 'reate' 5 +35508 'recht' 5 +35509 'redit' 5 +35510 'reens' 5 +35511 'refer' 5 +35512 'refix' 5 +35513 'regex' 5 +35514 'regon' 5 +35515 'regor' 5 +35516 'reich' 5 +35517 'reira' 5 +35518 'relax' 5 +35519 'rella' 5 +35520 'rence' 5 +35521 'rench' 5 +35522 'rende' 5 +35523 'renew' 5 +35524 'rente' 5 +35525 'reply' 5 +35526 'repos' 5 +35527 'reset' 5 +35528 'resid' 5 +35529 'resol' 5 +35530 'resse' 5 +35531 'retch' 5 +35532 'reten' 5 +35533 'retry' 5 +35534 'rette' 5 +35535 'reuse' 5 +35536 'riage' 5 +35537 'rians' 5 +35538 'rible' 5 +35539 'ribly' 5 +35540 'rical' 5 +35541 'rices' 5 +35542 'richt' 5 +35543 'ricia' 5 +35544 'ricks' 5 +35545 'rides' 5 +35546 'ridge' 5 +35547 'riend' 5 +35548 'rient' 5 +35549 'riers' 5 +35550 'rieve' 5 +35551 'right' 5 +35552 'rimin' 5 +35553 'ringe' 5 +35554 'rings' 5 +35555 'riors' 5 +35556 'rique' 5 +35557 'rison' 5 +35558 'rists' 5 +35559 'riter' 5 +35560 'rites' 5 +35561 'ritic' 5 +35562 'ritis' 5 +35563 'rival' 5 +35564 'rived' 5 +35565 'river' 5 +35566 'roads' 5 +35567 'robat' 5 +35568 'robot' 5 +35569 'rocal' 5 +35570 'rogen' 5 +35571 'roles' 5 +35572 'rolls' 5 +35573 'rolog' 5 +35574 'romes' 5 +35575 'rones' 5 +35576 'ronic' 5 +35577 'ronym' 5 +35578 'rooms' 5 +35579 'roots' 5 +35580 'rophe' 5 +35581 'rophy' 5 +35582 'ropic' 5 +35583 'ropol' 5 +35584 'ropri' 5 +35585 'rored' 5 +35586 'rosis' 5 +35587 'rosse' 5 +35588 'rough' 5 +35589 'round' 5 +35590 'route' 5 +35591 'rowse' 5 +35592 'rowth' 5 +35593 'rozen' 5 +35594 'ruary' 5 +35595 'ruits' 5 +35596 'rules' 5 +35597 'rying' 5 +35598 'rypto' 5 +35599 'sales' 5 +35600 'saved' 5 +35601 'sburg' 5 +35602 'scala' 5 +35603 'scale' 5 +35604 'scape' 5 +35605 'scene' 5 +35606 'sched' 5 +35607 'schen' 5 +35608 'scope' 5 +35609 'score' 5 +35610 'scrib' 5 +35611 'sembl' 5 +35612 'senal' 5 +35613 'sense' 5 +35614 'separ' 5 +35615 'serie' 5 +35616 'serve' 5 +35617 'setUp' 5 +35618 'setup' 5 +35619 'seudo' 5 +35620 'seven' 5 +35621 'sever' 5 +35622 'shake' 5 +35623 'shall' 5 +35624 'shape' 5 +35625 'share' 5 +35626 'sharp' 5 +35627 'sheet' 5 +35628 'shelf' 5 +35629 'shell' 5 +35630 'shift' 5 +35631 'shine' 5 +35632 'ships' 5 +35633 'shire' 5 +35634 'shirt' 5 +35635 'shoot' 5 +35636 'shops' 5 +35637 'shore' 5 +35638 'short' 5 +35639 'shots' 5 +35640 'shown' 5 +35641 'shows' 5 +35642 'sible' 5 +35643 'sided' 5 +35644 'sight' 5 +35645 'sigma' 5 +35646 'simeq' 5 +35647 'simpl' 5 +35648 'since' 5 +35649 'sites' 5 +35650 'sized' 5 +35651 'sizes' 5 +35652 'skill' 5 +35653 'skins' 5 +35654 'slack' 5 +35655 'slant' 5 +35656 'slash' 5 +35657 'slave' 5 +35658 'sleep' 5 +35659 'slice' 5 +35660 'slide' 5 +35661 'slope' 5 +35662 'slots' 5 +35663 'small' 5 +35664 'smart' 5 +35665 'smith' 5 +35666 'snake' 5 +35667 'sofar' 5 +35668 'solar' 5 +35669 'solid' 5 +35670 'solve' 5 +35671 'sound' 5 +35672 'south' 5 +35673 'space' 5 +35674 'spark' 5 +35675 'spawn' 5 +35676 'spect' 5 +35677 'speed' 5 +35678 'spell' 5 +35679 'split' 5 +35680 'sport' 5 +35681 'spots' 5 +35682 'stack' 5 +35683 'stadt' 5 +35684 'staff' 5 +35685 'stage' 5 +35686 'stalk' 5 +35687 'stamp' 5 +35688 'stand' 5 +35689 'stant' 5 +35690 'stars' 5 +35691 'start' 5 +35692 'stash' 5 +35693 'state' 5 +35694 'stats' 5 +35695 'stdin' 5 +35696 'stdio' 5 +35697 'stead' 5 +35698 'steel' 5 +35699 'stein' 5 +35700 'stell' 5 +35701 'steps' 5 +35702 'stere' 5 +35703 'sters' 5 +35704 'stery' 5 +35705 'stick' 5 +35706 'still' 5 +35707 'stime' 5 +35708 'stock' 5 +35709 'stone' 5 +35710 'stood' 5 +35711 'store' 5 +35712 'storm' 5 +35713 'story' 5 +35714 'stown' 5 +35715 'strap' 5 +35716 'strip' 5 +35717 'strom' 5 +35718 'study' 5 +35719 'stuff' 5 +35720 'ství' 5 +35721 'style' 5 +35722 'stype' 5 +35723 'stüt' 5 +35724 'subst' 5 +35725 'suite' 5 +35726 'super' 5 +35727 'sweet' 5 +35728 'swers' 5 +35729 'swick' 5 +35730 'swift' 5 +35731 'swing' 5 +35732 'szág' 5 +35733 'table' 5 +35734 'tails' 5 +35735 'taire' 5 +35736 'taken' 5 +35737 'takes' 5 +35738 'tasks' 5 +35739 'tbody' 5 +35740 'techn' 5 +35741 'teger' 5 +35742 'templ' 5 +35743 'temps' 5 +35744 'tered' 5 +35745 'terms' 5 +35746 'terra' 5 +35747 'tests' 5 +35748 'texto' 5 +35749 'texts' 5 +35750 'tfrac' 5 +35751 'thank' 5 +35752 'thead' 5 +35753 'their' 5 +35754 'theme' 5 +35755 'there' 5 +35756 'thern' 5 +35757 'thers' 5 +35758 'these' 5 +35759 'theta' 5 +35760 'thick' 5 +35761 'thing' 5 +35762 'think' 5 +35763 'third' 5 +35764 'thood' 5 +35765 'those' 5 +35766 'three' 5 +35767 'thren' 5 +35768 'throw' 5 +35769 'thumb' 5 +35770 'tical' 5 +35771 'ticks' 5 +35772 'tight' 5 +35773 'tilde' 5 +35774 'tiles' 5 +35775 'timer' 5 +35776 'times' 5 +35777 'tings' 5 +35778 'title' 5 +35779 'tober' 5 +35780 'today' 5 +35781 'todos' 5 +35782 'token' 5 +35783 'tools' 5 +35784 'topic' 5 +35785 'torch' 5 +35786 'total' 5 +35787 'touch' 5 +35788 'trace' 5 +35789 'track' 5 +35790 'tract' 5 +35791 'trade' 5 +35792 'trail' 5 +35793 'train' 5 +35794 'trait' 5 +35795 'trans' 5 +35796 'trash' 5 +35797 'treat' 5 +35798 'trees' 5 +35799 'trend' 5 +35800 'trial' 5 +35801 'tries' 5 +35802 'tring' 5 +35803 'trunc' 5 +35804 'trust' 5 +35805 'truth' 5 +35806 'tuple' 5 +35807 'tures' 5 +35808 'tweet' 5 +35809 'twist' 5 +35810 'typed' 5 +35811 'types' 5 +35812 'uable' 5 +35813 'ually' 5 +35814 'uario' 5 +35815 'uated' 5 +35816 'uates' 5 +35817 'ubble' 5 +35818 'ubern' 5 +35819 'ubert' 5 +35820 'ublic' 5 +35821 'ublin' 5 +35822 'ubyte' 5 +35823 'uchar' 5 +35824 'uchen' 5 +35825 'ucing' 5 +35826 'ucion' 5 +35827 'ucked' 5 +35828 'ucker' 5 +35829 'ucket' 5 +35830 'uckle' 5 +35831 'uctor' 5 +35832 'uddle' 5 +35833 'udeau' 5 +35834 'udent' 5 +35835 'uding' 5 +35836 'udson' 5 +35837 'uelle' 5 +35838 'uerdo' 5 +35839 'uerto' 5 +35840 'uesta' 5 +35841 'uesto' 5 +35842 'ufact' 5 +35843 'uffed' 5 +35844 'uffer' 5 +35845 'uffix' 5 +35846 'uffle' 5 +35847 'uggle' 5 +35848 'ugins' 5 +35849 'uitar' 5 +35850 'ulant' 5 +35851 'ulate' 5 +35852 'ulent' 5 +35853 'uliar' 5 +35854 'uling' 5 +35855 'ulkan' 5 +35856 'ullah' 5 +35857 'ullen' 5 +35858 'ulner' 5 +35859 'ulong' 5 +35860 'ulose' 5 +35861 'ulous' 5 +35862 'ultan' 5 +35863 'ultur' 5 +35864 'ulté' 5 +35865 'umann' 5 +35866 'umbai' 5 +35867 'umber' 5 +35868 'umble' 5 +35869 'ument' 5 +35870 'umina' 5 +35871 'uming' 5 +35872 'ummer' 5 +35873 'umped' 5 +35874 'umper' 5 +35875 'uncan' 5 +35876 'uncia' 5 +35877 'undai' 5 +35878 'unday' 5 +35879 'undef' 5 +35880 'unden' 5 +35881 'under' 5 +35882 'undle' 5 +35883 'ungal' 5 +35884 'ungen' 5 +35885 'unger' 5 +35886 'ungle' 5 +35887 'uning' 5 +35888 'union' 5 +35889 'units' 5 +35890 'unity' 5 +35891 'unker' 5 +35892 'unned' 5 +35893 'unnel' 5 +35894 'unque' 5 +35895 'unset' 5 +35896 'unted' 5 +35897 'unter' 5 +35898 'until' 5 +35899 'untos' 5 +35900 'uplic' 5 +35901 'upper' 5 +35902 'uracy' 5 +35903 'urate' 5 +35904 'urban' 5 +35905 'urbed' 5 +35906 'ureau' 5 +35907 'urent' 5 +35908 'urers' 5 +35909 'urger' 5 +35910 'uries' 5 +35911 'uring' 5 +35912 'urity' 5 +35913 'urnal' 5 +35914 'urope' 5 +35915 'urous' 5 +35916 'urred' 5 +35917 'ursed' 5 +35918 'urses' 5 +35919 'ursor' 5 +35920 'urtle' 5 +35921 'usage' 5 +35922 'users' 5 +35923 'useum' 5 +35924 'ushed' 5 +35925 'ushes' 5 +35926 'using' 5 +35927 'usion' 5 +35928 'usive' 5 +35929 'ussed' 5 +35930 'ussen' 5 +35931 'ussia' 5 +35932 'usted' 5 +35933 'uster' 5 +35934 'ustin' 5 +35935 'ustom' 5 +35936 'usual' 5 +35937 'utely' 5 +35938 'uters' 5 +35939 'uteur' 5 +35940 'uther' 5 +35941 'utils' 5 +35942 'uting' 5 +35943 'ution' 5 +35944 'utive' 5 +35945 'utors' 5 +35946 'utory' 5 +35947 'utral' 5 +35948 'utsch' 5 +35949 'utter' 5 +35950 'utton' 5 +35951 'uture' 5 +35952 'uyên' 5 +35953 'uzzle' 5 +35954 'vable' 5 +35955 'valid' 5 +35956 'valor' 5 +35957 'value' 5 +35958 'varez' 5 +35959 'vault' 5 +35960 'vdots' 5 +35961 'velle' 5 +35962 'velop' 5 +35963 'venir' 5 +35964 'venth' 5 +35965 'vents' 5 +35966 'venue' 5 +35967 'verbs' 5 +35968 'verse' 5 +35969 'verte' 5 +35970 'verts' 5 +35971 'verty' 5 +35972 'vette' 5 +35973 'video' 5 +35974 'vider' 5 +35975 'vidia' 5 +35976 'views' 5 +35977 'villa' 5 +35978 'ville' 5 +35979 'vious' 5 +35980 'viron' 5 +35981 'virus' 5 +35982 'vised' 5 +35983 'visit' 5 +35984 'visor' 5 +35985 'vival' 5 +35986 'vocab' 5 +35987 'voice' 5 +35988 'votes' 5 +35989 'väst' 5 +35990 'wagen' 5 +35991 'walls' 5 +35992 'wards' 5 +35993 'wares' 5 +35994 'watch' 5 +35995 'water' 5 +35996 'waves' 5 +35997 'wedge' 5 +35998 'weeks' 5 +35999 'weets' 5 +36000 'weise' 5 +36001 'wheel' 5 +36002 'where' 5 +36003 'which' 5 +36004 'while' 5 +36005 'white' 5 +36006 'whole' 5 +36007 'whose' 5 +36008 'width' 5 +36009 'witch' 5 +36010 'wives' 5 +36011 'wiąz' 5 +36012 'woman' 5 +36013 'women' 5 +36014 'woods' 5 +36015 'words' 5 +36016 'works' 5 +36017 'world' 5 +36018 'worth' 5 +36019 'would' 5 +36020 'write' 5 +36021 'wrong' 5 +36022 'xhtml' 5 +36023 'xiety' 5 +36024 'xmlns' 5 +36025 'xpath' 5 +36026 'xture' 5 +36027 'xygen' 5 +36028 'yahoo' 5 +36029 'yards' 5 +36030 'ycler' 5 +36031 'years' 5 +36032 'yield' 5 +36033 'ylene' 5 +36034 'ylvan' 5 +36035 'ymbol' 5 +36036 'yntax' 5 +36037 'young' 5 +36038 'ystem' 5 +36039 'yster' 5 +36040 'ython' 5 +36041 'ytics' 5 +36042 'zeich' 5 +36043 'zeros' 5 +36044 'ział' 5 +36045 'zilla' 5 +36046 'zione' 5 +36047 'zsche' 5 +36048 '}}_{\\' 5 +36049 'ÇÃO' 5 +36050 'État' 5 +36051 'ában' 5 +36052 'ácil' 5 +36053 'ález' 5 +36054 'ális' 5 +36055 'álva' 5 +36056 'ámos' 5 +36057 'ának' 5 +36058 'ános' 5 +36059 'ání' 5 +36060 'ária' 5 +36061 'ário' 5 +36062 'ások' 5 +36063 'átum' 5 +36064 'ával' 5 +36065 'ável' 5 +36066 'ází' 5 +36067 'ână' 5 +36068 'âtre' 5 +36069 'äche' 5 +36070 'ächs' 5 +36071 'ächt' 5 +36072 'äger' 5 +36073 'ählt' 5 +36074 'äler' 5 +36075 'älle' 5 +36076 'ällt' 5 +36077 'ämä' 5 +36078 'ände' 5 +36079 'änge' 5 +36080 'ären' 5 +36081 'ässt' 5 +36082 'äter' 5 +36083 'ätte' 5 +36084 'ätze' 5 +36085 'äude' 5 +36086 'ään' 5 +36087 'ædia' 5 +36088 'çais' 5 +36089 'çois' 5 +36090 'çoit' 5 +36091 'ção' 5 +36092 'èces' 5 +36093 'èles' 5 +36094 'èmes' 5 +36095 'ènes' 5 +36096 'èque' 5 +36097 'ères' 5 +36098 'ètes' 5 +36099 'ètre' 5 +36100 'èves' 5 +36101 'ébec' 5 +36102 'ében' 5 +36103 'écur' 5 +36104 'éder' 5 +36105 'édia' 5 +36106 'édie' 5 +36107 'édé' 5 +36108 'élé' 5 +36109 'émet' 5 +36110 'émie' 5 +36111 'émon' 5 +36112 'ének' 5 +36113 'énez' 5 +36114 'énom' 5 +36115 'éné' 5 +36116 'éral' 5 +36117 'érer' 5 +36118 'érez' 5 +36119 'éric' 5 +36120 'érie' 5 +36121 'ério' 5 +36122 'éré' 5 +36123 'ésie' 5 +36124 'éső' 5 +36125 'état' 5 +36126 'éter' 5 +36127 'été' 5 +36128 'ével' 5 +36129 'êmes' 5 +36130 'êque' 5 +36131 'êtes' 5 +36132 'être' 5 +36133 'ícia' 5 +36134 'ício' 5 +36135 'ícul' 5 +36136 'ící' 5 +36137 'ígen' 5 +36138 'ília' 5 +36139 'ínez' 5 +36140 'íses' 5 +36141 'ível' 5 +36142 'ître' 5 +36143 'ñana' 5 +36144 'òria' 5 +36145 'ództ' 5 +36146 'ópez' 5 +36147 'ória' 5 +36148 'ório' 5 +36149 'ôtel' 5 +36150 'öder' 5 +36151 'önig' 5 +36152 'öße' 5 +36153 'úmer' 5 +36154 'über' 5 +36155 'ücke' 5 +36156 'ügel' 5 +36157 'ügen' 5 +36158 'ühle' 5 +36159 'ührt' 5 +36160 'üler' 5 +36161 'ület' 5 +36162 'ünst' 5 +36163 'ční' 5 +36164 'ędzy' 5 +36165 'ění' 5 +36166 'ılı' 5 +36167 'ında' 5 +36168 'ını' 5 +36169 'łoż' 5 +36170 'łuż' 5 +36171 'łów' 5 +36172 'ńczy' 5 +36173 'ńska' 5 +36174 'ński' 5 +36175 'ństw' 5 +36176 'ście' 5 +36177 'śnie' 5 +36178 'ště' 5 +36179 'ším' 5 +36180 'ướ' 5 +36181 'ườ' 5 +36182 'ưở' 5 +36183 'ượ' 5 +36184 'ảng' 5 +36185 'ằng' 5 +36186 'ịch' 5 +36187 'ống' 5 +36188 'ồng' 5 +36189 'ụng' 5 +36190 'ứng' 5 +36191 'ững' 5 +36192 '’il' 5 +36193 '’ll' 5 +36194 '’re' 5 +36195 '’ve' 5 +36196 '“No' 5 +36197 '”),' 5 +36198 '”).' 5 +36199 '…..' 5 +36200 '!",' 5 +36201 ': +#include +#include +#include +#include +#include +#include +#include "bytematch.hpp" + + +class RWKVTokenizer { +private: + std::vector>>> table; + std::vector> good; + std::vector wlen; + std::unordered_map> idx2token; + std::unordered_map token2idx; + + +public: + RWKVTokenizer(const std::string& fileName) { + // Reading file and constructing idx2token and token2idx + std::ifstream file(fileName); + std::string line; + std::vector> sorted; + while (std::getline(file, line)) { + size_t idxSpace = line.find(' '); + int idx = std::stoi(line.substr(0, idxSpace)); + auto x = findPythonByteObjects(line.substr(idxSpace + 1, line.rfind(' ') - idxSpace - 1)); + if (x.size() == 0) { + // decode the string as utf-8 + auto line2 = line.substr(idxSpace + 2, line.rfind(' ') - idxSpace - 3); + // std::cout << line2 << std::endl; + + x = std::vector(line2.begin(), line2.end()); + } + + for (int i = 0; i < x.size(); i++) { + if (x[i] == '\\') { + switch (x[i + 1]) { + case 'n': + x[i] = '\n'; + break; + case 't': + x[i] = '\t'; + break; + case 'r': + x[i] = '\r'; + break; + case 'b': + x[i] = '\b'; + break; + case 'f': + x[i] = '\f'; + break; + case '\\': + x[i] = '\\'; + break; + case '\'': + x[i] = '\''; + break; + case '\"': + x[i] = '\"'; + break; + case '0': + x[i] = '\0'; + break; + } + x.erase(x.begin() + i + 1); + } + } + + sorted.push_back(x); + + + idx2token[idx] = x; + } + + file.close(); + + // Constructing token2idx + for (const auto& pair : idx2token) { + std::string tokenStr(pair.second.begin(), pair.second.end()); + token2idx[tokenStr] = pair.first; + } + + // precompute some tables for fast matching + // this.table = Array.from({ length: 256 }, () => Array.from({ length: 256 }, () => [])); + // this.good = Array.from({ length: 256 }, () => new Set()); + // this.wlen = Array.from({ length: 256 }, () => 0); + + // for (let i = sorted.length - 1; i >= 0; i--) { // reverse order - match longer tokens first + // const s = sorted[i]; + // if (s.length >= 2) { + // const s0 = s[0]; + // const s1 = s[1]; + // this.table[s0][s1].push(s); + // this.wlen[s0] = Math.max(this.wlen[s0], s.length); + // this.good[s0].add(s1); + // } + // } Convert to c++ + table = std::vector>>>(256, std::vector>>(256, std::vector>())); + good = std::vector>(256, std::set()); + wlen = std::vector(256, 0); + + for (int i = sorted.size() - 1; i >= 0; i--) { + const std::vector& s = sorted[i]; + if (s.size() >= 2) { + const uchar s0 = s[0]; + const uchar s1 = s[1]; + // init table[s0][s1] if it doesn't exist + + table[s0][s1].push_back(s); + wlen[s0] = std::max(wlen[s0], (int)s.size()); + good[s0].insert(s1); + } + } + + // More initializer code would go here to replicate the JavaScript behavior + } + + // More methods to replicate the JavaScript behavior would go here + + // Sample print function based on printTokens + void printTokens(const std::vector& tokens) { + for (auto i : tokens) { + try { + std::vector s = idx2token[i]; + std::string str(s.begin(), s.end()); + std::cout << "\"" << str << "\"" << i << " "; + } catch (...) { + // If the conversion to string fails, keep it in some other format. + // Note: Better error handling is needed + std::cout << "Error" << i << " "; + } + } + std::cout << std::endl; + } + + + std::vector encode(const std::string &src) { + std::vector srcBytes(src.begin(), src.end()); + return encodeBytes(srcBytes); + } + + std::string decode(const std::vector &tokens) { + std::vector byteResult = decodeBytes(tokens); + return std::string(byteResult.begin(), byteResult.end()); + } + + static bool startsWith(const std::vector &target, const std::vector &prefix) { + if (prefix.size() > target.size()) { + return false; + } + return std::equal(prefix.begin(), prefix.end(), target.begin()); + } + +private: + std::vector encodeBytes(const std::vector& src) { + const size_t srcLen = src.size(); + std::vector tokens; + size_t i = 0; + while (i < srcLen) { + std::vector s(src.begin() + i, src.begin() + i + 1); + if (i < srcLen - 1) { + const int s1 = src[i + 1]; + const int s0 = src[i]; + if (good[s0].find(s1) != good[s0].end()) { + std::vector sss(src.begin() + i, src.begin() + i + wlen[s0]); + auto matchIt = std::find_if(table[s0][s1].begin(), table[s0][s1].end(), + [&sss](const std::vector& t) { return startsWith(sss, t); }); + if (matchIt != table[s0][s1].end()) { + s = *matchIt; + } + } + } + std::string sStr(s.begin(), s.end()); + tokens.push_back(token2idx[sStr]); + i += s.size(); + } + return tokens; + } + + std::vector decodeBytes(const std::vector &tokens) { + std::vector decoded; + for (int token : tokens) { + const std::vector &tokenBytes = idx2token.at(token); + decoded.insert(decoded.end(), tokenBytes.begin(), tokenBytes.end()); + } + return decoded; + } + + + +}; + +RWKVTokenizer worldTokenizer("rwkv_vocab_v20230424.txt"); +// int main() { + +// std::vector sampleTokens = worldTokenizer.encode("Hello World!"); +// std::cout << "Encoded tokens: " << sampleTokens[0] << " " << sampleTokens[1] << std::endl; +// std::cout << worldTokenizer.decode({33155, 37576}) << std::endl; +// return 0; +// } + +#endif // BYTEMATCH_HPP \ No newline at end of file diff --git a/runexamples/node/package-lock.json b/runexamples/node/package-lock.json new file mode 100644 index 0000000..5996ef1 --- /dev/null +++ b/runexamples/node/package-lock.json @@ -0,0 +1,387 @@ +{ + "name": "node-rwkv", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "name": "node-rwkv", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "fs": "^0.0.1-security", + "onnxruntime-common": "^1.16.2", + "onnxruntime-node": "^1.16.2", + "ts-node": "^10.9.1" + }, + "devDependencies": { + "@types/node": "^20.9.0" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==", + "license": "MIT" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==", + "license": "MIT" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==", + "license": "MIT" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.9.0.tgz", + "integrity": "sha512-nekiGu2NDb1BcVofVcEKMIwzlx4NjHlcjhoxxKBNLtz15Y1z7MYf549DFvkHSId02Ax6kGwWntIBPC3l/JZcmw==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/acorn": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", + "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-walk": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.0.tgz", + "integrity": "sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", + "license": "MIT" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", + "license": "MIT" + }, + "node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/fs": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", + "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==", + "license": "ISC" + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "license": "ISC" + }, + "node_modules/onnxruntime-common": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.16.2.tgz", + "integrity": "sha512-S2/wPoW2uaq5WzpStS6XKOsy8EvKZOOdpzq++HpIV6XZYl0EIfoWBV/Pi5PWcJPFBcu7Rkopo/oPk9IbD9qRlw==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.16.2.tgz", + "integrity": "sha512-Qe/Fjx2n5Tlfm++RP/IHAmHrXaXoP75PK9p8XrDf6wI59Jk5ypL5F/bNH7lV3gOT8XIsjJmCBC2sfCVuivz1eQ==", + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "onnxruntime-common": "~1.16.2" + } + }, + "node_modules/ts-node": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", + "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "license": "MIT", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/typescript": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", + "license": "MIT" + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + } + }, + "dependencies": { + "@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "requires": { + "@jridgewell/trace-mapping": "0.3.9" + } + }, + "@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==" + }, + "@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "requires": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==" + }, + "@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==" + }, + "@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==" + }, + "@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==" + }, + "@types/node": { + "version": "20.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.9.0.tgz", + "integrity": "sha512-nekiGu2NDb1BcVofVcEKMIwzlx4NjHlcjhoxxKBNLtz15Y1z7MYf549DFvkHSId02Ax6kGwWntIBPC3l/JZcmw==", + "requires": { + "undici-types": "~5.26.4" + } + }, + "acorn": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", + "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==" + }, + "acorn-walk": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.0.tgz", + "integrity": "sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA==" + }, + "arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" + }, + "create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" + }, + "diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==" + }, + "fs": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", + "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==" + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "onnxruntime-common": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.16.2.tgz", + "integrity": "sha512-S2/wPoW2uaq5WzpStS6XKOsy8EvKZOOdpzq++HpIV6XZYl0EIfoWBV/Pi5PWcJPFBcu7Rkopo/oPk9IbD9qRlw==" + }, + "onnxruntime-node": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.16.2.tgz", + "integrity": "sha512-Qe/Fjx2n5Tlfm++RP/IHAmHrXaXoP75PK9p8XrDf6wI59Jk5ypL5F/bNH7lV3gOT8XIsjJmCBC2sfCVuivz1eQ==", + "requires": { + "onnxruntime-common": "~1.16.2" + } + }, + "ts-node": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", + "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "requires": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + } + }, + "typescript": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", + "peer": true + }, + "undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==" + }, + "yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==" + } + } +} diff --git a/runexamples/node/package.json b/runexamples/node/package.json new file mode 100644 index 0000000..ad1ee80 --- /dev/null +++ b/runexamples/node/package.json @@ -0,0 +1,17 @@ +{ + "name": "node-rwkv", + "version": "1.0.0", + "description": "A rwkv node runner", + "main": "index.js", + "author": "Harrison vanderbyl", + "license": "MIT", + "dependencies": { + "fs": "^0.0.1-security", + "onnxruntime-common": "^1.16.2", + "onnxruntime-node": "^1.16.2", + "ts-node": "^10.9.1" + }, + "devDependencies": { + "@types/node": "^20.9.0" + } +} diff --git a/runexamples/node/sampler/sample.ts b/runexamples/node/sampler/sample.ts new file mode 100644 index 0000000..4797956 --- /dev/null +++ b/runexamples/node/sampler/sample.ts @@ -0,0 +1,144 @@ +/** + * Given the float array, get its max value. + * @param {Float32Array} arr + * @returns {number} + */ +export function getMaxFloat(arr:Float32Array): number { + let max = -Infinity; + for (let i = 0; i < arr.length; i++) { + if (arr[i] > max) max = arr[i]; + } + // if( max == 0.0 ) { + // throw "Unexpected max == 0 in getMaxFloat" + // } + return max; +} + +/** + * Implements the softmax function. + * Which reads the input array, and outputs an array of + * index to probability mappings. + * + * @param {Float32Array} arr to read from + * @returns + */ +function softmaxToProbPair( arr:Float32Array ) { + // Get the logits size + const logits_size = arr.length; + + // Setup the probability pair array + const probPair = new Array(logits_size); + + // Get the max value + const max = getMaxFloat(arr); + + // Subtract the max value from each element + // and calculate the sum of exponents + let sum = 0.0; + for (let i = 0; i < logits_size; i++) { + const prob = Math.exp(arr[i] - max); + probPair[i] = [i, prob]; + sum += prob; + } + + // Divide each element by the sum + for (let i = 0; i < logits_size; i++) { + probPair[i][1] = probPair[i][1] / sum; + } + + // Return the sorted probability pair + return probPair.sort((a, b) => b[1] - a[1]); +} + +/** + * sample_logits operation, used to decide on the next token + * given the current logits output. + * + * @param {Float32Array} logits - The logits output from the model + * @param {number} temp - The temperature to use for sampling + * @param {number} top_p - The top_p to use for sampling + * + * @returns {Object} containing the token index, and the final logits + */ +export function sampleLogits(logits:Float32Array, temp: number = 1.0, top_p: number = 1.0): {token: number, logprobs: number[][]} { + // + // !!! Important note !!! + // + // Because sampling function can differ between implementation. + // We are following blinks RWKV_in_150_lines as close as possible here. + // To help ensure consistency between implementations of RWKV + // + // https://github.com/BlinkDL/ChatRWKV/blob/main/RWKV_in_150_lines.py#L119 + // + // This will differ from minGPT implementation (and some other implementations) + // https://github.com/karpathy/minGPT/blob/37baab71b9abea1b76ab957409a1cc2fbfba8a26/mingpt/model.py#L283 + // + + // Validate the logits buffer + if (logits == null) { + throw "Invalid logits buffer"; + } + + // If temp is 0.0, then we just return the max logit index + if (temp <= 0.0) { + return {token:logits.indexOf(getMaxFloat(logits)), logprobs:[]}; + } + + // Validate the top_p + if (top_p < 0.0) { + throw "Invalid top_p"; + } + + // Normalize temp, and top_p as float values + temp = temp * 1.0; + top_p = top_p * 1.0; + + // Change into a list of [index, prob] pairs + // while applying softmax at the same time + let probPairs = softmaxToProbPair(logits); + + // Get the cumulative probability pre and post temp scaling + let cumSoftmaxProb = 0.0; + let cumTempProb = 0.0; + for (let i = 0; i < probPairs.length; i++) { + const tempProb = Math.pow(probPairs[i][1], 1.0 / temp); + cumSoftmaxProb += probPairs[i][1]; + cumTempProb += tempProb; + probPairs[i][1] = tempProb; + + // Top_p filtering + // --- + // If top_p is is valid and + // If we have reached the top_p threshold, then break + // This is done here to avoid the need to loop again + if (top_p < 1.0 && cumTempProb >= top_p) { + probPairs = probPairs.slice(0, i + 1); + break; + } + } + + // Time to sample + let randProb = Math.random() * cumTempProb; + + // Find the index of the sampled token + for(let i = 0; i < probPairs.length; i++) { + randProb -= probPairs[i][1]; + if (randProb <= 0.0) { + return { + token: probPairs[i][0], + logprobs: probPairs + }; + } + } + + // Out of bound? return the first index + // (higest probability token) + // + // This should not happen unless an extream case + // of floating point accuracy error + return { + token: probPairs[0][0], + logprobs: probPairs + }; +} + diff --git a/runexamples/node/test.ts b/runexamples/node/test.ts new file mode 100644 index 0000000..a3a66bc --- /dev/null +++ b/runexamples/node/test.ts @@ -0,0 +1,306 @@ +// Declare to typescript compiler that we are using onnxruntime-node and to ignore type checking. + +// Ignore type checking for onnxruntime-node. +// @ts-ignore +import * as ort from 'onnxruntime-node'; + +import {InferenceSession, Tensor, TypedTensor, InferenceSessionFactory} from 'onnxruntime-common'; +import { WorldTokenizer } from './tokenizer/tokenizer'; +import { sampleLogits } from './sampler/sample'; + +// write data content to a file continously +import { createWriteStream } from 'fs'; + +type WkvStateName = "wkv"|"" +type StateKey = `state${WkvStateName}${number}` +type OutStateKey = `state${WkvStateName}${number}out` + +type State = { + + [key: StateKey]: TypedTensor<"float32"> +} + +type TokenJob = { + token: number + state: State + callback: (logits:Tensor,state:State) => void +} + +type ProbState = { + probs: Tensor, + state: State +} + +// function zipState(states:State[]):State { +// const result:State = {} +// for (const key in states[0]) { +// const tensors = states.map(state => state[key]) +// // result[key] = Tensor.concat(tensors) +// } +// return result +// } + + +class RWKV { + + embed:number = 0 + layers:number = 0 + heads:number = 0 + model: Initialized extends true ? InferenceSession : null = null as Initialized extends true ? InferenceSession : null + path : string + jobQueue:TokenJob[] = [] + currentJobs:TokenJob[] = [] + stateHolder:State = {} + + constructor(path:string) { + this.path = path + } + + + unzipState(state:State, oldStates:State[]):State[] { + const result:State[] = [] + + const B = oldStates.length + + for (let i = 0; i < B; i++) { + for (const key in state) { + const tensor:TypedTensor<"float32"> = state[key as StateKey] + const dims = tensor.dims + const muldims = dims.slice(1).reduce((a,b) => a*b) + const data = tensor.data.subarray(i*muldims,(i+1)*muldims) + oldStates[i][key as StateKey].data.set(data) + } + } + return oldStates + } + + zipState(states:State[]) { + for (const key in states[0]) { + const tensors = states.map(state => (state[key as StateKey] as TypedTensor<"float32">)) + const dims = tensors[0].dims + const newdims = [states.length,...dims.slice(1)]; + const newsize = newdims.reduce((a,b) => a*b) + + if(this.stateHolder[key as StateKey] == undefined ){ + this.stateHolder[key as StateKey] = new Tensor("float32",new Float32Array(newsize),newdims) + } + + if (this.stateHolder[key as StateKey].dims[0] != states.length) { + this.stateHolder[key as StateKey] = new Tensor("float32",new Float32Array(newsize),newdims) + } + + + for (let i = 0; i < states.length; i++) { + const state = states[i]; + const tensor = state[key as StateKey] + const data = tensor.data + this.stateHolder[key as StateKey].data.set(data,i*data.length) + } + + // 390 18 + } + } + + async run (){ + if (this.jobQueue.length > 0) { + const jobs = this.jobQueue.splice(0,Math.min(this.jobQueue.length,128)) + + this.currentJobs = jobs + const states = jobs.map(job => job.state) + this.zipState(states) + const tokens = new Tensor("int32",jobs.map(job => job.token),[jobs.length]) + + const stateNames = this.model!.inputNames.filter(name => name.startsWith("state")) as StateKey[] + + const outputs = await this.model!.run({"input0":tokens,...this.stateHolder}); + + + + const logits = Object.values(outputs).find( + (tensor) => tensor.dims[1] == 2**16 + ) as Tensor + + const nextInputState = stateNames.reduce((acc,name) => { + acc[name] = outputs[name+"out"] as TypedTensor<"float32"> + return acc + }, {} as State) + + + + + const newstates = this.unzipState(nextInputState, states) + + this.stateHolder = {} + + newstates.forEach((state,i) => { + // console.log("state: ", Object.keys(state)) + jobs[i].callback(logits,state) + }) + this.currentJobs = [] + + } + + } + + + + + async load():Promise> { + const sess:InferenceSession = await (ort.InferenceSession as InferenceSessionFactory).create(this.path, { + interOpNumThreads: 8, + intraOpNumThreads: 8, + executionMode: 'parallel', + executionProviders: ["cpu"] + }); + + // prepare inputs. a tensor need its corresponding TypedArray as data + const inputnames = sess.inputNames; + + // console.log("inputnames: ",inputnames) + + // Get the shape of the input + + this.embed = 2048 + this.layers = (inputnames.length-1)/3 + this.heads = 32 // 32 if 1b5 + + // console.log("embed: ", this.embed) + // console.log("layers: ", this.layers) + + this.model = sess as Initialized extends true ? InferenceSession : null + + return this as unknown as RWKV + } + + newState():State { + const result:State = {} + for (let i = 0; i < this.layers*2; i++) { + result[`state${i}` as StateKey] = new Tensor("float32",new Float32Array(this.embed),[1,this.embed]) + } + + for (let i = 0; i < this.layers; i++) { + result[`statewkv${i}` as StateKey] = new Tensor("float32",new Float32Array(((this.embed * this.embed)/this.heads)),[1,this.heads,this.embed/this.heads, this.embed/this.heads]) + } + return result + } + + async readContext(context:number[],state?:State):Promise{ + return new Promise((resolve,reject) => { + if (state == undefined) { + state = this.newState() + } + + var current = 0; + + const callback = (logits:Tensor,nextstate:State) => { + current+=1 + console.log("current: ",current, nextstate.state1.data[0]) + if (current == context.length) { + resolve({ + state: nextstate, + probs: logits + }) + }else{ + this.jobQueue.push({ + token: context[current], + state: nextstate, + callback + }) + } + } + + this.jobQueue.push({ + token: context[current], + state, + callback + }) + + + }) + +} + + startListening() { + setInterval(() => { + this.run() + }, 10); + } + + sampleLogits(logits:Tensor):number { + return sampleLogits(logits.data as Float32Array,0.9,0.9).token + } + + async genToken(input:ProbState, callback:(i:number)=>void):Promise{ + const {state,probs} = input + const token = this.sampleLogits(probs) + callback(token) + const newstate = await this.readContext([token],state) + return newstate + } + + + +} + + + +// use an async context to call onnxruntime functions. +async function main() { + try { + + const tokens = WorldTokenizer.encode("\n### Instruction:\nCan you please write a short epic fantasy story? ### Response: \n") + + // create a new session and load the specific model. + // + // the model in this example contains a single MatMul node + // it has 2 inputs: 'a'(float32, 3x4) and 'b'(float32, 4x3) + // it has 1 output: 'c'(float32, 3x3) + + // const testTensor:Tensor = new Tensor('float32', [0, 0, 0, 0], [1,2,2]); + + // console.log("testTensor: ", testTensor) + + // console.log("testTensor.data: ", testTensor.data.slice(0,2)) + + const model = await new RWKV('../../RWKV_24_2048_32_15.onnx').load() + model.startListening() + + const writeStream = createWriteStream("./out.txt") + + var curstate = await model.readContext(tokens) + + console.log("curstate: ", curstate.state.state1.data[0]) + + for(var i = 0; i < 100; i++){ + curstate = await model.genToken(curstate, + (token) => { + try{ + + const text = WorldTokenizer.decode([token]) + writeStream.write(text) + + } + catch(e){ + console.log("error: ", e) + } + } + ) + } + + + + + + while (true) { + await new Promise(resolve => setTimeout(resolve, 1000)); + } + + + + + } catch (e) { + console.error(`failed to inference ONNX model: ${e}.`); + } +} + +main(); \ No newline at end of file diff --git a/runexamples/node/tokenizer b/runexamples/node/tokenizer new file mode 160000 index 0000000..0131095 --- /dev/null +++ b/runexamples/node/tokenizer @@ -0,0 +1 @@ +Subproject commit 01310957c62c5c2f312671eaa42f658362d567c4 diff --git a/runexamples/node/yarn-error.log b/runexamples/node/yarn-error.log new file mode 100644 index 0000000..3b4a1fd --- /dev/null +++ b/runexamples/node/yarn-error.log @@ -0,0 +1,165 @@ +Arguments: + /usr/local/bin/node /usr/local/bin/yarn add @types/onnxruntime-node + +PATH: + /home/harrison/.local/bin:/home/harrison/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin + +Yarn version: + 1.22.19 + +Node version: + 18.10.0 + +Platform: + linux x64 + +Trace: + Error: https://registry.yarnpkg.com/@types%2fonnxruntime-node: Not found + at params.callback [as _callback] (/usr/local/lib/node_modules/yarn/lib/cli.js:66145:18) + at self.callback (/usr/local/lib/node_modules/yarn/lib/cli.js:140890:22) + at Request.emit (node:events:513:28) + at Request. (/usr/local/lib/node_modules/yarn/lib/cli.js:141862:10) + at Request.emit (node:events:513:28) + at IncomingMessage. (/usr/local/lib/node_modules/yarn/lib/cli.js:141784:12) + at Object.onceWrapper (node:events:627:28) + at IncomingMessage.emit (node:events:525:35) + at endReadableNT (node:internal/streams/readable:1359:12) + at process.processTicksAndRejections (node:internal/process/task_queues:82:21) + +npm manifest: + { + "name": "node-rwkv", + "version": "1.0.0", + "description": "A rwkv node runner", + "main": "index.js", + "author": "Harrison vanderbyl", + "license": "MIT", + "dependencies": { + "onnxruntime-node": "^1.16.2", + "ts-node": "^10.9.1" + } + } + +yarn manifest: + No manifest + +Lockfile: + # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. + # yarn lockfile v1 + + + "@cspotcode/source-map-support@^0.8.0": + version "0.8.1" + resolved "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz#00629c35a688e05a88b1cda684fb9d5e73f000a1" + integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== + dependencies: + "@jridgewell/trace-mapping" "0.3.9" + + "@jridgewell/resolve-uri@^3.0.3": + version "3.1.1" + resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721" + integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== + + "@jridgewell/sourcemap-codec@^1.4.10": + version "1.4.15" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" + integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== + + "@jridgewell/trace-mapping@0.3.9": + version "0.3.9" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + + "@tsconfig/node10@^1.0.7": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.9.tgz#df4907fc07a886922637b15e02d4cebc4c0021b2" + integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA== + + "@tsconfig/node12@^1.0.7": + version "1.0.11" + resolved "https://registry.yarnpkg.com/@tsconfig/node12/-/node12-1.0.11.tgz#ee3def1f27d9ed66dac6e46a295cffb0152e058d" + integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== + + "@tsconfig/node14@^1.0.0": + version "1.0.3" + resolved "https://registry.yarnpkg.com/@tsconfig/node14/-/node14-1.0.3.tgz#e4386316284f00b98435bf40f72f75a09dabf6c1" + integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== + + "@tsconfig/node16@^1.0.2": + version "1.0.4" + resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.4.tgz#0b92dcc0cc1c81f6f306a381f28e31b1a56536e9" + integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== + + acorn-walk@^8.1.1: + version "8.3.0" + resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.3.0.tgz#2097665af50fd0cf7a2dfccd2b9368964e66540f" + integrity sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA== + + acorn@^8.4.1: + version "8.11.2" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.11.2.tgz#ca0d78b51895be5390a5903c5b3bdcdaf78ae40b" + integrity sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w== + + arg@^4.1.0: + version "4.1.3" + resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" + integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== + + create-require@^1.1.0: + version "1.1.1" + resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" + integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== + + diff@^4.0.1: + version "4.0.2" + resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + + make-error@^1.1.1: + version "1.3.6" + resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" + integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== + + onnxruntime-common@~1.16.2: + version "1.16.2" + resolved "https://registry.yarnpkg.com/onnxruntime-common/-/onnxruntime-common-1.16.2.tgz#bfd0d60406e5842185a1be0962e645ebd578ec97" + integrity sha512-S2/wPoW2uaq5WzpStS6XKOsy8EvKZOOdpzq++HpIV6XZYl0EIfoWBV/Pi5PWcJPFBcu7Rkopo/oPk9IbD9qRlw== + + onnxruntime-node@^1.16.2: + version "1.16.2" + resolved "https://registry.yarnpkg.com/onnxruntime-node/-/onnxruntime-node-1.16.2.tgz#54e9aa27f5e85dae9e02b43eb09e356ff586844e" + integrity sha512-Qe/Fjx2n5Tlfm++RP/IHAmHrXaXoP75PK9p8XrDf6wI59Jk5ypL5F/bNH7lV3gOT8XIsjJmCBC2sfCVuivz1eQ== + dependencies: + onnxruntime-common "~1.16.2" + + ts-node@^10.9.1: + version "10.9.1" + resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.1.tgz#e73de9102958af9e1f0b168a6ff320e25adcff4b" + integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw== + dependencies: + "@cspotcode/source-map-support" "^0.8.0" + "@tsconfig/node10" "^1.0.7" + "@tsconfig/node12" "^1.0.7" + "@tsconfig/node14" "^1.0.0" + "@tsconfig/node16" "^1.0.2" + acorn "^8.4.1" + acorn-walk "^8.1.1" + arg "^4.1.0" + create-require "^1.1.0" + diff "^4.0.1" + make-error "^1.1.1" + v8-compile-cache-lib "^3.0.1" + yn "3.1.1" + + v8-compile-cache-lib@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" + integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== + + yn@3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50" + integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== diff --git a/runexamples/node/yarn.lock b/runexamples/node/yarn.lock new file mode 100644 index 0000000..587b51b --- /dev/null +++ b/runexamples/node/yarn.lock @@ -0,0 +1,136 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@cspotcode/source-map-support@^0.8.0": + version "0.8.1" + resolved "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz" + integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== + dependencies: + "@jridgewell/trace-mapping" "0.3.9" + +"@jridgewell/resolve-uri@^3.0.3": + version "3.1.1" + resolved "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz" + integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== + +"@jridgewell/sourcemap-codec@^1.4.10": + version "1.4.15" + resolved "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz" + integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== + +"@jridgewell/trace-mapping@0.3.9": + version "0.3.9" + resolved "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz" + integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== + dependencies: + "@jridgewell/resolve-uri" "^3.0.3" + "@jridgewell/sourcemap-codec" "^1.4.10" + +"@tsconfig/node10@^1.0.7": + version "1.0.9" + resolved "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz" + integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA== + +"@tsconfig/node12@^1.0.7": + version "1.0.11" + resolved "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz" + integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== + +"@tsconfig/node14@^1.0.0": + version "1.0.3" + resolved "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz" + integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== + +"@tsconfig/node16@^1.0.2": + version "1.0.4" + resolved "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz" + integrity sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA== + +"@types/node@^20.9.0": + version "20.9.0" + resolved "https://registry.yarnpkg.com/@types/node/-/node-20.9.0.tgz#bfcdc230583aeb891cf51e73cfdaacdd8deae298" + integrity sha512-nekiGu2NDb1BcVofVcEKMIwzlx4NjHlcjhoxxKBNLtz15Y1z7MYf549DFvkHSId02Ax6kGwWntIBPC3l/JZcmw== + dependencies: + undici-types "~5.26.4" + +acorn-walk@^8.1.1: + version "8.3.0" + resolved "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.0.tgz" + integrity sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA== + +acorn@^8.4.1: + version "8.11.2" + resolved "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz" + integrity sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w== + +arg@^4.1.0: + version "4.1.3" + resolved "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz" + integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== + +create-require@^1.1.0: + version "1.1.1" + resolved "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz" + integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== + +diff@^4.0.1: + version "4.0.2" + resolved "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz" + integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== + +fs@^0.0.1-security: + version "0.0.1-security" + resolved "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz" + integrity sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w== + +make-error@^1.1.1: + version "1.3.6" + resolved "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz" + integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== + +onnxruntime-common@^1.16.2, onnxruntime-common@~1.16.2: + version "1.16.2" + resolved "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.16.2.tgz" + integrity sha512-S2/wPoW2uaq5WzpStS6XKOsy8EvKZOOdpzq++HpIV6XZYl0EIfoWBV/Pi5PWcJPFBcu7Rkopo/oPk9IbD9qRlw== + +onnxruntime-node@^1.16.2: + version "1.16.2" + resolved "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.16.2.tgz" + integrity sha512-Qe/Fjx2n5Tlfm++RP/IHAmHrXaXoP75PK9p8XrDf6wI59Jk5ypL5F/bNH7lV3gOT8XIsjJmCBC2sfCVuivz1eQ== + dependencies: + onnxruntime-common "~1.16.2" + +ts-node@^10.9.1: + version "10.9.1" + resolved "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz" + integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw== + dependencies: + "@cspotcode/source-map-support" "^0.8.0" + "@tsconfig/node10" "^1.0.7" + "@tsconfig/node12" "^1.0.7" + "@tsconfig/node14" "^1.0.0" + "@tsconfig/node16" "^1.0.2" + acorn "^8.4.1" + acorn-walk "^8.1.1" + arg "^4.1.0" + create-require "^1.1.0" + diff "^4.0.1" + make-error "^1.1.1" + v8-compile-cache-lib "^3.0.1" + yn "3.1.1" + +undici-types@~5.26.4: + version "5.26.5" + resolved "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz" + integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA== + +v8-compile-cache-lib@^3.0.1: + version "3.0.1" + resolved "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz" + integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== + +yn@3.1.1: + version "3.1.1" + resolved "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz" + integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== diff --git a/test.py b/test.py index 2eb181d..9a65fbf 100644 --- a/test.py +++ b/test.py @@ -1,9 +1,29 @@ +import onnxruntime as rt +# register custom op for domain recursal.rwkv -def initONNXFile(path, useAllAvailableProviders=False): - import onnxruntime as rt +import onnx + + + +def initONNXFile(path, STREAMS, useAllAvailableProviders=False): + # session execution provider options sess_options = rt.SessionOptions() + + # load onnx graph and check for wkv5 nodes + graph = onnx.load(path,load_external_data=False).graph + + nodes = graph.node + # print(nodes) + + # check if wkv5 nodes are present + if not any([x.op_type == "wkv5" for x in nodes]): + print("No wkv5 nodes found in graph, skipping custom op registration") + else: + + from customoptools.customop import _get_library_path + sess_options.register_custom_ops_library(_get_library_path()) # sess_options.enable_profiling = True print(rt.get_available_providers()) @@ -18,6 +38,8 @@ def initONNXFile(path, useAllAvailableProviders=False): sess_options.execution_mode = rt.ExecutionMode.ORT_PARALLEL sess_options.graph_optimization_level = rt.GraphOptimizationLevel.ORT_ENABLE_BASIC sess_options.add_session_config_entry("session.intra_op.allow_spinning", "1") + + sess = rt.InferenceSession( path, sess_options, providers=providers) @@ -26,10 +48,15 @@ def initONNXFile(path, useAllAvailableProviders=False): } - embed = int(path.split("_")[2].split(".")[0]) - layers = int(path.split("_")[1]) + embed = sess.get_inputs()[1].shape[-1] + layers = (sess.get_inputs().__len__()-1)//3 typenum = sess.get_inputs()[1].type - print(typenum, embed, layers) + heads = sess.get_inputs()[layers*2+1].shape[1] + print("HEADS: ", heads) + print("LAYERS: ", layers) + print("EMBED: ", embed) + print("TYPE: ", typenum) + import numpy as np if typenum == "tensor(float)": @@ -54,7 +81,7 @@ def forward(selff, xi, statei, statei2): # print(output_names) # create input dict - inputs[input_names[0]] = np.array([xi], dtype=np.int32) + inputs[input_names[0]] = np.array(xi, dtype=np.int32) for i in range(len(input_names)-1): # print(input_names[i+1]) if "wkv" in input_names[i+1]: @@ -71,8 +98,11 @@ def forward(selff, xi, statei, statei2): model = InterOp() # emptyState = [] - emptyState = np.array(([[0.01]*embed, [0.01]*embed])*layers, typenum) - emptyState2 = np.array(([[[[0.01]*64]*64]*40])*layers, typenum) + + emptyState = np.zeros((layers*2,STREAMS,embed), dtype=typenum) + emptyState2 = np.zeros((layers,STREAMS,heads,embed//heads,embed//heads), dtype=typenum) + # emptyState = np.array(([[[0.01]*embed]*STREAMS, STREAMS*[[0.01]*embed]])*layers, typenum) + # emptyState2 = np.array(([[[[[0.01]*64]*64]*32]*STREAMS])*layers, typenum) print (emptyState.shape) print (emptyState2.shape) @@ -104,25 +134,31 @@ def npsample(ozut, temp: float = 1.0, top_p_usual: float = 0.8) -> int: probs = probs / np.sum(probs, axis=0) mout = np.random.choice(a=len(probs), p=probs) return mout +# Example usage: import inquirer # get all .onnx files in current directory import os files = [f for f in os.listdir('.') if os.path.isfile(f)] files = [f for f in files if f.endswith(".onnx") or f.endswith(".ort")] -model, state, state2 = initONNXFile(inquirer.list_input("Select model", choices=files)) from tokenizer import world as tokenizer +STREAMS = 8 +model, state, state2 = initONNXFile(inquirer.list_input("Select model", choices=files), STREAMS) + +prompt = STREAMS * [tokenizer.encode("### Instruction:\nPlease write a short story of a man defeating a two headed dragon\n### Result\n")] -prompt = tokenizer.encode("### Instruction:\nPlease write a short story of a man defeating a two headed dragon###Result\n") +print(prompt.__len__()) +# 3b is 2.5 tokens pers econd with 32 streams = 64 + 32 = 96 tokens per second import tqdm -for token in tqdm.tqdm(prompt[:-1]): - logits, state, state2 = model.forward(token,state, state2) +for tokennum in tqdm.tqdm(range(prompt[0].__len__()-1)): + logits, state, state2 = model.forward([prompt[i][tokennum] for i in range(STREAMS)],state, state2) print("Loaded prompt.") - +import numpy as np for i in range(1000): - logits, state, state2 = model.forward(prompt[-1],state, state2) - prompt = prompt+[npsample(logits)] - print(tokenizer.decode(prompt[-1:]),end="", flush=True) + logits, state, state2 = model.forward([prompt[i][-1] for i in range(STREAMS)],state, state2) + prompt = [prompt[i]+[np.argmax(logits[i])] for i in range(STREAMS)] + + print(tokenizer.decode(prompt[2][-1:]), end="", flush=True) print(tokenizer.decode(prompt))