File MIES_Utilities.ipf

General utility functions.

Debugger state constants for DisableDebugger and ResetDebuggerState

static const double DEBUGGER_ENABLED = 0x01
static const double DEBUGGER_DEBUG_ON_ERROR = 0x02
static const double DEBUGGER_NVAR_CHECKING = 0x04

Functions

variable IsFinite(variable var)

Returns 1 if var is a finite/normal number, 0 otherwise.

UTF_NOINSTRUMENTATION

variable IsNaN(variable var)

Returns 1 if var is a NaN, 0 otherwise.

UTF_NOINSTRUMENTATION

variable IsInf(variable var)

Returns 1 if var is +/- inf, 0 otherwise.

UTF_NOINSTRUMENTATION

variable IsNull(string *str)

Returns 1 if str is null, 0 otherwise.

UTF_NOINSTRUMENTATION

Parameters:

str – must not be a SVAR

variable IsEmpty(string str)

Returns one if str is empty, zero otherwise.

UTF_NOINSTRUMENTATION

Parameters:

str – any non-null string variable or text wave element

variable ASSERT(variable var, string errorMsg, variable extendedOutput = defaultValue)

Low overhead function to check assertions.

Example usage:

ControlInfo/W = $device popup_MoreSettings_DeviceType
ASSERT(V_flag > 0, "Non-existing control or window")
do something with S_value

UTF_NOINSTRUMENTATION

Parameters:
  • var – if zero an error message is printed into the history and procedure execution is aborted, nothing is done otherwise. If the debugger is enabled, it also steps into it.

  • errorMsg – error message to output in failure case

  • extendedOutput – [optional, defaults to true] Output additional information on failure

variable ASSERT_TS(variable var, string errorMsg, variable extendedOutput = defaultValue)

Low overhead function to check assertions (threadsafe variant)

Example usage:

ASSERT_TS(DataFolderExistsDFR(dfr), "dfr does not exist")
do something with dfr

Unlike ASSERT() this function does not jump into the debugger (Igor Pro limitation).

UTF_NOINSTRUMENTATION

Parameters:
  • var – if zero an error message is printed into the history and procedure execution is aborted, nothing is done otherwise.

  • errorMsg – error message to output in failure case

  • extendedOutput – [optional, defaults to true] Output additional information on failure

variable WindowExists(string win)

Checks if the given name exists as window.

UTF_NOINSTRUMENTATION

string GetListOfObjects(dfref dfr, string matchExpr, variable typeFlag = defaultValue, variable fullPath = defaultValue, variable recursive = defaultValue, variable exprType = defaultValue)

Alternative implementation for WaveList/VariableList/etc. which honours a dfref and thus does not require SetDataFolder calls.

Parameters:
  • dfr – datafolder reference to search for the objects

  • matchExpr – expression matching the objects, either a regular (exprType == MATCH_REGEXP) or wildcard (exprType == MATCH_WILDCARD) expression

  • typeFlag – [optional, default: COUNTOBJECTS_WAVES] One of TypeFlags

  • fullPath – [optional, default: false] should only the object name or the absolute path of the object be returned

  • recursive – [optional, default: false] descent into all subfolders recursively

  • exprType – [optional, defaults: MATCH_REGEXP] convention used for matchExpr, one of MatchExpressions

Returns:

list of object names matching matchExpr

static string GetAllObjects(dfref dfr, variable typeFlag)

Return a list of all objects of the given type from dfr.

Does not work for datafolders which have a comma (,) in them.

string ListMatchesExpr(string list, string matchExpr, variable exprType)

Matches list against the expression matchExpr using the given convention in exprType

variable EnsureLargeEnoughWave(wave wv, variable indexShouldExist = defaultValue, variable dimension = defaultValue, variable initialValue = defaultValue, variable checkFreeMemory = defaultValue)

Redimension the wave to at least the given size.

The redimensioning is only done if it is required.

Can be used to fill a wave one at a time with the minimum number of redimensions. In the following example NOTE_INDEX is the index of the next free row and the total number of rows filled with data.

Make/FREE/N=(MINIMUM_WAVE_SIZE) data
SetNumberInWaveNote(data, NOTE_INDEX, 0)
// ...
for(...)
    index = GetNumberFromWaveNote(data, NOTE_INDEX)
    // ...
    EnsureLargeEnoughWave(data, dimension = ROWS, indexShouldExist = index)
    data[index] = ...
    // ...
    SetNumberInWaveNote(data, NOTE_INDEX, ++index)
endfor

Parameters:
  • wv – wave to redimension

  • indexShouldExist – [optional, default is implementation defined] the minimum size of the wave. The actual size of the wave after the function returns might be larger.

  • dimension – [optional, defaults to ROWS] dimension to resize, all other dimensions are left untouched.

  • initialValue – [optional, defaults to zero] initialValue of the new wave points

  • checkFreeMemory – [optional, defaults to false] check if the free memory is enough for increasing the size

Returns:

0 on success, (only for checkFreeMemory = True) 1 if increasing the wave’s size would fail due to out of memory

variable ValueCanBeWritten(WaveOrNull wv, variable value)

Check that the given value can be stored in the wave.

Does currently ignore floating point precision and ranges for integer waves

variable EnsureSmallEnoughWave(wave wv, variable maximumSize = defaultValue)

Resize the number of rows to maximumSize if it is larger than that.

Parameters:
  • wv – wave to redimension

  • maximumSize – maximum number of the rows, defaults to MAXIMUM_SIZE

variable ConvertFromBytesToMiB(variable var)

Convert Bytes to MiBs, a mebibyte being 2^20.

static variable GetWaveSizeImplementation(wave wv)

Returns the size of the wave in bytes.

variable GetSizeOfType(wave wv)

Return the size in bytes of a given type.

Inspired by http://www.igorexchange.com/node/1845

variable GetWaveSize(WaveOrNull wv, variable recursive = defaultValue)

Returns the size of the wave in bytes.

variable GetLockState(wave wv)

Return the lock state of the passed wave.

variable ConvertSamplingIntervalToRate(variable val)

Convert the sampling interval in microseconds (1e-6s) to the rate in kHz.

variable ConvertRateToSamplingInterval(variable val)

Convert the rate in kHz to the sampling interval in microseconds (1e-6s)

variable DataFolderExistsDFR(dfref dfr)

Checks if the datafolder referenced by dfr exists.

Parameters:

dfr[in] data folder to test

Returns:

one if dfr is valid and references an existing or free datafolder, zero otherwise UTF_NOINSTRUMENTATION

variable IsGlobalDataFolder(dfref dfr)

Check if the passed datafolder reference is a global/permanent datafolder.

UTF_NOINSTRUMENTATION

variable IsFreeDatafolder(dfref dfr)

Returns 1 if dfr is a valid free datafolder, 0 otherwise.

UTF_NOINSTRUMENTATION

dfref createDFWithAllParents(string dataFolder)

Create a datafolder and all its parents,.

Includes fast handling of the common case that the datafolder exists.

Returns:

reference to the datafolder UTF_NOINSTRUMENTATION

variable IsInteger(variable var)

Returns one if var is an integer and zero otherwise UTF_NOINSTRUMENTATION.

variable IsEven(variable var)

UTF_NOINSTRUMENTATION.

variable IsOdd(variable var)

UTF_NOINSTRUMENTATION.

variable Downsample(WaveOrNull wv, variable downsampleFactor, variable upsampleFactor, variable mode, string winFunction = defaultValue)

Downsample data.

Downsampling is performed on each column of the input wave. Edge-points of the output wave are by default set to zero.

Parameters:
  • wv – numeric wave, its row must hold more points than downsampleFactor. Will hold the downsampled data on successfull return, in the error case the contents are undetermined

  • downsampleFactor – positive non-zero integer by which the wave should be downsampled

  • upsampleFactor – positive non-zero integer by which the wave should be upsampled

  • mode – decimation mode, one of DECIMATION_BY_OMISSION, DECIMATION_BY_AVERAGING or DECIMATION_BY_SMOOTHING.

  • winFunction – Windowing function for DECIMATION_BY_SMOOTHING mode, must be one of FFT_WINF.

Returns:

One on error, zero otherwise

variable CalculateLCM(variable a, variable b)

Compute the least common multiplier of two variables.

variable CalculateLCMOfWave(wave wv)

Compute the least common multiplier of all entries in the 1D-wave.

wave GetUniqueEntries(wave wv, variable caseSensitive = defaultValue, variable dontDuplicate = defaultValue)

Returns an unsorted free wave with all unique entries from wv If dontDuplicate is set, then for a single element input wave no new free wave is created but the input wave is returned.

uses built-in igor function FindDuplicates. Entries are deleted from left to right.

Parameters:
  • wv – wave reference, can be numeric or text

  • caseSensitive – [optional, default = 1] Indicates whether comparison should be case sensitive. Applies only if the input wave is a text wave

  • dontDuplicate – [optional, default = 0] for a single element input wave no new free wave is created but the input wave is returned.

string GetUniqueTextEntriesFromList(string list, string sep = defaultValue, variable caseSensitive = defaultValue)

Convenience wrapper around GetUniqueTextEntries() for string lists.

static wave GetUniqueTextEntries(WaveText wv, variable caseSensitive = defaultValue, variable dontDuplicate = defaultValue)

Search and Remove Duplicates from Text Wave wv.

Duplicates are removed from left to right

Parameters:
  • wv – text wave reference

  • caseSensitive – [optional, default = 1] Indicates whether comparison should be case sensitive.

  • dontDuplicate – [optional, default = 0] for a single element input wave no new free wave is created but the input wave is returned.

Returns:

free wave with unique entries

variable RemoveEmptyDataFolder(dfref dfr)

Removes the datafolder reference if there are no objects in it anymore.

Parameters:

dfr – data folder reference to kill

Returns:

1 in case the folder was removed and 0 in all other cases

variable IsDataFolderEmpty(dfref dfr)

Return 1 if the datafolder is empty, zero if not.

variable RemoveAllEmptyDataFolders(dfref sourceDFR)

Remove all empty datafolders in the passed datafolder reference recursively including sourceDFR.

variable DisableDebugger()

Disable the debugger.

Returns:

the full debugger state binary encoded. first bit: on/off, second bit: debugOnError on/off, third bit: nvar/svar/wave checking on/off

variable ResetDebuggerState(variable debuggerState)

Reset the debugger to the given state.

Useful in conjunction with DisableDebugger() to temporarily disable the debugger

variable debuggerState = DisableDebugger()
// code which might trigger the debugger, e.g. CurveFit
ResetDebuggerState(debuggerState)
// now the debugger is in the same state as before

variable DisableDebugOnError()

Disable Debug on Error.

Returns:

1 if it was enabled, 0 if not, pass this value to ResetDebugOnError()

variable ResetDebugOnError(variable debugOnError)

Reset Debug on Error state.

Parameters:

debugOnError – state before, usually the same value as DisableDebugOnError() returned

variable GetNumberFromWaveNote(wave wv, string key)

Returns the numeric value of key found in the wave note, returns NaN if it could not be found.

The expected wave note format is: key1:val1;key2:val2; UTF_NOINSTRUMENTATION

variable SetNumberInWaveNote(wave wv, string key, variable val, string format = defaultValue)

Updates the numeric value of key found in the wave note to val

The expected wave note format is: key1:val1;key2:val2;

Parameters:
  • wv – wave

  • key – key of the Key/Value pair

  • val – value of the Key/Value pair

  • format – [optional] printf compatible format string to set the conversion to string for val

string GetStringFromWaveNote(wave wv, string key, string keySep = defaultValue, string listSep = defaultValue, variable recursive = defaultValue)

Return the string value of key found in the wave note default expected wave note format: key1:val1;key2:str2; counterpart of AddEntryIntoWaveNoteAsList when supplied with keySep = “=”.

Parameters:
  • wv – wave reference where the WaveNote is taken from

  • key – search for the value at key:value;

  • keySep – [optional, defaults to DEFAULT_KEY_SEP] separation character for (key, value) pairs

  • listSep – [optional, defaults to DEFAULT_LIST_SEP] list separation character

  • recursive – [optional, defaults to false] checks all wave notes in referenced waves from wave reference waves

Returns:

the value on success. An empty string is returned if it could not be found

string ExtractStringFromPair(string str, string key, string keySep = defaultValue, string listSep = defaultValue)

Same functionality as GetStringFromWaveNote() but accepts a string.

variable SetStringInWaveNote(wave wv, string key, string str, variable recursive = defaultValue, string keySep = defaultValue, string listSep = defaultValue)

Update the string value of key found in the wave note to str

The expected wave note format is: key1:val1;key2:str2;

string PossiblyUnquoteName(string name, string quote)

Remove the surrounding quotes from the string if they are present.

variable AddEntryIntoWaveNoteAsList(wave wv, string key, variable var = defaultValue, string str = defaultValue, variable appendCR = defaultValue, variable replaceEntry = defaultValue, string format = defaultValue)

Structured writing of numerical values with names into wave notes.

The general layout is key1 = var;key2 = str; and the note is never prefixed with a carriage return (“\r”).

Parameters:
  • wv – wave to add the wave note to

  • key – string identifier

  • var – variable to output

  • str – string to output

  • appendCR – 0 (default) or 1, should a carriage return (“\r”) be appended to the note

  • replaceEntry – 0 (default) or 1, should existing keys named key be replaced (does only work reliable in wave note lists without carriage returns).

  • format – [optional, defaults to g] format string used for converting var to str

variable HasEntryInWaveNoteList(wave wv, string key, string value)

Checks if key = value; can be found in the wave note.

Ignores spaces around the equal (“=”) sign.

variable IsWaveDisplayedOnGraph(string win, WaveOrNull wv = defaultValue, dfref dfr = defaultValue)

Check if a given wave, or at least one wave from the dfr, is displayed on a graph.

Returns:

one if one is displayed, zero otherwise

variable KillCursorInGraphs(string graphs, string cursorName)

Kill all cursors in a given list of graphs.

Parameters:
  • graphs – semicolon separated list of graph names

  • cursorName – name of cursor as string

string FindCursorInGraphs(string graphs, string cursorName)

Find the first match for a given cursor in a list of graph names.

Parameters:
  • graphs – semicolon separated list of graph names

  • cursorName – name of cursor as string

Returns:

graph where cursor was found

variable GetCursorXPositionAB(string graph, variable *csrAx, variable *csrBx)

get the x value of the cursors A and B

Todo:

make this a generic cursor getter function and merge with cursors() in

See also

SF_FormulaExecutor

Parameters:
  • graph[in] where the cursor are

  • csrAx[out] Position of cursor A

  • csrBx[out] Position of cursor B

variable RemoveAnnotationsFromGraph(string graph)

Removes all annotations from the graph.

string LineBreakingIntoPar(string str, variable minimumWidth = defaultValue)

Break a string into multiple lines.

All spaces and tabs which are not followed by numbers are replace by carriage returns (\r) if the minimum width was reached.

A generic solution would either implement the real deal

Knuth, Donald E.; Plass, Michael F. (1981), Breaking paragraphs into lines Software: Practice and Experience 11 (11): 1119-1184, doi:10.1002/spe.4380111102.

or translate 1 from C++ to Igor Pro.

Parameters:
  • str – string to break into lines

  • minimumWidth – [optional, defaults to zero] Each line, except the last one, will have at least this length

dfref UniqueDataFolder(dfref dfr, string baseName)

Returns a reference to a newly created datafolder.

Basically a datafolder aware version of UniqueName for datafolders

Parameters:
  • dfr – datafolder reference where the new datafolder should be created

  • baseName – first part of the datafolder, might be shortend due to Igor Pro limitations

string UniqueDataFolderName(dfref dfr, string baseName)

Return an absolute unique data folder name which does not exist in dfr.

Parameters:
  • dfr – datafolder to search

  • baseName – first part of the datafolder, must be a valid Igor Pro object name

string UniqueWaveName(dfref dfr, string baseName)

Returns a wave name not used in the given datafolder.

Basically a datafolder aware version of UniqueName for datafolders

Parameters:
  • dfr – datafolder reference where the new datafolder should be created

  • baseName – first part of the wave name, might be shorted due to Igor Pro limitations

string RemovePrefix(string str, string start = defaultValue, variable regExp = defaultValue)

Remove a prefix from a string.

Same semantics as the RemoveEnding builtin for regExp == 0.

UTF_NOINSTRUMENTATION

Parameters:
  • str – string to potentially remove something from its beginning

  • start – [optional, defaults to the first character] Remove this from the begin of str

  • regExp – [optional, defaults to false] If start is a simple string (false) or a regular expression (true)

string UniqueFileOrFolder(string symbPath, string baseName, string suffix = defaultValue)

Returns a unique and non-existing file or folder name.

Warning

This function must not be used for security relevant purposes, as for that the check-and-file-creation must be an atomic operation.

Parameters:
  • symbPath – symbolic path

  • baseName – base name of the file, must not be empty

  • suffix – file/folder suffix

string GetExperimentName()

Return the name of the experiment without the file suffix.

string GetExperimentFileType()

Return the experiment file type.

string GetTimeStamp(variable secondsSinceIgorEpoch = defaultValue, variable humanReadable = defaultValue)

Return a formatted timestamp of the form YY_MM_DD_HHMMSS

Uses the local time zone and not UTC.

Parameters:
  • humanReadable – [optional, default to false] Return a format viable for display in a GUI

  • secondsSinceIgorEpoch – [optional, defaults to number of seconds until now] Seconds since the Igor Pro epoch (1/1/1904)

variable CALL_FUNCTION_LIST_PROTOTYPE(string str)

Function prototype for use with CallFunctionForEachListItem.

variable CALL_FUNCTION_LIST_PROTOTYPE_TS(string str)

Function prototype for use with CallFunctionForEachListItem.

variable CallFunctionForEachListItem(CALL_FUNCTION_LIST_PROTOTYPE f, string list, string sep = defaultValue)

Convenience function to call the function f with each list item.

The function’s type must be CALL_FUNCTION_LIST_PROTOTYPE where the return type is ignored.

variable CallFunctionForEachListItem_TS(CALL_FUNCTION_LIST_PROTOTYPE_TS f, string list, string sep = defaultValue)

Compatibility wrapper for threadsafe functions f

variable IsDriveValid(string absPath)

Return true if the given absolute path refers to an existing drive letter.

string GetDrive(string path)

Return the drive letter of the given path (Windows) or the volume name (Macintosh)

variable CreateFolderOnDisk(string absPath)

Create a folder recursively on disk given an absolute path.

If you pass windows style paths using backslashes remember to always double them.

variable GetRowIndex(wave wv, variable val = defaultValue, string str = defaultValue, WaveOrNull refWave = defaultValue)

Return the row index of the given value, string converted to a variable, or wv.

Assumes wv being one dimensional

string ListFromList(string list, variable itemBegin, variable itemEnd, string listSep = defaultValue)

return a subset of the input list

Parameters:
  • list – input list

  • itemBegin – first item

  • itemEnd – last item

  • listSep – [optional] list Separation character. default is “;”

Returns:

a list with elements ranging from itemBegin to itemEnd of the input list

std::tuple<variable, variable> MinMax(variable a, variable b)

Return the minimum and maximum of both values.

wave DuplicateSubRange(wave wv, variable first, variable last)

Return a new wave from the subrange of the given 1D wave.

string GetListDifference(string list1, string list2, variable caseSensitive = defaultValue)

calculates the relative complement of list2 in list1

Every list item of list2 must be in list1.

also called the set-theoretic difference of list1 and list2

Returns:

difference as list

string GetBaseName(string filePathWithSuffix, string sep = defaultValue)

Return the base name of the file.

Given path/file.suffix this gives file.

Parameters:
  • filePathWithSuffix – full path

  • sep – [optional, defaults to “:”] character separating the path components

string GetFileSuffix(string filePathWithSuffix, string sep = defaultValue)

Return the file extension (suffix)

Given path/file.suffix this gives suffix.

Parameters:
  • filePathWithSuffix – full path

  • sep – [optional, defaults to “:”] character separating the path components

string GetFolder(string filePathWithSuffix, string sep = defaultValue)

Return the folder of the file.

Given path/file.suffix this gives path. The returned result has a trailing separator.

Parameters:
  • filePathWithSuffix – full path

  • sep – [optional, defaults to “:”] character separating the path components

string GetFile(string filePathWithSuffix, string sep = defaultValue)

Return the filename with extension.

Given path/file.suffix this gives file.suffix.

Parameters:
  • filePathWithSuffix – full path

  • sep – [optional, defaults to “:”] character separating the path components

string GetWindowsPath(string path)

Return the path converted to a windows style path.

string GetHFSPath(string path)

Return the path converted to a HFS style (aka “:” separated) path.

variable SetBit(variable var, variable bit)

Set the given bit mask in var.

variable ClearBit(variable var, variable bit)

Clear the given bit mask in var.

string BuildList(string format, variable start, variable step, variable stop)

Create a list of strings using the given format in the given range.

Parameters:
  • format – formatting string, must have exactly one specifier which accepts a number

  • start – first point of the range

  • step – step size for iterating over the range

  • stop – last point of the range

variable GetFreeMemory()

Return the amount of free memory in GB.

Due to memory fragmentation you can not assume that you can still create a wave occupying as much space as returned.

string RemoveEndingRegExp(string str, string endingRegExp)

Remove the given reguluar expression from the end of the string.

In case the regular expression does not match, the string is returned unaltered.

See also DisplayHelpTopic "Regular Expressions".

variable SearchWordInString(string str, string word, string *prefix = defaultValue, string *suffix = defaultValue)

Search for a Word inside a String.

example of the usage of SearchStringBase (basically the same as WM GrepString())

Function SearchString(str, substring)
    string str, substring

    ASSERT(!IsEmpty(substring), "supplied substring is empty")
    WAVE/Z/T wv = SearchStringBase(str, "(.*)\\Q" + substring + "\\E(.*)")

    return WaveExists(wv)
End

Parameters:
  • str[in] input text in which word should be searched

  • word[in] searchpattern (non-regex-sensitive)

  • prefix[out] (optional) string preceding word. (”” for unmatched pattern)

  • suffix[out] (optional) string succeeding word.

Returns:

1 if word was found in str and word was not “”. 0 if not.

static std::tuple<variable, string, string> SearchRegexInString(string str, string regex)
wave SearchStringBase(string str, string regex)

More advanced version of SplitString.

supports 6 subpatterns, specified by curly brackets in regex

Returns:

text wave containing subpatterns of regex call

variable CountSubstrings(string str, string pattern)

Search for the occurence of pattern in string.

Returns:

number of occurences

variable GetRowWithSameContent(WaveText refWave, WaveText sourceWave, variable row)

Search the row in refWave which has the same contents as the given row in the sourceWave.

variable InPlaceRandomShuffle(wave inwave, variable noiseGenMode = defaultValue)

Random shuffle of the wave contents.

Function was taken from: http://www.igorexchange.com/node/1614 author s.r.chinn

Parameters:
  • inwave – The wave that will have its rows shuffled.

  • noiseGenMode – [optional, defaults to NOISE_GEN_XOSHIRO] type of RNG to use

string UniqueTraceName(string graph, string baseName)

Return a unique trace name in the graph.

Remember that it might be necessary to call DoUpdate if you added possibly colliding trace names in the current function run.

Parameters:
  • graph – existing graph

  • baseName – base name of the trace, must not be empty

variable WaveListHasSameWaveNames(string listOfWaves, string *baseName)

Checks wether the wave names of all waves in the list are equal Returns 1 if true, 0 if false and NaN for empty lists.

Parameters:
  • listOfWaves – list of waves with full path

  • baseName[out] Returns the common baseName if the list has one, otherwise this will be an empty string.

variable IsBackgroundTaskRunning(string task)

Check wether the given background task is currently running.

Note: Background functions which are currently waiting for their period to be reached are also running.

Parameters:

task – Named background task identifier, this is not the function set with proc=

variable PopCount(variable value)

Count the number of ones in value

Parameters:

value – will be truncated to an integer value

variable NewRandomSeed()

Initializes the random number generator with a new seed between (0,1] The time base is assumed to be at least 0.1 microsecond precise, so a new seed is available every 0.1 microsecond.

Usage example for the case that one needs n non reproducible random numbers. Whenever the following code block is executed a new seed is set, resulting in a different series of numbers

Make/D/N=(n) newRandoms
NewRandomSeed() // Initialize random number series with a new seed
newRandoms[] = GetReproducibleRandom() // Get n randoms from the new series

variable GetReproducibleRandom(variable noiseGenMode = defaultValue)

Return a random value in the range (0,1] which can be used as a seed for SetRandomSeed

Return a reproducible random number depending on the RNG seed.

variable GetUniqueInteger()

Return a unique integer.

The returned values can not be used for statistical purposes as the distribution is not uniform anymore.

string AddPrefixToEachListItem(string prefix, string list, string sep = defaultValue)

Add a string prefix to each list item and return the new list.

string AddSuffixToEachListItem(string suffix, string list, string sep = defaultValue)

Add a string suffix to each list item and return the new list.

string RemovePrefixFromListItem(string prefix, string list, string listSep = defaultValue, variable regExp = defaultValue)

Remove a string prefix from each list item and return the new list.

UTF_NOINSTRUMENTATION

variable FuncRefIsAssigned(string funcInfo)

Check wether the function reference points to the prototype function or to an assigned function.

Due to Igor Pro limitations you need to pass the function info from FuncRefInfo and not the function reference itself.

UTF_NOINSTRUMENTATION

Returns:

1 if pointing to prototype function, 0 otherwise

variable DateTimeInUTC()

Return the seconds, including fractional part, since Igor Pro epoch (1/1/1904) in UTC time zone.

string GetISO8601TimeStamp(variable secondsSinceIgorEpoch = defaultValue, variable numFracSecondsDigits = defaultValue, variable localTimeZone = defaultValue)

Return a string in ISO 8601 format with timezone UTC.

Parameters:
  • secondsSinceIgorEpoch – [optional, defaults to number of seconds until now] Seconds since the Igor Pro epoch (1/1/1904) in UTC (or local time zone depending on localTimeZone)

  • numFracSecondsDigits – [optional, defaults to zero] Number of sub-second digits

  • localTimeZone – [optional, defaults to false] Use the local time zone instead of UTC

variable ParseUnit(string unitWithPrefix, string *prefix, variable *numPrefix, string *unit)

Parses a simple unit with prefix into its prefix and unit.

Note: The currently allowed units are the SI base units [1] and other common derived units. And in accordance to SI definitions, “kg” is a base unit.

Parameters:
  • unitWithPrefix[in] string to parse, examples are “ms” or “kHz”

  • prefix[out] symbol of decimal multipler of the unit, see below or [1] chapter 3 for the full list

  • numPrefix[out] numerical value of the decimal multiplier

  • unit[out] unit

variable GetDecimalMultiplierValue(string prefix)

Return the numerical value of a SI decimal multiplier.

See also

ParseUnit

variable QuerySetIgorOption(string name, variable globalSymbol = defaultValue)

Query a numeric option settable with SetIgorOption

Parameters:
  • name – name of the keyword/setting

  • globalSymbol – [optional, defaults to false] name refers to a global symbol set via poundDefine

variable ForceRecompile()

Force recompilation of all procedure files.

Uses the “Operation Queue”.

variable ParseISO8601TimeStamp(string timestamp)

Parse a ISO8601 timestamp, e.g. created by GetISO8601TimeStamp(), and returns the number of seconds, including fractional parts, since Igor Pro epoch (1/1/1904) in UTC time zone.

Accepts also the following specialities:

  • no UTC timezone specifier (UTC timezone is still used)

  • /T between date and time

  • fractional seconds

  • ,/. as decimal separator

std::tuple<variable, string, string, string, string, string, string, string, string, string, string> ParseISO8601TimeStampToComponents(string timestamp)

Parses a ISO8601 timestamp to its components, year, month, day, hour, minute are required and the remaining components are optional and can be returned as empty strings.

string GetIgorExtensionFolderName()

Return the disc folder name where the XOPs are located.

Distinguishes between i386 and x64 Igor versions

string GetIgorExecutable()

Return an Igor-style path to the Igor Pro executable.

string ResolveAlias(string path, string pathName = defaultValue)

Recursively resolve shortcuts to files/directories.

Returns:

full path or an empty string if the file does not exist or the shortcut points to a non existing file/folder

variable GetArchitectureBits()

Return the number of bits of the architecture Igor Pro was built for.

string GetIgorInfo(variable selector)

Return the given IgorInfo (cached)

This is faster than calling IgorInfo everytime.

string GetIgorProVersion()

Return the Igor Pro version string.

string GetIgorProBuildVersion()

Return the Igor Pro build version string.

This allows to distinguish different builds from the same major/minor version.

string GetUniqueSymbolicPath(string prefix = defaultValue)

Return a unique symbolic path name.

string symbPath = GetUniqueSymbolicPath()
NewPath/Q/O $symbPath, "C:"

string GetAllFilesRecursivelyFromPath(string pathName, string extension = defaultValue)

Return a list of all files from the given symbolic path and its subfolders. The list is pipe (FILE_LIST_SEP) separated as the semicolon (;) is a valid character in filenames.

Note: This function does not work on MacOSX as there filenames are allowed to have pipe symbols in them.

Parameters:
  • pathName – igor symbolic path to search recursively

  • extension – [optional, defaults to all files] file suffixes to search for

string TextWaveToList(WaveTextOrNull txtWave, string rowSep, string colSep = defaultValue, string layerSep = defaultValue, string chunkSep = defaultValue, variable stopOnEmpty = defaultValue, variable maxElements = defaultValue)

Convert a text wave to string list.

Counterpart

See also

ConvertListToTextWave

Parameters:
  • txtWave – input text wave

  • rowSep – separator for row entries

  • colSep – [optional, default = “,”] separator for column entries

  • layerSep – [optional, default = “:”] separator for layer entries

  • chunkSep – [optional, default = “/”] separator for chunk entries

  • stopOnEmpty – [optional, default = 0] when 1 stops generating the list when an empty string entry in txtWave is encountered

  • maxElements – [optional, defaults to inf] output only the first maxElements entries

Returns:

string with wave entries separated as list using given separators

wave ListToTextWaveMD(string list, variable dims, string rowSep = defaultValue, string colSep = defaultValue, string laySep = defaultValue, string chuSep = defaultValue)

Converts a list to a multi dimensional text wave, treating it row major order The output wave does not contain unused dimensions, so if dims = 4 is specified but no chunk separator is found then the returned wave is 3 dimensional. An empty list results in a zero dimensional wave.

The following call ListToTextWaveMD(“1/5/6/:8/:,;2/:,;3/7/:,;4/:,;”, 4, rowSep=”;”, colSep=”,”,laySep=”:”, chuSep=”/”) returns ‘free’[0][0][0][0]= {“1”,”2”,”3”,”4”} ‘free’[0][0][1][0]= {“8”,””,””,””} ‘free’[0][0][0][1]= {“5”,””,”7”,””} ‘free’[0][0][1][1]= {“”,””,””,””} ‘free’[0][0][0][2]= {“6”,””,””,””} ‘free’[0][0][1][2]= {“”,””,””,””}

Parameters:
  • list[in] input string with list

  • dims[in] number of dimensions the output text wave should have

  • rowSep[in] [optional, default = “;”] row separator

  • colSep[in] [optional, default = “,”] column separator

  • laySep[in] [optional, default = “:”] layer separator

  • chuSep[in] [optional, default = “/”] chunk separator

Returns:

text wave with at least dims dimensions

string NumericWaveToList(WaveOrNull wv, string sep, string format = defaultValue, string colSep = defaultValue)

Convert a 1D or 2D numeric wave to string list.

Counterpart

See also

TextWaveToList

Parameters:
  • wv – numeric wave

  • sep – separator

  • colSep – [optional, default = ,] separator for column entries

  • format – [optional, defaults to g] sprintf conversion specifier

static string WaveToListFast(wave wv, string format, string sep, string colSep)
wave ListToNumericWave(string list, string sep, variable type = defaultValue, variable ignoreErr = defaultValue)

Convert a list to a numeric wave.

Counterpart

See also

TextWaveToList

Parameters:
  • list – list with numeric entries

  • sep – separator

  • type – [optional, defaults to double precision float (IGOR_TYPE_64BIT_FLOAT)] type of the created numeric wave

  • ignoreErr – [optional, defaults 0] when this flag is set conversion errors are ignored, the value placed is NaN (-9223372036854775808 for int type)

wave GetColfromWavewithDimLabel(wave wv, string dimLabel)

Returns the column from a multidimensional wave using the dimlabel.

wave MakeWaveFree(wave wv)

Turn a persistent wave into a free wave.

variable SetDimensionLabels(wave wv, string list, variable dim, variable startPos = defaultValue)

Sets the dimension labels of a wave.

Parameters:
  • wv – Wave to add dim labels

  • list – List of dimension labels, semicolon separated.

  • dim – Wave dimension, see, WaveDimensions

  • startPos – [optional, defaults to 0] First dimLabel index

variable CheckIfClose(variable var1, variable var2, variable tol = defaultValue, variable strong_or_weak = defaultValue)

Compare two variables and determines if they are close.

Based on the implementation of “Floating-point comparison algorithms” in the C++ Boost unit testing framework.

Literature:

The art of computer programming (Vol II). Donald. E. Knuth. 0-201-89684-2. Addison-Wesley Professional; 3 edition, page 234 equation (34) and (35).

UTF_NOINSTRUMENTATION

Parameters:
  • var1 – first variable

  • var2 – second variable

  • tol – [optional, defaults to 1e-8] tolerance

  • strong_or_weak – [optional, defaults to strong] type of condition, can be zero for weak or 1 for strong

variable CheckIfSmall(variable var, variable tol = defaultValue)

Test if a variable is small using the inequality \( | var | < | tol | \).

Parameters:
  • var – variable

  • tol – [optional, defaults to 1e-8] tolerance

variable ListHasOnlyOneUniqueEntry(string list, string sep = defaultValue)

Check if all elements of the string list are the same.

Returns true for lists with less than one element

wave ExtractFromSubrange(string listOfRanges, variable dim)

Extract the values of a list of subrange specifications See also DisplayHelpTopic “Subrange Display”.

Example invocations:

WAVE ranges = ExtractFromSubrange("[3,4]_[*]_[1, *;4]_[]_[5][]", 0)

Parameters:
  • listOfRanges – list of subrange specifications separated by **_**

  • dim – dimension to extract

Returns:

2-dim wave with the start, stop, step as columns and rows as number of elements. Returns -1 instead of * or ``. An invalid wave reference is returned on parsing errors.

variable FindNextPower(variable a, variable p)

Find an integer x which is larger than a but the smallest possible power of p.

\( x > a \) where \( x = c^p \) holds and \( x \) is the smallest possible value.

variable FindPreviousPower(variable a, variable p)

Find an integer x which is smaller than a but the largest possible power of p.

\( x < a \) where \( x = c^p \) holds and \( x \) is the largest possible value.

wave DeepCopyWaveRefWave(WaveRefWave src, variable dimension = defaultValue, variable index = defaultValue, wave indexWave = defaultValue)

Return a wave with deep copies of all referenced waves.

The deep copied waves will be free waves. Does not allow invalid wave references in src.

Parameters:
  • src – wave reference wave

  • dimension – [optional] copy only a single dimension, requires index or indexWave as well

  • index – [optional] specifies the index into dimension, index is not checked

  • indexWave – [optional] specifies the indizes into dimension, allows for differing indizes per src entry, indices are not checked

variable ReduceWaveDimensionality(WaveOrNull wv, variable minDimension = defaultValue)

Shrinks a waves dimensionality if higher dimensions have size 1.

Parameters:
  • wv – Wave that should be shrinked

  • minDimension – [optional, default COLS] shrinks a wave only up to this dimension, e.g. with minDimension = LAYERS a wave of size (1,1,1,1) is shrinked to (1,1,1,0).

variable IsTextWave(wave wv)

Return 1 if the wave is a text wave, zero otherwise UTF_NOINSTRUMENTATION.

variable IsNumericWave(wave wv)

Return 1 if the wave is a numeric wave, zero otherwise UTF_NOINSTRUMENTATION.

variable IsWaveRefWave(wave wv)

Return 1 if the wave is a wave reference wave, zero otherwise UTF_NOINSTRUMENTATION.

variable IsFloatingPointWave(wave wv)

Return 1 if the wave is a floating point wave UTF_NOINSTRUMENTATION.

variable IsDoubleFloatingPointWave(wave wv)

Return 1 if the wave is a double (64bit) precision floating point wave.

UTF_NOINSTRUMENTATION

variable IsSingleFloatingPointWave(wave wv)

Return 1 if the wave is a single (32bit) precision floating point wave.

UTF_NOINSTRUMENTATION

variable IsGlobalWave(wave wv)

Return 1 if the wave is a global wave (not a null wave and not a free wave)

variable IsComplexWave(wave wv)

Return 1 if the wave is a complex wave.

string GetSystemUserName()

Return the user name of the running user.

variable ControlWindowToFront()

Bring the control window (the window with the command line) to the front of the desktop.

variable GetAlignment(variable val)

Return the alignment of the decimal number (usually a 32bit/64bit pointer)

variable RemoveAllDimLabels(WaveOrNull wv)

Remove the dimlabels of all dimensions with data.

Due to no better solutions the dim labels are actually overwritten with an empty string

variable GetMarkerSkip(variable numPoints, variable numMarkers)

Calculate the value for mskip of ModifyGraph

Parameters:
  • numPoints – number of points shown

  • numMarkers – desired number of markers

wave GetSetUnion(wave wave1, wave wave2)

Return a wave of the union of all entries from both waves with duplicates removed.

Given {1, 2, 10} and {2, 5, 11} this will return {1, 2, 5, 10, 11}. The order of the returned entries is not defined.

wave GetSetDifference(wave wave1, wave wave2)

Return a wave were all elements which are in both wave1 and wave2 have been removed from wave1.

See also

GetListDifference for string lists

static std::tuple<WAVE, variable> GetSetDifferenceNumeric(wave wave1, wave wave2)
static std::tuple<WAVE, variable> GetSetDifferenceText(WaveText wave1, WaveText wave2)
wave GetSetIntersection(wave wave1, wave wave2)

Return a wave with the set theory style intersection of wave1 and wave2.

Given {1, 2, 4, 10} and {2, 5, 11} this will return {2}.

Inspired by http://www.igorexchange.com/node/366 but adapted to modern Igor Pro It does work with text waves as well, there it performs case sensitive comparions

Returns:

free wave with the set intersection or an invalid wave reference if the intersection is an empty set

variable KillWindows(string list)

Kill all passed windows.

Silently ignore errors.

variable str2numSafe(string str)

str2num variant with no runtime error on invalid conversions

UTF_NOINSTRUMENTATION

string AskUserForExistingFolder(string baseFolder)

Open a folder selection dialog.

Returns:

a string denoting the selected folder, or an empty string if nothing was supplied.

string GetAllAxesWithOrientation(string graph, variable axisOrientation)

Return all axes with the given orientation.

Parameters:
variable GetNumFromModifyStr(string info, string key, string listChar, variable item)

Polished version of GetNumFromModifyStr from Readback ModifyStr.ipf

Parameters:
  • info – string as returned by AxisInfo or TraceInfo

  • key – keyword

  • listChar – empty, { or ( depending on keyword style

  • item – return the given element from the extracted list

string SortAxisList(string graph, string list)

Return the list of axis sorted from highest to lowest starting value of the axisEnab keyword.

list must be from one orientation, usually something returned by GetAllAxesWithOrientation()

string ReplaceWordInString(string word, string str, string replacement)
string ReplaceRegexInString(string regex, string str, string replacement)

Replaces all occurences of the regular expression regex in str with replacement

variable ExecuteListOfFunctions(string funcList)

Execute a list of functions via the Operation Queue.

Special purpose function. Not intended for normal use.

variable DoAbortNow(string msg)

Wrapper function for Abort which honours our interactive mode setting.

string FloatWithMinSigDigits(variable var, variable numMinSignDigits = defaultValue)

Return a floating point value as string rounded to the given number of minimum significant digits.

This allows to specify the minimum number of significant digits. The normal printf/sprintf specifier only allows the maximum number of significant digits for g.

string NormalizeToEOL(string str, string eol)

Normalize the line endings in the given string to either classic Mac OS/Igor Pro EOLs (\r) or Unix EOLs (\n)

UTF_NOINSTRUMENTATION

string GetStackTrace(string prefix = defaultValue)

Return a nicely formatted multiline stacktrace.

variable StopAllMSTimers()

Stop all millisecond Igor Pro timers.

variable RelativeNowHighPrec()

Return a time in seconds with high precision, microsecond resolution, using an arbitrary zero point.

variable SleepHighPrecision(variable var)

High precision version of the builtin Sleep command.

Parameters:

var – time in seconds to busy-sleep (current precision is around 0.1ms)

variable GetMachineEpsilon(variable type)

Return the machine epsilon for the given wave type.

Experimentally determined with Igor Pro 7.08

variable IsFreeWave(wave wv)

Return true if wv is a free wave, false otherwise.

UTF_NOINSTRUMENTATION

variable WaveModCountWrapper(wave wv)

Return the modification count of the (permanent) wave.

Returns NaN when running in a preemptive thread

UTF_NOINSTRUMENTATION

string ToPassFail(variable passedOrFailed)
string ToTrueFalse(variable var)
string ToOnOff(variable var)
variable HasOneValidEntry(wave wv)

Return true if not all wave entries are NaN, false otherwise.

UTF_NOINSTRUMENTATION

wave MergeTwoWaves(wave wv1, wave wv2)

Merge two floating point waves labnotebook waves.

The result will hold the finite row entry of either wv1 or wv2.

variable CreateHistoryNotebook()

Create the special Notebook “HistoryCarbonCopy” which will hold a readable copy of the history starting from the time of the notebook creation.

string GetHistoryNotebookText()

Return the text of the history notebook.

variable AssertOnAndClearRTError()

Helper function to ensure that there is no pending RTE before entering a critical section. If there is a pending RTE then a BUG message is output (which is a CI error).

Not catching any pending RTE would clear this condition silently and valid errors would be suppressed. This is dangerous in regards of data consistency.

Not clearing the RTE before calling AbortOnRTE will always trigger the RTE no matter what you do in that line. Any call to GetRTErrMessage() must be done prior to clearing the runtime error in the catch block.

Usage:

AssertOnAndClearRTError()
  try
    CriticalFunc(); AbortOnRTE
  catch
    msg = GetRTErrMessage()
    err = ClearRTError()
  endtry

UTF_NOINSTRUMENTATION

variable ClearRTError()

Helper function to unconditionally clear a RTE condition It is generally strongly recommended to use.

UTF_NOINSTRUMENTATION

See also

AssertOnAndClearRTError before critical code sections. For detailed description of the implications

string DAQRunModeToString(variable runMode)

Convert the DAQ run mode to a string.

Parameters:

runMode – One of DAQRunModes

string TestPulseRunModeToString(variable runMode)

Convert the Testpulse run mode to a string.

Parameters:

runMode – One of TestPulseRunModes

variable ChangeWaveLock(WaveRefWave wv, variable val)

Adapt the wave lock status on the wave and its contained waves.

variable DeleteWavePoint(wave wv, variable dim, variable index)

Deletes one row, column, layer or chunk from a wave Advantages over DeletePoints: Keeps the dimensionality of the wave when deleting the last row, column, layer or chunk in a wave Implements range check Advantages over DeletePoints + KillWaves: The wave reference stays valid.

Parameters:
  • wv – wave where the row, column, layer or chunk should be deleted

  • dim – dimension 0 - rows, 1 - column, 2 - layer, 3 - chunk

  • index – index where one point in the given dimension is deleted

string num2strHighPrec(variable val, variable precision = defaultValue, variable shorten = defaultValue)

Converts a number to a string with specified precision (digits after decimal dot). This function is an extension for the regular num2str that is limited to 5 digits. Input numbers are rounded using the “round-half-to-even” rule to the given precision. The default precision is 5. If val is complex only the real part is converted to a string.

Parameters:
  • val[in] number that should be converted to a string

  • precision[in] [optional, default 5] number of precision digits after the decimal dot using “round-half-to-even” rounding rule. Precision must be in the range 0 to MAX_DOUBLE_PRECISION.

  • shorten[in] [optional, defaults to false] Remove trailing zeros and optionally the decimal dot to get a minimum length string

Returns:

string with textual number representation

variable RoundNumber(variable val, variable precision)

Round the given number to the given number of decimal digits.

variable GetASLREnabledState()

Return the per application setting of ASLR for the Igor Pro executable.

See https://docs.microsoft.com/en-us/windows/security/threat-protection/windows-defender-exploit-guard/enable-exploit-protection for the powershell cmdlet documentation.

Returns:

0 or 1

variable TurnOffASLR()

Turn off ASLR.

Requires administrative privileges via UAC. Only required once for ITC hardware.

variable IsWindows10()

Check if we are running on Windows 10.

variable GetReferenceTime()

Start a timer for performance measurements.

Usage:

variable referenceTime = GetReferenceTime()
// part one to benchmark
print GetReferenceTime(referenceTime)
// part two to benchmark
print GetReferenceTime(referenceTime)
// you can also store all times via
StoreElapsedTime(referenceTime)

variable GetElapsedTime(variable referenceTime)

Get the elapsed time in seconds.

variable StoreElapsedTime(variable referenceTime)

Store the elapsed time in a wave.

variable GetPlotArea(string win, RectD *s)
variable HasEnoughDiskspaceFree(string diskPath, variable requiredFreeSpace)

Check that the given path on disk has enough free space.

Parameters:
  • diskPath – path on disk to check

  • requiredFreeSpace – required free space in GB

static variable FindLevelSingle(wave data, variable level, variable edge, variable first, variable last)
static wave FindLevelsMult(wave data, variable level, variable edge, variable first, variable last, variable maxNumLevels)
wave FindLevelWrapper(wave data, variable level, variable edge, variable mode, variable maxNumLevels = defaultValue)

FindLevel wrapper which handles 2D data without copying data.

The returned levels are in the wave’s row units.

FINDLEVEL_MODE_SINGLE:

  • Return a 1D wave with as many rows as columns in the input data

  • Contents are the x values of the first level or NaN if none could be found

FINDLEVEL_MODE_MULTI:

  • Returns a 2D WAVE rows being the number of columns in the input data and columns holding all found x values of the levels per data column.

In both cases the dimension label of the each column holds the number of found levels in each data colum. This will be always 1 for FINDLEVEL_MODE_SINGLE.

Parameters:
  • data – input data, can be either 1D or 2D

  • level – level to search

  • edge – type of the edge, one of FindLevelEdgeTypes

  • mode – mode, one of FindLevelModes

  • maxNumLevels – [optional, defaults to number of points/rows] maximum number of levels to find

variable GetOpenZFlag()

Return a /Z flag value for the Open operation which works with automated testing.

variable SaveTextFile(string *data, string *fileName, string *fileFilter = defaultValue, string *message = defaultValue, string *savedFileName = defaultValue, variable showDialogOnOverwrite = defaultValue)

Saves string data to a file.

Parameters:
  • data[in] string containing data to save

  • fileName[in] fileName to use. If the fileName is empty or invalid a file save dialog will be shown.

  • fileFilter[in] [optional, default = “Plain Text Files (*.txt):.txt;All Files:.*;”] file filter string in Igor specific notation.

  • message[in] [optional, default = “Create file”] window title of the save file dialog.

  • savedFileName[out] [optional, default = “”] file name of the saved file

  • showDialogOnOverwrite[in] [optional, default = 0] opens save file dialog, if the current fileName would cause an overwrite, to allow user to change fileName

Returns:

NaN if file open dialog was aborted or an error was encountered, 0 otherwise

std::tuple<string, string> LoadTextFile(string fileName, string fileFilter = defaultValue, string message = defaultValue)

Load data from file to a string. The file size must be < 2GB.

Parameters:
  • fileName[in] fileName to use. If the fileName is empty or invalid a file load dialog will be shown.

  • fileFilter[in] [optional, default = “Plain Text Files (*.txt):.txt;All Files:.*;”] file filter string in Igor specific notation.

  • message[in] [optional, default = “Select file”] window title of the save file dialog.

Returns:

loaded string data and full path fileName

wave LoadTextFileToWave(string fullFilePath, string sep)

Load data from a file to a text wave.

Parameters:
  • fullFilePath[in] full path to the file to be loaded

  • sep[in] separator string that splits the file data to the wave cells, typically the line ending

Returns:

free text wave with the data, a null wave if the file could not be found or there was a problem reading the file

variable RemoveTextWaveEntry1D(WaveText w, string entry, variable options = defaultValue, variable all = defaultValue)

Removes found entry from a text wave.

Parameters:
  • w – text wave

  • entry – element content to compare

  • options – [optional, defaults to “whole wave element”] FindValue/TXOP options

  • all – [optional, defaults to false] removes all entries

Returns:

0 if at least one entry was found, 1 otherwise

variable StringEndsWith(string str, string suffix)

Checks if a string ends with a specific suffix. The check is case-insensitive.

Parameters:
  • str[in] string to check for suffix

  • suffix[in] to check for

Returns:

1 if str ends with suffix, 0 otherwise. If str and/or suffix are empty or null 0 is returned.

std::tuple<WaveText, WaveText> SplitTextWaveBySuffix(WaveText source, string suffix)

Splits a 1d text wave into two waves. The first contains elements with a suffix, the second elements without.

Parameters:
  • source[in] 1d text wave

  • suffix[in] string suffix to distinguish elements

Returns:

two 1d text waves, the first contains all elements with the suffix, the second all elements without

variable FileExists(string filepath)

Check wether the given path points to an existing file.

Resolves shortcuts and symlinks recursively.

variable FolderExists(string folderpath)

Check wether the given path points to an existing folder.

string GetFileVersion(string filepath)

Return the file version.

variable GetFileSize(string filepath)

Return the file size in bytes.

string HFSPathToPosix(string path)

Convert a HFS path (:) to a POSIX path (/)

The path must exist.

string HFSPathToWindows(string path)

Convert a HFS path (:) to a Windows path (\\)

string HFSPathToNative(string path)

Convert HFS path (:) to OS native path (\\ or /)

variable ScaleToIndexWrapper(wave wv, variable scale, variable dim)

wrapper to ScaleToIndex

ScaleToIndex treats input inf to scale always as the last point in a wave. -inf on the other hand is undefined. This wrapper function respects the scaled point wave. -inf refers to the negative end of the scaled wave and +inf is the positive end of the scaled wave. This means that this wrapper function also respects the DimDelta direction of the wave scaling. and always returns the closest matching (existing) point in the wave. This also means that the returned values cannot be negative or larger than the numer of points in the wave.

Returns:

an existing index in wv between 0 and DimSize(wv, dim) - 1

string GetSymbolicPathForDiagnosticsDirectory()

Return the name of a symbolic path which points to the crash dump directory on windows.

variable ShowDiagnosticsDirectory()
string GenerateRFC4122UUID()

Generate a version 4 UUID according to https://tools.ietf.org/html/rfc4122.

4.4.  Algorithms for Creating a UUID from Truly Random or
      Pseudo-Random Numbers

   The version 4 UUID is meant for generating UUIDs from truly-random or
   pseudo-random numbers.

   The algorithm is as follows:

   o  Set the two most significant bits (bits 6 and 7) of the
      clock_seq_hi_and_reserved to zero and one, respectively.

   o  Set the four most significant bits (bits 12 through 15) of the
      time_hi_and_version field to the 4-bit version number from
      Section 4.1.3.

   o  Set all the other bits to randomly (or pseudo-randomly) chosen
      values.

See Section 4.5 for a discussion on random numbers.

[...]

 In the absence of explicit application or presentation protocol
 specification to the contrary, a UUID is encoded as a 128-bit object,
 as follows:

 The fields are encoded as 16 octets, with the sizes and order of the
 fields defined above, and with each field encoded with the Most
 Significant Byte first (known as network byte order).  Note that the
 field names, particularly for multiplexed fields, follow historical
 practice.

 0                   1                   2                   3
  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |                          time_low                             |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |       time_mid                |         time_hi_and_version   |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |                         node (2-5)                            |
 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

[...]

4.1.3.  Version

   The version number is in the most significant 4 bits of the time
   stamp (bits 4 through 7 of the time_hi_and_version field).

   The following table lists the currently-defined versions for this
   UUID variant.

   Msb0  Msb1  Msb2  Msb3   Version  Description

    0     0     0     1        1     The time-based version
                                     specified in this document.

    0     0     1     0        2     DCE Security version, with
                                     embedded POSIX UIDs.

    0     0     1     1        3     The name-based version
                                     specified in this document
                                     that uses MD5 hashing.

    0     1     0     0        4     The randomly or pseudo-
                                     randomly generated version
                                     specified in this document.

    0     1     0     1        5     The name-based version
                                     specified in this document
                                     that uses SHA-1 hashing.

   The version is more accurately a sub-type; again, we retain the term
   for compatibility.

See also https://www.rfc-editor.org/errata/eid3546 and https://www.rfc-editor.org/errata/eid1957 for some clarifications.

variable HexToNumber(string ch)

Convert a hexadecimal character into a number.

UTF_NOINSTRUMENTATION

string NumberToHex(variable var)

Convert a number into hexadecimal.

UTF_NOINSTRUMENTATION

wave HexToBinary(string str)

Convert a string in hex format to an unsigned binary wave.

This function works on a byte level so it does not care about endianess.

UTF_NOINSTRUMENTATION

string ConvertListToRegexpWithAlternations(string list)

Turn a list of entries into a regular expression with alternations.

Can be used for GetListOfObjects() if you know in advance which entries to filter out.

variable AddPayloadEntriesFromFiles(variable jsonID, WaveText paths, variable isBinary = defaultValue)

Helper function for UploadCrashDumps.

Fill payload array with content from files

variable AddPayloadEntries(variable jsonID, WaveText keys, WaveText values, variable isBinary = defaultValue)

Helper function for UploadCrashDumps.

Fill payload array

variable UploadJSONPayload(variable jsonID)

Upload the given JSON document.

See tools/http-upload/upload-json-payload-v1.php for the JSON format description.

wave ConvertToUniqueNumber(WaveText wv, variable doZapNaNs = defaultValue, variable doSort = defaultValue)

Convert a text wave to a double wave with optional support for removing NaNs and sorting.

wave GrepWave(WaveText wv, string regex)

Wrapper for Grep which uses a textwave for input and ouput.

std::tuple<RGBAColor> ParseColorSpec(string str)

Parse a color specification as used by ModifyGraph having an optionl translucency part.

wave WaveRef(WaveOrNull w, variable row = defaultValue, variable col = defaultValue, variable layer = defaultValue, variable chunk = defaultValue)

Helper function to be able to index waves stored in wave reference waves in wave assignment statements.

The case where wv contains wave references is also covered by the optional parameters. While returned regular waves can be indexed within the assignment as shown in the first example, this does not work for wave reference waves. Thus, the parameters allow to index through the function call.

Example for source containing regular waves:


Make/FREE data1 = p Make/FREE data2 = p^2 Make/FREE/WAVE source = {data1, data2}

Make/FREE dest dest[] = WaveRef(source[0])[p] + WaveRef(source[1])[p] // note the direct indexing [p] following WaveRef(…) here

Example for source containing wave ref waves:


Make/FREE data1 = p Make/FREE/WAVE interm = {data1, data1} Make/FREE/WAVE source = {interm, interm}

Make/FREE/WAVE/N=2 dest dest[] = WaveRef(source[p], row = 0) // direct indexing does not work here, so we index through the optional function parameter

row, col, layer, chunk are evaluated in this order until one argument is not given.

UTF_NOINSTRUMENTATION

Parameters:
  • w – input wave ref wave

  • row – [optional, default = n/a] when param set returns wv[row] typed

  • col – [optional, default = n/a] when param row and this set returns wv[row][col] typed

  • layer – [optional, default = n/a] when param row, col and this set returns wv[row][col][layer] typed

  • chunk – [optional, default = n/a] when param row, col, layer and this set returns wv[row][layer][chunk] typed

Returns:

untyped waveref of wv or typed wave ref of wv when indexed

string WaveText(WaveOrNull w, variable row = defaultValue, variable col = defaultValue, variable layer = defaultValue, variable chunk = defaultValue)

Compensate IP not having a way to dynamically extract a string from an untyped, i.e. numeric, wave.

UTF_NOINSTRUMENTATION

wave GrepTextWave(WaveText in, string regexp, variable invert = defaultValue)

Grep the given regular expression in the text wave.

std::tuple<variable, variable> SymmetrizeRangeAroundZero(variable minimum, variable maximum)

Given a range [a, b] this returns a symmetric range around zero including both elements.

wave SelectWave(variable condition, WaveOrNull waveIfFalse, WaveOrNull waveIfTrue)

Helper function for multithread statements where ? : does not work with wave references.

The order of arguments is modelled after SelectString/SelectNumber.

std::tuple<WaveDouble, WaveDouble> DistributeElements(variable numElements, variable offset = defaultValue)

Distribute N elements over a range from 0.0 to 1.0 with spacing.

variable CalculateNiceLength(variable range, variable multiple)

Calculate a nice length which is an integer number of multiple long.

For small values \( 10^{-x} \) times multiple are returned

wave RemoveUnusedRows(wave wv)

Remove unused rows from the passed wave and return a copy of it.

If the wave is empty with index being zero, we return a wave with one point so that we:

  • can store something non-empty

  • preserve the dimension labels (this can get lost for empty waves when duplication/saving)

variable EqualValuesOrBothNaN(variable left, variable right)

Check wether val1 and val2 are equal or both NaN.

UTF_NOINSTRUMENTATION

variable IsConstant(wave wv, variable val, variable ignoreNaN = defaultValue)

Checks wether wv is constant and has the value val

UTF_NOINSTRUMENTATION

Parameters:
  • wv – wave to check

  • val – value to check

  • ignoreNaN – [optional, defaults to true] ignore NaN in wv

string SanitizeFilename(string name)

Sanitize the given name so that it is a nice file name.

string MergeLists(string l1, string l2, string sep = defaultValue)

Merges list l1 into l2. Double entries in l2 are kept. “a;b;c;” with “a;d;d;f;” -> “a;d;d;f;b;c;”.

wave DuplicateWaveToFree(wave w)

Duplicates the input wave to a free wave and returns the free wave reference.

wave ZapNaNs(wave data)

Removes all NaNs from the input wave.

variable BinarySearchText(WaveText theWave, string theText, variable caseSensitive = defaultValue, variable startPos = defaultValue, variable endPos = defaultValue)

Finds the first occurrence of a text within a range of points in a SORTED text wave.

From https://www.wavemetrics.com/code-snippet/binary-search-pre-sorted-text-waves by Jamie Boyd Completely reworked, fixed and removed unused features

string GetIgorInstanceID()

Returns a hex string which is unique for the given Igor Pro session.

It allows to distinguish multiple Igor instances, but is not globally unique.

variable RenameDataFolderToUniqueName(string path, string suffix)

Rename the given datafolder path to a unique name.

With path root:a:b:c and suffix _old the datafolder is renamed to root:a:b:c_old or if that exists root:a:b:c_old_1 and so on.

string GetCodeForWaveContents(WaveText wv)

Prepare wave for inline definition.

Outputs a wave in a format so that it can be initialized with these contents in an Igor Pro procedure file.

variable StoreCurrentPanelsResizeInfo(string panel)

If the layout of an panel was changed, this function calls the ResizeControlsPanel module functions of the Igor Pro native package to store the changed resize info. The originally intended way to do this was through the Packages GUI, which is clunky for some workflows.

string ElideText(string str, variable returnLength)

Elide the given string to the requested length.

wave LoadWaveFromDisk(string name)

Load the wave $name.itx from the folder of this procedure file and store it in the static data folder.

variable StoreWaveOnDisk(wave wv, string name)

Store the given wave as $name.itx in the same folder as this procedure file on disk.

variable GenerateMultiplierConstants()
variable IsValidRegexp(string regexp)

Return true if the passed regular expression is well-formed.

variable DoPowerSpectrum(wave input, wave output, variable col)

Calculate PowerSpectrum on a per column basis on each input[][col] and write the result into output[][col]. The result is capped to the output rows. No window function is applied.

wave DoFFT(wave input, string winFunc = defaultValue, variable padSize = defaultValue)

Perform FFT on input with optionally given window function.

Parameters:
  • input – Wave to perform FFT on

  • winFunc – [optional, defaults to NONE] FFT window function

  • padSize – [optional, defaults to the next power of 2 of the input wave row size] Target size used for padding

string CompressNumericalList(string list, string sepChar)

Convert a numerical integer list seperated by sepChar to a list including a range sign (“-”) e. g. 1,2,3,4 -> 1-4 1,2,4,5,6 -> 1-2,4-6 1,1,1,2 -> 1-2 the input list does not have to be sorted.

variable ChangeFreeWaveName(wave wv, string name)

Give the free wave wv the name name

variable WaveTypeStringToNumber(string type)

Returns the wave type as constant.

Same constant as WaveType with selector zero (default) and Redimension/Y.

string WaveToJSON(WaveOrNull wv)

Serialize a wave as JSON and return it as string.

The format is documented here.

wave JSONToWave(string str, string path = defaultValue)

Deserialize a JSON document generated by WaveToJSON()

Supports only a currently used subset.

See also

WaveToJSON

Parameters:
  • str – serialized JSON document

  • path – [optional, defaults to “”] json path with the serialized wave info

variable GetNotebookCRC(string win)

Return the CRC of the contents of the plain/formatted notebook.

Takes into account formatting but ignores selection.

string FormatTextWaveForLegend(WaveText input)

Format the 2D text wave into a string usable for a legend.

variable IsValidTraceLineStyle(variable lineStyleCode)

Checks if given lineStyle code is valid (as of Igor Pro 9)

Parameters:

lineStyleCode – line style code value for a trace

Returns:

1 if valid, 0 otherwise

variable IsValidTraceDisplayMode(variable traceDisplayCode)

Checks if given trace display code is valid (as of Igor Pro 9)

Parameters:

traceDisplayCode – line style code value for a trace

Returns:

1 if valid, 0 otherwise

variable NumBytesInUTF8Character(string str, variable byteOffset)

Returns the number of bytes in the UTF-8 character that starts byteOffset bytes from the start of str. NOTE: If byteOffset is invalid this routine returns 0. Also, if str is not valid UTF-8 text, this routine return 1.

From DisplayHelpTopic “Character-by-Character Operations”

variable UTF8CharactersInString(string str)

Returns the number of UTF8 characters in a string.

From DisplayHelpTopic “Character-by-Character Operations”

string UTF8CharacterAtPosition(string str, variable charPos)

Returns the UTF8 characters in a string at position charPos.

From DisplayHelpTopic “Character-by-Character Operations”

wave UTF8StringToTextWave(string str)

Converts a string in UTF8 encoding to a text wave where each wave element contains one UTF8 characters.

string GetUserDocumentsFolderPath()

Returns the path to the users documents folder.

variable RefCounterDFIncrease(dfref dfr)

For DF memory management, increase reference count.

Parameters:

dfr – data folder reference of the target df

variable RefCounterDFDecrease(dfref dfr)

For DF memory management, decrease reference count and kill DF if zero is reached.

Parameters:

dfr – data folder reference of the target df

variable UpdateInfoButtonHelp(string win, string ctrl, string content)

Update the help and user data of a button used as info/copy button.

variable LimitWithReplace(variable val, variable low, variable high, variable replacement)

Acts like the limit builtin but replaces values outside the valid range instead of clipping them.

variable IsFunctionCalledRecursively()

Return true if the calling function is called recursively, i.e. it is present multiple times in the call stack.

wave SplitLogDataBySize(WaveText logData, string sep, variable lim, variable lastIndex = defaultValue, variable firstPartSize = defaultValue)

Splits a text wave (with e.g. log entries) into parts. The parts are limited by a size in bytes such that each part contains only complete lines and is smaller than the given size limit. A possible separator for line endings is considered in the size calculation.

Parameters:
  • logData – text wave

  • sep – separator string that is considered in the length calculation. This is useful if the resulting waves are later converted to strings with TextWaveToList, where the size grows by lines * separatorLength.

  • lim – size limit for each part in bytes

  • lastIndex – [optional, default DimSize(logData, ROWS) - 1] When set, only elements in logData from index 0 to lastIndex are considered. lastIndex is included. lastIndex is limited between 0 and DimSize(logData, ROWS) - 1.

  • firstPartSize – [optional, default lim] When set then the first parts size limit is firstPartSize instead of lim

Returns:

wave reference wave containing text waves that are consecutive and sequential parts of logdata

variable Base64EncodeSize(variable unencodedSize)

Calculated the size of Base64 encoded data from the unencoded size.

Parameters:

unencodedSize – unencoded size

Returns:

encoded size

variable GetDayOfWeek(variable seconds)

Returns the day of the week, where 1 == Sunday, 2 == Monday … 7 == Saturday.

string UpperCaseFirstChar(string str)

Upper case the first character in an ASCII string.

variable FindRightMostHighBit(uint64 value)

Find the right most high bit.

Parameters:

value – integer value in the range [0, 2^64]

Returns:

right most high bit or NaN in case nothing could be found

wave ZapNullRefs(WaveRefWave input)
wave SplitWavesToDimension(WaveRefWave input, variable sdim = defaultValue)

Split multidimensional waves inside input to the given dimension.

Parameters:
  • input – wave reference wave

  • sdim – [optional, defaults to 1] dimensionality to split to

static variable AreIntervalsIntersectingImpl(variable index, wave intervals)
variable AreIntervalsIntersecting(wave intervalsParam)

Return the truth if any of the given intervals ]A, B[ intersect.

Parameters:

intervalsParam – Nx2 wave with the intervals

std::tuple<variable, variable> RoundAndDelta(variable val)

Returns the integer result and the difference of it to the original value.

std::tuple<variable, variable> CeilAndDelta(variable val)

Returns the integer result and the difference of it to the original value.

std::tuple<variable, variable> FloorAndDelta(variable val)

Returns the integer result and the difference of it to the original value.

variable IndexAfterDecimation(variable sourceIndex, variable decimationFactor)

Returns the target index closer to zero of a given source index for a decimation in the form target[] = source[round(p * decimationFactor)] Note: For a decimationFactor < 1 a point in source may be decimated to multiple points in target, thus a resulting index in target of sourceIndex + 1 may be equal to the index retrieved for sourceindex. For a decimationFactor > 1 points in source may be skipped on decimation, thus a resulting index in target of sourceIndex + 1 may increase the result by more than 1.

variable FindFirstNaNIndex(wave wv)

Returns the first row index that is NaN from the floating point wave wv, NaN if no index is NaN.

variable SetDimensionLabelsFromWaveContents(wave wv, string prefix = defaultValue, string suffix = defaultValue, variable strict = defaultValue)

Sets the DimLabels for elements of a 1d numerical or text wave based on the content of the wave For numerical waves the wave element is treated as integer For textual waves the elements must translate to a valid DimLabel.

Parameters:
  • wv – input wave

  • prefix – [optional: default “” for numerical waves and NUM_ for textual waves] prefix of the dimlabel For numerical waves it is recommended to provide an own prefix.

  • suffix – [optional: default “”] suffix of the dimlabel

  • strict – [optional: default 0] When this flag is set then each constructed DimLabels for text wave elements are checked if it results in a valid DimLabel, it is also checked if duplicate Dimlabels would be created.

variable HasWildcardSyntax(string str)

Return true if str is in wildcard syntax, false if not.

struct Uuid

Helper structure for GenerateRFC4122UUID()

Public Members

uint32 time_low
uint16 time_mid
uint16 time_hi_and_version
uint16 clock_seq
uint16 node0
uint16 node1
uint16 node2