builtin_functions.q

The functions listed in this document are implemented in the Quasar runtime library (Quasar.exe).  Hence, the source code of these functions is not available.

Summary
builtin_functions.qThe functions listed in this document are implemented in the Quasar runtime library (Quasar.exe).
built-in constants
mathematical functionsMathematical functions that can be used in both device/kernel functions or host code.
absComputes the absolute value of a real-valued number/matrix, the modulus of a complex number/matrix.
asinComputes the arcus sine of a real-valued number/matrix.
acosComputes the arcus cosine of a real-valued number/matrix
atanComputes the arcus tangent of a real-valued number/matrix.
atan2Computes the arcus tangent of a real-valued number/matrix with two parameters Returns the principal value of the arc tangent of y/x, expressed in radians.
ceilReturns the nearest integer not less than x
roundRounds to the nearest integer
cosComputes the cosine of x, where x is specified in radials
sinComputes the sine of x, where x is specified in radials
expComputes e^x
exp2Computes 2^x
floorReturns the nearest integer not greater than x.
modComputes the modulus of x after division by a
fracComputes the fractional part of x such that x = floor(x) + frac(x)
logComputes the natural logarithm of x
log2Computes the logarithm of x base 2
log10Computes the logarithm of x base 10
maxComputes the maximum value of all elements x.
minComputes the minimum value of all elements x.
powReturns x to the power a.
saturateSaturates the values of x to the range [0,1]
signReturns +1 if x is positive, 0 if x == 0, and -1 if x is negative.
sqrtReturns the square root of x.
tanComputes the tangent of x, where x is specified in radials
conjReturns the conjugate of a complex-valued number (or matrix)
floatConverts an integer number to floating point
intConverts a floating point number to integer
isinfReturns 1 if x is infinite, 0 otherwise
isfiniteReturns 1 if x is finite, 0 otherwise
isnanReturns 1 if x is NaN, 0 otherwise
periodizePeriodic extension of input coordinate between [0,p[.
mirror_extMirror extension of the input coordinate between [0,p[
clampClamps the input coordinate between [0,p], i.e.
factorialReturns x!
discrete Fourier transforms
fft1Computes the 1D Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.
fft2Computes the 2D Discrete Fourier Transform (DFT) of x along the first (0) and second (1) dimension of x
fft3Computes the 3D Discrete Fourier Transform (DFT) of x.
ifft1Computes the 1D inverse Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.
ifft2Computes the 2D inverse Discrete Fourier Transform (DFT) of x along the first (0) and second (1) dimension of x
ifft3Computes the 3D inverse Discrete Fourier Transform (DFT) of x.
matrix processing/utility functions
numelReturns the number of elements in x
sizeReturns a vector of length 3 with the size of x
sizeReturns the size of x along dimension y (y=0,1,2)
complexConverts a real-valued number/matrix to a complex-valued number/matrix
complexReturns a complex-valued number/matrix, based on the specified real/imaginary parts
realReturns the real part of a complex number / matrix
transposeTransposes a matrix.
imagReturns the imaginary part of a complex number / matrix
sumComputes the sum of all elements of a matrix (along all dimensions)
sumComputes the sum of all elements of a matrix, along the specified dimension d=0,1,2
cumsumComputes the cumulative sum of all elements of a matrix (along the rows)
prodComputes the product of all elements of a matrix (along all dimensions)
prodComputes the product of all elements of a matrix, along the specified dimension d=0,1,2
cumprodComputes the cumulative product of all elements of a matrix (along the rows)
linspaceReturns a linearly spaced vector from a (inclusive) to b (inclusive), containing c elements.
copyReturns a one-level deep copy of the specified variable.
eyeCreates an n x n identity matrix
repmatRepeats the matrix ‘dims’ times.
reshapeChanges the dimensions of a matrix, by reordering the elements of the matrix.
shuffledimsPerforms a permutation on the dimensions of a matrix
matrix creation/allocation
sharedAllocates uninitialized shared memory according to the dimensions x.
shared_zerosAllocates zero-initialized shared memory according to the dimensions x.
csharedAllocates uninitialized complex-valued shared memory according to the dimensions x.
cshared_zerosAllocates zero-initialized complex-valued shared memory according to the dimensions x.
zerosCreates a zero-initialized real-valued data vector of length a
zerosCreates a zero-initialized real-valued data matrix of dimensions a x b
zerosCreates a zero-initialized real-valued data cube of dimensions a x b x c
onesCreates a one-initialized real-valued data vector of length a
onesCreates a one-initialized real-valued data matrix of dimensions a x b
onesCreates a one-initialized real-valued data vector of dimensions a x b x c
uninitCreates an uninitialized real-valued data vector of length a
uninitCreates a uninitialized real-valued data matrix of dimensions a x b
uninitCreates a uninitialized real-valued data vector of dimensions a x b x c
czerosCreates a zero-initialized complex-valued data vector of length a
czerosCreates a zero-initialized complex-valued data matrix of dimensions a x b
czerosCreates a zero-initialized complex-valued data matrix of dimensions a x b x c
czerosCreates a uninitialized complex-valued data vector of length a
cuninitCreates a uninitialized complex-valued data matrix of dimensions a x b
czerosCreates a uninitialized complex-valued data matrix of dimensions a x b x c
random number generators
randCreates a uniformly distributed data vector of length a (values are in the range [0,1[)
randCreates a uniformly distributed data vector of dimensions a x b (values are in the range [0,1[)
randCreates a uniformly distributed data vector of dimensions a x b x c (values are in the range [0,1[)
randnCreates a Gaussian distributed data vector of length a, with mean=0 and standard deviation=1
randnCreates a Gaussian distributed data vector of dimensions a x b, with mean=0 and standard deviation=1
randnCreates a Gaussian distributed data vector of dimensions a x b x c, with mean=0 and standard deviation=1
cell matrix functions
cellCreates an empty cell vector of length a
cellCreates an empty cell matrix of dimensions a x b
cellCreates an empty cell vector of dimensions a x b x c
image I/O
imreadReads an image input file.
imwriteSaves an image as a file
imwriteSaves an image as a file
general utility functions
typeReturns the type of an object
typeChecks whether the variable ‘x’ is of type ‘y’
ticSet a timer to be read by the next call to toc.
tocPrint and return the time elapsed since the last tic
objectCreates an empty untyped object, which can be used to store data.
printPrints text to the console
errorGenerates an error with the specified message
assertAsserts that x is true, and generates an error otherwise (if x is false)
evalDynamic expression evaluation
pauseDelays the program for “delay” milliseconds
string parsing/composition functions
sprintfC-like string formatting
sscanfParses a string using C-style formatting rules
printfC-like printing to the console
strcatConcatenates strings
File I/OFile input/output routines
fopenOpens the specified file for reading or writing.
fcloseCloses the specified file (that was previously opened using fopen)
freadReads binary data from a file (opened in binary mode)
fwriteWrites binary data to a file (opened in binary mode)
fprintPrints text to a file (opened in text mode)
fprintfPrints C-style formatted text to a file (opened in text mode)
fscanfReads C-style formatted text from a file (opened in text mode)
dirLists all files in a given directory according to the specification
saveSaves variables to a file
loadLoads variables from a file
parallel processing functions
parallel_doLauches a given kernel function fn in parallel to every element of a certain matrix
serial_doLauches a given kernel function fn in serial to every element of a certain matrix
max_block_sizeReturns the maximum block size that can be used for the function parallel_do.
visualization functions
dispShows a visualizer window for matrices
holdRetain current graph when adding new graphs (plot, scatter or imshow function).
sync_framerateSets the synchronization framerate for the imshow function, in number of frames displayed per second.
plotData visualization function
scatterData visualization function
titleModifies the title of the previous plot
xlabelModifies the label of the x-axis of the previous plot
ylabelModifies the label of the y-axis of the previous plot
xlimModifies the range of the x-axis of the previous plot
ylimModifies the range of the y-axis of the previous plot
imshowImage visualization function.
imshowImage visualization function.
formOpens a new window

built-in constants

pithe constant pi
epsthe machine precision
truethe Boolean value true
falsethe Boolean value false

mathematical functions

Mathematical functions that can be used in both device/kernel functions or host code.

abs

Computes the absolute value of a real-valued number/matrix, the modulus of a complex number/matrix.

function y = abs(x)

asin

Computes the arcus sine of a real-valued number/matrix.

Returns

The result is expressed in radials.

function y = asin(x)

acos

Computes the arcus cosine of a real-valued number/matrix

Returns

The result is expressed in radials.

function y = acos(x)

atan

Computes the arcus tangent of a real-valued number/matrix.

Returns

The result is expressed in radials.

function y = atan(x)

atan2

Computes the arcus tangent of a real-valued number/matrix with two parameters Returns the principal value of the arc tangent of y/x, expressed in radians.

Returns

The result is expressed in radials.

function z = atan2(y,x)

ceil

Returns the nearest integer not less than x

function y = ceil(x)

round

Rounds to the nearest integer

function y = round(x)

cos

Computes the cosine of x, where x is specified in radials

function y = cos(x)

sin

Computes the sine of x, where x is specified in radials

function y = sin(x)

exp

Computes e^x

function y = exp(x)

exp2

Computes 2^x

function y = exp(x)

floor

Returns the nearest integer not greater than x.

function y = floor(x)

mod

Computes the modulus of x after division by a

function y = mod(x, a)

See also

periodize

frac

Computes the fractional part of x such that x = floor(x) + frac(x)

function y = frac(x)

log

Computes the natural logarithm of x

function y = log(x)

log2

Computes the logarithm of x base 2

function y = log(x)

log10

Computes the logarithm of x base 10

function y = log10(x)

max

Computes the maximum value of all elements x.  The result is a scalar number.

function y = max(x)

min

Computes the minimum value of all elements x.  The result is a scalar number.

function y = min(x)

pow

Returns x to the power a.  Note that this is equivalent to x^a (which is also legal syntax in Quasar)

function y = pow(x, a)

saturate

Saturates the values of x to the range [0,1]

function y = saturate(x)

sign

Returns +1 if x is positive, 0 if x == 0, and -1 if x is negative.

function y = sign(x)

sqrt

Returns the square root of x.

Returns

  • a real-valued matrix if x is real-valued
  • a complex-valued matrix if x is complex-valued
function y = sqrt(x)

tan

Computes the tangent of x, where x is specified in radials

function y = tan(x) builtin

conj

Returns the conjugate of a complex-valued number (or matrix)

function y = conj(x)

float

Converts an integer number to floating point

function y = float(x)

int

Converts a floating point number to integer

function y = int(x)

isinf

Returns 1 if x is infinite, 0 otherwise

function y = isinf(x) builtin

isfinite

Returns 1 if x is finite, 0 otherwise

function y = isfinite(x) builtin

isnan

Returns 1 if x is NaN, 0 otherwise

function y = isnan(x) builtin

periodize

Periodic extension of input coordinate between [0,p[.

function y = periodize(x, p)

Notes

  • For positive numbers this is equivalent to the mod function.
  • For negative numbers, the result is guaranteed to be positive.

Example

mod(-4.5,4) = -0.5
periodize(-4.5,4) = -3.5

See also

mod

mirror_ext

Mirror extension of the input coordinate between [0,p[

function y = mirror_ext(x, p)

clamp

Clamps the input coordinate between [0,p], i.e. clamp(x, p) = max(0, min(p, x)).  This function can be used to make a rectangular function.

function y = clamp(x, p)

factorial

Returns x!

function y = factorial(x)

discrete Fourier transforms

fft1

Computes the 1D Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.

function y = fft1(x)

Parameters

xa real-valued or complex-valued input matrix.

Notes

The DFT is implemented using:

  • CuFFT for the CUDA computation engine
  • FFTW for the CPU computation engine

See also

fft2, fft3

fft2

Computes the 2D Discrete Fourier Transform (DFT) of x along the first (0) and second (1) dimension of x

function y = fft2(x)

Parameters

xa real-valued or complex-valued input matrix.

Notes

The DFT is implemented using:

  • CuFFT for the CUDA computation engine
  • FFTW for the CPU computation engine

See also

fft1, fft3

fft3

Computes the 3D Discrete Fourier Transform (DFT) of x.

function y = fft3(x)

Parameters

xa real-valued or complex-valued input matrix.

Notes

The DFT is implemented using:

  • CuFFT for the CUDA computation engine
  • FFTW for the CPU computation engine

See also

fft1, fft2

ifft1

Computes the 1D inverse Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.

function y = ifft1(x)

Parameters

xa complex-valued input matrix.

See also

ifft1

ifft2

Computes the 2D inverse Discrete Fourier Transform (DFT) of x along the first (0) and second (1) dimension of x

function y = ifft2(x)

Parameters

xa complex-valued input matrix.

See also

fft2

ifft3

Computes the 3D inverse Discrete Fourier Transform (DFT) of x.

function y = ifft3(x)

Parameters

xa complex-valued input matrix.

See also

ifft3

matrix processing/utility functions

numel

Returns the number of elements in x

For matrices, numel(x) = prod(size(x))

function y = numel(x)

size

Returns a vector of length 3 with the size of x

function y = size(x)

size

Returns the size of x along dimension y (y=0,1,2)

function z = size(x, y)

complex

Converts a real-valued number/matrix to a complex-valued number/matrix

function y = complex(re)

complex

Returns a complex-valued number/matrix, based on the specified real/imaginary parts

function y = complex(re,im)

real

Returns the real part of a complex number / matrix

function y = real(c)

transpose

Transposes a matrix.

function y = transpose(r)

Notes

See also

herm_transpose

imag

Returns the imaginary part of a complex number / matrix

function y = imag(c)

sum

Computes the sum of all elements of a matrix (along all dimensions)

function y = sum(c)

sum

Computes the sum of all elements of a matrix, along the specified dimension d=0,1,2

function y = sum(c)

cumsum

Computes the cumulative sum of all elements of a matrix (along the rows)

function y = cumsum(c)

prod

Computes the product of all elements of a matrix (along all dimensions)

function y = prod(c)

prod

Computes the product of all elements of a matrix, along the specified dimension d=0,1,2

function y = prod(c)

cumprod

Computes the cumulative product of all elements of a matrix (along the rows)

function y = cumprod(c)

linspace

Returns a linearly spaced vector from a (inclusive) to b (inclusive), containing c elements.

function y = linspace(a,b,c)

copy

Returns a one-level deep copy of the specified variable.  This is useful for creating e.g. a temporary copy of a matrix that can be changed without affecting the original matrix.  Note: to copy nested objects (such as cell matrices), it can be useful to use the function <deepcopy>

function y = copy(x)

See also

<deepcopy>

eye

Creates an n x n identity matrix

function y = eye(n)

Parameters

nsize (number of rows/cols) of the output matrix

repmat

Repeats the matrix ‘dims’ times.

function y = repmat(a,dims)

Parameters

athe matrix to repeat
dimsthe number of times to repeat in each dimension

reshape

Changes the dimensions of a matrix, by reordering the elements of the matrix.  Note that Quasar uses a row-major ordering of the elements by default.

function y = reshape(a,dims)

Parameters

athe matrix to reshape
dimsthe new dimensions of the matrix.  Note that the number of elements may not change, i.e. it is required that prod(dims) = numel(a)

shuffledims

Performs a permutation on the dimensions of a matrix

function y = shuffledims(a,dims)

Parameters

athe matrix to change
dimsthe new order of the dimensions.  For example:
  • dims = [0,1,2] preserves the dimensions of the input
  • dims = [1,0,2] swaps the first and second dimensions (transposition, while keeping the third dimension)
  • dims = [2,1,0] reverses the dimensions of the matrix

matrix creation/allocation

shared

Allocates uninitialized shared memory according to the dimensions x.

function y = shared(x)

Notes

  • The function shared can only be called from kernel/device functions.
  • The amount of shared memory is restricted to about 32K.  When the maximum of shared memory is exceeded, an error will be generated.

See also

shared_zeros, cshared_zeros

shared_zeros

Allocates zero-initialized shared memory according to the dimensions x.  It is important to use the keyword ‘syncthreads’ because the zero- initialization operation is distributed along all threads.  The ‘syncthreads’ keyword then ensures that all threads see a fully zero-initialized copy of y.

function y = shared_zeros(x)
syncthreads

Notes

  • The function shared_zeros can only be called from kernel/device functions.
  • The amount of shared memory is restricted to about 32K.  When the maximum of shared memory is exceeded, an error will be generated.

See also

shared

cshared

Allocates uninitialized complex-valued shared memory according to the dimensions x.

function y = cshared(x)
function y = complex(shared(x))  % through reductions

Notes

  • The function cshared can only be called from kernel/device functions.
  • The amount of shared memory is restricted to about 32K.  When the maximum of shared memory is exceeded, an error will be generated.

See also

shared, cshared_zeros

cshared_zeros

Allocates zero-initialized complex-valued shared memory according to the dimensions x.  It is important to use the keyword ‘syncthreads’ because the zero- initialization operation is distributed along all threads.  The ‘syncthreads’ keyword then ensures that all threads see a fully zero-initialized copy of y.

function y = cshared_zeros(x)
function y = complex(shared_zeros(x))  % through reductions
syncthreads

Notes

  • The function cshared_zeros can only be called from kernel/device functions.
  • The amount of shared memory is restricted to about 32K.  When the maximum of shared memory is exceeded, an error will be generated.

See also

shared

zeros

Creates a zero-initialized real-valued data vector of length a

function y = zeros(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

zeros

Creates a zero-initialized real-valued data matrix of dimensions a x b

function y = zeros(a,b)

zeros

Creates a zero-initialized real-valued data cube of dimensions a x b x c

function y = zeros(a,b,c)

ones

Creates a one-initialized real-valued data vector of length a

function y = ones(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

ones

Creates a one-initialized real-valued data matrix of dimensions a x b

function y = ones(a,b)

ones

Creates a one-initialized real-valued data vector of dimensions a x b x c

function y = ones(a,b,c)

uninit

Creates an uninitialized real-valued data vector of length a

function y = uninit(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

uninit

Creates a uninitialized real-valued data matrix of dimensions a x b

function y = uninit(a,b)

uninit

Creates a uninitialized real-valued data vector of dimensions a x b x c

y = uninit(a,b,c)

czeros

Creates a zero-initialized complex-valued data vector of length a

function y = czeros(a,b)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

czeros

Creates a zero-initialized complex-valued data matrix of dimensions a x b

function y = czeros(a,b)

czeros

Creates a zero-initialized complex-valued data matrix of dimensions a x b x c

function y = czeros(a,b,c)

czeros

Creates a uninitialized complex-valued data vector of length a

function y = czeros(a,b)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

cuninit

Creates a uninitialized complex-valued data matrix of dimensions a x b

function y = czeros(a,b)

czeros

Creates a uninitialized complex-valued data matrix of dimensions a x b x c

function y = cuninit(a,b,c)

random number generators

rand

Creates a uniformly distributed data vector of length a (values are in the range [0,1[)

function y = rand(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

rand

Creates a uniformly distributed data vector of dimensions a x b (values are in the range [0,1[)

function y = rand(a,b)

rand

Creates a uniformly distributed data vector of dimensions a x b x c (values are in the range [0,1[)

function y = rand(a,b,c)

randn

Creates a Gaussian distributed data vector of length a, with mean=0 and standard deviation=1

function y = randn(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

randn

Creates a Gaussian distributed data vector of dimensions a x b, with mean=0 and standard deviation=1

function y = randn(a,b)

randn

Creates a Gaussian distributed data vector of dimensions a x b x c, with mean=0 and standard deviation=1

function y = randn(a,b,c)

cell matrix functions

cell

Creates an empty cell vector of length a

function y = cell(a)

Parameters

aeither a scalar value (creating a vector), or a vector of maximally length 3 (to create a matrix or cube)

cell

Creates an empty cell matrix of dimensions a x b

function y = cell(a, b)

cell

Creates an empty cell vector of dimensions a x b x c

function y = cell(a, b, c)

image I/O

imread

Reads an image input file.

function y = imread(filename)

Supported file formats are: BMP, GIF, JPEG, EXIF, PNG, TIFF.  The output y is in the range [0-255] for 8-bit images, and in the range [0-65535] for 16-bit images.

Parameters

filenamethe filename of the image to open

See also

imread

imwrite

Saves an image as a file

function y = imwrite(filename,data)

Parameters

filenamethe output file name
datathe data to save

Supported file formats are: BMP, GIF, JPEG, EXIF, PNG, TIFF.  The input ‘data’ is in the range [0-255] for 8-bit images, and in the range [0-65535] for 16-bit images.  Values outside this range are automatically clipped

See also

imread

imwrite

Saves an image as a file

function y = imwrite(filename,data,range)

Parameters

filenamethe output file name
datathe data to save
rangethe range of the data.  The data will be automatically scaled using the specified range to the default ranges (i.e.  [0-255] for 8-bit images, and [0-65535] for 16-bit images).

Supported file formats are: BMP, GIF, JPEG, EXIF, PNG, TIFF.

See also

imread

general utility functions

type

Returns the type of an object

function y = type(x)

type

Checks whether the variable ‘x’ is of type ‘y’

function z = type(x,y : string)

tic

Set a timer to be read by the next call to toc.

function [] = tic()

See also

tic

toc

Print and return the time elapsed since the last tic

function y = toc(varargs)

Parameters

varargsthe message to print to the console
ythe number of seconds passed since the last tic

See also

toc

object

Creates an empty untyped object, which can be used to store data.

function y = object()

print

Prints text to the console

function [] = print(varargs)

error

Generates an error with the specified message

function [] = error(varargs)

assert

Asserts that x is true, and generates an error otherwise (if x is false)

function [] = assert(x)

Parameters

xthe condition to test.

Notes

  • The function “assert” may trigger a compiler error, if the compiler is already sure that x will always be false.
  • The function “assert” may also be used to give certain hints to the compiler, for example, about the type of a given variable.

Example

function y = do_something(x : ??)
    assert(type(x, "vec[int]"))
end

eval

Dynamic expression evaluation

function y = eval(expr : string)

String expressions can be parsed and evaluated at runtime using the eval(.) function.  For example

val = eval("(x) -> 3*eye(x)")(8)

Here, the eval function parses the string expression “(x) -> 3*eye(x)” and returns a corresponding lambda expression.  This lambda expression can then be evaluated at the same speed as “regular” lambda expressions.  This can be useful for simulations (e.g. passing functions through the command line).

pause

Delays the program for “delay” milliseconds

function [] = pause(delay)

Parameters

delaythe delay time, in milliseconds

string parsing/composition functions

sprintf

C-like string formatting

function y = sprintf(text, varargs)

See also

sscanf

sscanf

Parses a string using C-style formatting rules

function [varargs] = sscanf(text, fmt)

Parameters

textthe text to parse
fmta C-style format specifier (e.g.  “%s %d %c”)

Returns

A cell array with the results.  It is possible to use this cell array in a multiple-variable assignment.  For example:

[x,y,z] = sscanf("[0.2,0.5,0.8], "[%f,%d,%f]")

See also

sprintf

printf

C-like printing to the console

function [] = printf(text, varargs)

strcat

Concatenates strings

function y = strcat(varargs)

File I/O

File input/output routines

fopen

Opens the specified file for reading or writing.  The file handle must be closed using fclose

function file_handle = fopen(filename : string, options)

Parameters

filenamethe path of the file to open
optionsa string containing the options for loading:
  • ”w”: open for writing
  • ”r”: open for reading
  • ”a”: open for appending
  • ”b”: binary mode (for reading/writing binary data)
  • ”t”: text mode (for reading/writing text)

See also

fclose, fread, fwrite, fprint, fprintf

fclose

Closes the specified file (that was previously opened using fopen)

function [] = fclose(file_handle)

Parameters

file_handlethe handle of the file to close.

See also

fopen, fread, fwrite

fread

Reads binary data from a file (opened in binary mode)

function y = fread(file_handle, dims, typestring : string)

Parameters

file_handlethe handle of the file (obtained using fopen) to read from
dimsthe dimensions of the data to read
typestringthe data type to read.  Supported typestrings are: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64

Returns

a matrix of dimensions ‘dims’.  Note that row-major order is used in Quasar.  In case column-major order is desired, the function shuffledims can be used to change the order.

See also

fopen, fwrite, fclose

fwrite

Writes binary data to a file (opened in binary mode)

function y = fwrite(file_handle, value, typestring : string)

Parameters

file_handlethe handle of the file (obtained using fopen) to write to
valuethe data to write.  Note that row-major order is used in Quasar.  In case column-major order is desired, the function shuffledims can be used to change the order.
typestringthe data type to read.  Supported typestrings are: int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64

See also

fopen, fread, fclose

fprint

Prints text to a file (opened in text mode)

function [] = fprint(file_handle, varargs)

See also

fopen, fprintf, fclose

fprintf

Prints C-style formatted text to a file (opened in text mode)

function [] = fprintf(file_handle, fmt, varargs)

See also

fopen, fprint, fclose

fscanf

Reads C-style formatted text from a file (opened in text mode)

function [varargs] = fscanf(file_handle, fmt)

Parameters

file_handlethe handle of the file (obtained using fopen) to read from
fmta C-style format specifier (e.g.  “%s %d %c”)

Returns

A cell array with the results.  It is possible to use this cell array in a multiple-variable assignment.  For example:

[x,y,z] = fscanf(handle, "[%f,%d,%f]")

See also

fopen, fprintf, fprint, fclose

dir

Lists all files in a given directory according to the specification

function list = dir(spec)

Parameters

specthe specification (e.g.  “.png;.tif”, “image_stack_*.png”)

save

Saves variables to a file

function [] = save(file_name : string, varargs) builtin

Notes

  • the function save can store Quasar objects of all types (including cell matrices, user defined types, objects with references).
  • a custom binary format is used for storing the data.  To save disk space, LZMA compression is used by default.

Example

save("out.dat",A,B,C)

See also

load

load

Loads variables from a file

function [varargs] = load(file_name : string)

Notes

  • The file needs to be created using the function ‘save’, otherwise an error will be generated
  • By default, the variables returned by the function ‘load’ are untyped, hampering compiler optimizations (because the compiler cannot determine the type of the variables).  To solve this problem, add explicit types to the output variables.  The variable types will then be checked at runtime, and the compiler can generate more optimal code.

Example

[A,B,C] = load("out.dat")
[A:scalar, B:cube, C:vec[cube]] = load("out.dat")

See also

save

parallel processing functions

parallel_do

Lauches a given kernel function fn in parallel to every element of a certain matrix

function [] = parallel_do(dim,varargs,fn : kernel_function)

A kernel function is a Quasar function with a special attribute kernel , that can be parallelized.  Kernel functions are launched in parallel on every element of a certain matrix, using the “parallel_do” built-in function.  The kernel attribute specifies that the function should be natively compiled for the targeted computation engine (e.g.  CUDA, CPU).  Consequently, kernel functions are considerably faster than regular functions, not only due to their parallelization.  As example, consider the following algorithm:

function [] = __kernel__ color_temperature(x : cube, y : cube,
   temp, cold : vec3, hot : vec3, pos : vec2)
   input = x[pos[0],pos[1],0..2]
   if temp<0
      output = lerp(input,cold,(-0.25)*temp)
   else
      output = lerp(input,hot,0.25*temp)
   endif
   y[pos[0],pos[1],0..2] = output
end
hot = [1.0,0.2,0.0]*255
cold = [0.3,0.4,1]*255
img_out = zeros(size(img_in))
parallel_do(size(img_out,0..1),img_in,img_out,temp,cold,hot,color_temperature)

The kernel function is launched on a grid of dimensions “ size(img_out,0..1)” using the parallel_do construct.  This means that every pixel in img_out will be addressed individually by parallel_do, and correspondingly the function color_temperature will be called for every pixel position.

For a kernel function, all arguments need to be explicitly typed.  Recall that untyped arguments (or arguments without type) in Quasar are denoted by ??.  Untyped arguments are not allowed because these arguments can not be mapped onto a device architecture.

Kernel functions differ from “regular” functions, in the sense that in addition to the standard data types, some special data types are allowed:

  • vecx - with x=1,2,varargs,16 corresponds to a vector of length x.
  • ivecx - with x=1,2,varargs,16 corresponds to an integer vector of length x.
  • cvecx - with x=1,2,varargs,16 corresponds to a complex-valued vector of length x.
  • int - integer data type

However, some datatypes can currently not be passed as arguments to kernel functions: cell matrices containing unknown types (??) and strings.  To pass cell matrices, use parametrized matrix types (vec[cube], mat[cube], mat[vec], etc., see [sec:Typing-system-full] ).  Device functions ( device ) possibly containing closure variables (see [sub:closures]), can also be passed.

For vectors of length \leq16, it is more efficient to use the dedicated datatypes vecx, ivecx, cvecx, with x=1,2,varargs,16 since they are treated in a special way (e.g. passed by value on the stack, SIMD instructions if the underlying C/C++ compiler supports them.).  Note that inside kernel functions, it is recommended to use integers instead of scalars (when possible).  This may yield a speed-up of about 30% using the CUDA computation engine.  When a scalar constant contains a decimal point (e.g., 1.2), the compiler will consider this constant to be a floating point number, otherwise it will be considered to be an integer.

Parameters

dimsvector of length 3.
fnthe kernel function to apply in parallel

Kernel function parameters

Note that a kernel function cannot have output arguments.  Instead, the return values should be written to the input arguments passed by reference, i.e. arguments of types vec, mat, cube, cvec, cmat, ccube.  There are some special arguments that can be defined in the kernel function declaration, but that do not need to be passed to parallel_do:

  • pos - (of type int, (i)vec1, (i)vec2, (i)vec3): the current position of the work item being processed.  Note that a “work item” can be either an individual pixel, or a “group of pixels” , depending on how you specify the “dimensions” argument.
  • blkpos - (of type int, (i)vec1, (i)vec2, (i)vec3): the current position within the block
  • blkidx - (of type int, (i)vec1, (i)vec2, (i)vec3): the block index
  • blkdim - (of type int, (i)vec1, (i)vec2, (i)vec3): the current dimensions a block (advanced users only, see [sub:Advanced-usage] ).  Internally, the data is processed on a block-by-block basis.  The dimensions of a block depend on the computation engine in use.  For example, for the CUDA computation engine (with CUDA compute capability 2.0), the block dimensions can be as large as 16x32 or 32x16.  For the CPU computation engine, the block dimensions will rather be 1x#num_processors.

The parallel_do function performs the following sequential program in parallel:

blkdim = choose_optimal_block_size(kernel_function)

for m=0..dimensions[0]-1
    for n=0..dimensions[1]-1
        for p=0..dimensions[2]-1
            pos = [m,n,p]
            blkpos = mod(pos, blkdim)
            blkidx = floor(pos/blkdim)
            kernel_function(inarg1, varargs, inargN, [pos], [blkpos], [blkidx], [blkdim])
        end
    end
end

Here, first optimal block dimensions (blkdim) for the given kernel function are being selected.  Then, kernel_function is run inside the three loops, prod(dimensions)=dimensions[0]\times dimensions[1] x dimensions[2] times.

Special modifiers are available for kernel function arguments.  The modifiers are specified using the apostrophe-symbol:

function [] = __kernel__ imfilter_kernel_nonsep_mirror_ext(y :
      cube'unchecked, x : cube'unchecked, mask : mat'unchecked'const,
      center : ivec2, pos : ivec3)

These modifiers specify how vector/matrix/cube elements are accessed, and in particular enable efficient boundary handling in image processing:

  • ’safe: the default access mode: disregards writes outside the data boundaries, reads outside the data boundaries evaluate to zero.
  • ’circular: performs circular boundary handling
  • ’mirror: mirrors when accessing outside the data boundaries.
  • ’unchecked (warning: dangerous usage - your computer will explode if not used properly): specifies no bounds checking on the input/output data.  In case of access outside the data boundaries, a runtime error will be generated (or the program may crash).  Specify this modifier in case you are sure your kernel/device function is 100% correct, and when you want to enjoy a modest extra code speedup.
  • ’checked: the opposite of ‘unchecked: generates an error when indices are out of the data boundaries.  Quasar will give information on which matrices are the prime suspect.

See also: serial_do

serial_do

Lauches a given kernel function fn in serial to every element of a certain matrix

function [] = serial_do(dim,varargs,fn : kernel_function)

The parameters of the serial_do function are exactly the same as those of parallel_do.  The main difference between serial_do and parallel_do is that the operations are performed sequentially rather than in parallel.  This is useful for algorithms that cannot be parallelized (or that are very difficult to parallelize).  Generally, the serial operations will be performed by the host CPU.

See also: parallel_do

max_block_size

Returns the maximum block size that can be used for the function parallel_do.

function y = max_block_size()
function y = max_block_size(sz)
function y = max_block_size(fn : kernel_function, sz)

Parameters

szthe upper bound for the size returned by max_block_size.  A vector of length 1, 2 or 3.
fnthe kernel function for which the maximum block size is determined.  Depending on the register usage (see below), the actual maximal block size can be lower than the maximal block size of the device.

The block size (blkdim) can be manually specified, through the function parallel_do.  ‘sz’ depends on the amount of shared memory you want to use within the kernel.  The function max_block_size computes the maximally allowed block size for the given kernel function.  Note that for:

  • The CUDA computation engine, the maximum block size is limited by the maximum number of threads per block.  For CUDA compute capability 2.0, we should have that the maximum number of elements <= 1024 . In practice, this number is even lower, due to register usage and other internal details.
  • For the CPU computation engine, the maximum block size is unlimited, unless synchronization (syncthreads) is used.  In this case, the block size is limited depending on the number of multi-processors in the system.  Note that the above behavior is handled transparently by the function max_block_size(.).  Hence one should always call max_block_size, to determine the maximal block size for a given kernel function.

visualization functions

disp

Shows a visualizer window for matrices

function [] = disp(x)

Parameters

xthe matrix for displaying

hold

Retain current graph when adding new graphs (plot, scatter or imshow function).  Note that a graph should already have been created when the function is called.

function success = hold(val : string)
hold("on")
hold("off")

Parameters

valeither “on” or “off”
successreturns TRUE if a graph is existing

Remarks

  • The hold(“on”) function provides a very simple means for generating and playing videos in Quasar.  The following example using the function sync_framerate illustrates how this can be done.
sync_framerate(25) % set frame rate to 25 frames/second
repeat
   frame = ... % generate a frame
   imshow(frame,[0,255])
until !hold("on")

sync_framerate

Sets the synchronization framerate for the imshow function, in number of frames displayed per second.  This function is useful when you want to display images at a given frame rate.

function [] = sync_framerate(fps : scalar)

Parameters

fpsthe number of frames per second

plot

Data visualization function

function [] = plot(varargs)

scatter

Data visualization function

function [] = scatter(varargs)

title

Modifies the title of the previous plot

function [] = plot(varargs)

xlabel

Modifies the label of the x-axis of the previous plot

function [] = xlabel(text : string)

ylabel

Modifies the label of the y-axis of the previous plot

function [] = ylabel(text : string)

xlim

Modifies the range of the x-axis of the previous plot

function [] = xlim(range)

ylim

Modifies the range of the y-axis of the previous plot

function [] = ylim(range)

imshow

Image visualization function.

Parameters

imgan image with range [0,255]
function [] = imshow(img)

imshow

Image visualization function.

Parameters

imgan image to display
rangethe range of the data.  The data will be automatically scaled to the range [0,255].
function [] = imshow(img, range)

form

Opens a new window

function y = form(varargs)
Opens the specified file for reading or writing.
Lauches a given kernel function fn in parallel to every element of a certain matrix
Data visualization function
Data visualization function
Image visualization function.
Periodic extension of input coordinate between [0,p[.
Computes the modulus of x after division by a
Computes the 2D Discrete Fourier Transform (DFT) of x along the first (0) and second (1) dimension of x
Computes the 3D Discrete Fourier Transform (DFT) of x.
Computes the 1D Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.
Computes the 1D inverse Discrete Fourier Transform (DFT) of x along the last dimension that has size != 1.
Computes the 3D inverse Discrete Fourier Transform (DFT) of x.
Hermitian transpose of a matrix
Allocates uninitialized shared memory according to the dimensions x.
Allocates zero-initialized shared memory according to the dimensions x.
Allocates zero-initialized complex-valued shared memory according to the dimensions x.
Allocates uninitialized complex-valued shared memory according to the dimensions x.
Reads an image input file.
Set a timer to be read by the next call to toc.
Print and return the time elapsed since the last tic
Parses a string using C-style formatting rules
C-like string formatting
Closes the specified file (that was previously opened using fopen)
Reads binary data from a file (opened in binary mode)
Writes binary data to a file (opened in binary mode)
Prints text to a file (opened in text mode)
Prints C-style formatted text to a file (opened in text mode)
Performs a permutation on the dimensions of a matrix
Loads variables from a file
Saves variables to a file
Lauches a given kernel function fn in serial to every element of a certain matrix
Sets the synchronization framerate for the imshow function, in number of frames displayed per second.
Close