IGOR Pro

From Torben's Wiki

Wave Metrics IGOR Pro

General

Deklarations

variable thickness,messstrom
String str= "huhu"
wave calcHTemp,calcHRdcA

Functions

Function Funktion(param1,param2)
	variable param1,param2
	variable int
	return int
end
Function/S Funktion(param1,param2)
	variable param1,param2
	String str
	return str
end

Loops

if (a==b)
  [BODY]
else
  [BODY]
endif

for (i=0;i<numpnts(wave);i=i+1)
  [BODY]
endfor 

Menu-Entry

menu "MyMacros"
	"Eintrag", Funktion()
end

Prompt

Prompt thickness, "Dicke der Schicht in Nanometern"
Prompt messstrom, "Messstrom in Mikroampere"
DoPrompt "Nur eine Kleinigkeit noch . . .",thickness,messstrom

Strings

num2str(dicke*10^9)+"nm"
String str = "Hello World"
str[0] = "HuHu "
-> str = "HuHu Hello World"
String str = "Hello World"
str[0,4] = "HuHu "
-> str = "HuHu World"

Find a substring

strsearch(str, searchStr, start )

File Access

Variable lauf
wave /T filelist
NewPath/O MyPath  //  New Path
NumOfImages = ItemsInList(IndexedFile(MyPath,-1,".txt"))
Redimension/N=(NumOfImages) filelist
for (lauf=0;lauf<NumOfImages;lauf+=1)
	filelist[lauf] = IndexedFile(MyPath,lauf,".txt")
endfor
Sort filelist,filelist

My Toolbox

Main File

#include "m:igor:werkzeugkiste:Waves"
#include "m:igor:werkzeugkiste:Graphs"
#include "m:igor:werkzeugkiste:Fits"
#include "m:igor:werkzeugkiste:Styles"

menu "Werkzeugkiste"
end

Function ZeitenAusInfoEinlesen()
	LoadWave /J/L={0, 5, 0, 1, 1 }/O/N=Zeiten //P=GreenPath "info.txt"
	wave Zeiten0
	rename Zeiten0,Zeiten
	Wave Zeiten
	Zeiten/=1000 //ms -> s
	// die ersten Zeiten müssen evtl noch manuel rausgenommen werden
	// Zeiten[0] muss dann auf Null gesetzt werden
End


Function makeNewFolders(anzahl)
	Variable anzahl
	Variable i
	for (i=1;i<=anzahl;i+=1)
	String str =""
	if (i<10)
		str = "0"
	endif
	str = str + num2str(i)
	NewDataFolder /O $str
	endfor
End


Function /S GetListOfFolderCont(objectType)
	Variable objectType //1==Waves, 2==Vars, 3==Strings, 4==Folders
	String sourceFolderStr = GetDataFolder(1)
	String Liste = ""
	Variable i
	For(i=0;i<CountObjects(sourceFolderStr, objectType ); i+=1)
		Liste += GetIndexedObjName(sourceFolderStr, objectType, i )+";"
	EndFor
	Return Liste
End


Function/S PopUpChooseFolder()
	String liste = GetListOfFolderCont(4)
	String verz = ""
	Prompt verz,"Folder",popup,liste
	DoPrompt "",verz
	if (V_Flag == 1) 
		return "" 
	endif 
	Return verz
End

Waves

menu "Werkzeugkiste"
	"ForEach Wave", ForEachWave()
	"Dublicate Waves", WavesDublizieren()
	"Rename Waves", WavesUmbenennen()
	"Delete Waves", WavesLoeschen()
	//findmin, findmax, createx
	"Waves -> Matrix", Waves2Matrix()
	"Matrix-Y-Region -> Wave", Matrix2Wave()
	"-"
end

Function ForEachWave(Cmd)
	String Cmd
	String WaveNameMatch = "*"
	Prompt WaveNameMatch, "Only waves matching:"
	String RegExp = "^m..$"
	Prompt RegExp, "Regular Expression Filter"
	If(StrLen(Cmd)==0)
		Cmd += "Display %n%,%n%_smth vs ::%n%xwave_eV;"
		Cmd += "ModifyGraph rgb(%n%)=(0,0,0);"
		Cmd += "ModifyGraph rgb(%n%_smth)=(65280,0,0);"
		
//		Cmd += "Duplicate/O %n%,%n%_smth;"
//		Cmd += "Smooth 25, %n%_smth;"
	EndIf
	Prompt Cmd, "Command"
	DoPrompt "", WaveNameMatch,RegExp, Cmd
	if (V_Flag)
		return -1 // User canceled
	endif
	String List = GrepList( WaveList(WaveNameMatch,";","") , RegExp)
	Variable i
	For (i=0;i<ItemsInList(List);i+=1)
		String n = StringFromList(i,List)
		String ThisCmd = ReplaceString("%n%", Cmd, n)
		Execute ThisCmd
	EndFor
End


Function WavesDublizieren()
	String WaveNameMatch = "*"
	Prompt WaveNameMatch, "Only doublicate waves matching"
	String RegExp = ".*"
	Prompt RegExp, "Regular Expression Filter"
	String TargetFolder = "Copy"
	Prompt TargetFolder, "Target Folder"
	DoPrompt "", WaveNameMatch, RegExp, TargetFolder
	if (V_Flag)
		return -1 // User canceled
	endif
	String List = GrepList(WaveList(WaveNameMatch,";","") , RegExp)
	If (!DataFolderExists(TargetFolder))
		NewDataFolder $TargetFolder
	EndIf
	Variable i
	For (i=0;i<ItemsInList(List);i+=1)
		String n = StringFromList(i,List)
		String new = ":"+TargetFolder+":"+n
		Duplicate $n, $new
	EndFor
End


Function WavesUmbenennen()
	String WaveNameMatch = "*"
	Prompt WaveNameMatch, "Only rename waves matching:"
	String RegExp = "^.*$"
	Prompt RegExp, "Regular Expression Filter"
	String Was   = "00"
	Prompt Was  , "Replace what"
	String Womit = "__"
	Prompt Womit, "Replace with"
	DoPrompt "", WaveNameMatch,RegExp, Was, Womit
	if (V_Flag)
		return -1 // User canceled
	endif
	String List = GrepList ( WaveList(WaveNameMatch,";","") , RegExp )
	Variable i
	For (i=0;i<ItemsInList(List);i+=1)
		String oldname = StringFromList(i,List)
		String newname = ReplaceString(Was,oldname,Womit)
		Wave wo = $oldname
		Wave wn = $newname
		Rename wo,$newname
	EndFor
End


Function WavesLoeschen()
	String WaveNameMatch = "*_smth"
	Prompt WaveNameMatch, "Only rename waves matching:"
	String RegExp = ".*"
	Prompt RegExp, "Regular Expression Filter"
	DoPrompt "", WaveNameMatch,RegExp
	if (V_Flag)
		return -1 // User canceled
	endif
	String List = GrepList(WaveList(WaveNameMatch,";","") , RegExp)
	DoAlert 1, "REALLY sure to delete " + num2str(ItemsInList(List)) + "waves???\r " + ReplaceString(";",List," ")
	if (V_Flag!=1) // Not "Yes" clicked
		return -1 
	endif
	Variable i
	For (i=0;i<ItemsInList(List);i+=1)
		String n = StringFromList(i,List)
		Wave w = $n
		KillWaves w
	EndFor
End


function findmin(data)
	wave data
	variable i
	variable mini =data[0]
	variable maxi=data[0]
	for (i=1;i<numpnts(data);i=i+1) // hier nicht von i=0
		mini=min(mini,data[i])
		maxi=max(maxi,data[i])
	endfor
	return mini
end // findmin
function findmax(data)
	wave data
	variable i
	variable maxi=data[0]
	for (i=1;i<numpnts(data);i=i+1) // hier nicht von i=0
		maxi=max(maxi,data[i])
	endfor
	return maxi
end // findmax

// Extracts an xwave from an igor combined wave
// use: createx("wave")
function createx(NameDerWave)
	String NameDerWave
	wave w=$NameDerWave
	variable start=leftx(w)
	variable delta=deltax(w)
	String NameDerXWave = NameDerWave+"x"
	Make /N=(numpnts(w)) $NameDerXWave
	wave wx = $NameDerXWave
	variable index=0
	for (index=0;index<numpnts(xaxis);index+=1)
		wx[index]=start+ index*delta
	endfor
end

// joins all waves of folder "Waves" into matrix "Matrix", having the wave# as the x-axis
// Sorts waves by name
function Waves2Matrix()
	if (!DataFolderExists("waves"))
		DoAlert 0,"No child datafolder named waves"
		return -1
	endif
	SetDataFolder("waves")
	String sWaveListe = WaveList("*",";","")
	sWaveListe = SortList(sWaveListe,";",16) // case-insensitive alphanumeric sort that sorts wave0 and wave9 before wave10.
	Variable numWaves = ItemsInList(sWaveListe,";")
	
	Make /N=(numWaves,0)/O/U/I ::Matrix //unsigned integer
	Wave m=::Matrix
	
	Variable index
	for (index=0; index<numWaves; index+=1)
		String sWaveName = StringFromList(index, sWaveListe)
		Print sWaveName
		Wave w = $sWaveName
		Variable numpntsInWave = numpnts(w)
		If (index==0)
			Redimension/N=(-1,numpntsInWave) m
		ElseIf(numpntsInWave != dimsize(m,1))
			DoAlert 0, "Waves do not have the same number of points!"		
			SetDataFolder("::")
			return -1
		EndIf
		Variable i
		for (i=0;i<numpntsInWave;i+=1)
			m[index][i] = w[i]
		endfor
	endfor
	SetDataFolder("::")
end

// joins averages an Y-region of a matrix into a single wave
// Matrixname = "Matrix"
function Matrix2Wave()
	If (!WaveExists(Matrix))
		DoAlert 0, "No matrix named \"Matrix\" existing"
		Return -1
	EndIf
	Wave m = Matrix
	Variable numXValues = DimSize(m,0)
	Variable maxLines = DimSize(m,1)
	
	Variable loiUp=maxLines-1
	Variable LoiDown=0
	Prompt loiUp, "Upper Line of Interest"
	Prompt loiDown, "Lower Line of Interest"
	DoPrompt "", loiDown,loiUp
	if (V_flag != 0)
		return -1
	endif
	If (loiUp>=maxLines)
		loiUp=maxLines-1
	EndIf	
	If(loiUp<loiDown)
		Variable var = loiUp
		loiUp=loiDown
		loiDown=var
	EndIf
	
	Variable numLines = loiUp - loiDown
	String nameDerWave = "MatrixRegion" + num2str(loiDown) + "-" + num2str(loiUp) 
	Make /O/N=(numXValues) $nameDerWave
	Wave w = $nameDerWave
	w=0
	Variable i,j
	For (i=0;i<numXValues;i+=1)
		For (j=0;j<numLines;j+=1)
			w[i] += m[i][j]
		EndFor
	EndFor
end

Graphs

menu "Werkzeugkiste"
	"Plot File", plotfile()
	"Colorize Traces", colorizeTraces()
	"Label Graph", LabelGraph()
	"Add Legend to Graph", AddLegend()
	"Save Graph as PNG", exportPNG()
	"Save Graph as PNG, Screen-Resolution", exportPNGScreen()
	"KillAll", killAll()
	"ForEach Graph", ForEachGraph()
//	"ForEach Graph-Trace", ForEachGraphTrace()
	"-"
end

function plotfile()
	KillWaves /Z xwave, ywave, matrix0, matrix
	string file = OpenFileDialog()
	if (StrLen(file)==0) // canceled
		return -1 
	endif	

	LoadWave /A=matrix/M/O/G file // /M for Matrix	
	rename matrix0,matrix
	wave matrix
	variable anzSpalten = DimSize(matrix, 1)

	if (anzSpalten==1)
	rename matrix, xwave
	Display xwave
	else
		if (anzSpalten==2)
			make /O /N=(DimSize(matrix, 0)) xwave
			make /O /N=(DimSize(matrix, 0)) ywave
			variable i=0
			for (i=0;i<DimSize(matrix,0);i+=1)
				xwave[i]=matrix[i][0]
				ywave[i]=matrix[i][1]
			endfor
	
			Display ywave vs xwave
		endif
		if (anzSpalten>2)
//			turnMatrix("matrix")
			NewImage /F/K=0 matrix ;
			ModifyGraph swapXY=1;
			ModifyImage matrix ctab= {0,50,Rainbow,1}
		endif
	endif
	KillWaves /Z xwave, ywave, matrix0, matrix
end //Plotfile()

Function/S OpenFileDialog() // used by Plotfile()
	Variable refNum
//	String message = "Select a file"
	String outputPath
	Open/D/R/M="Choose File" refNum
	outputPath = S_fileName
	return outputPath
End 


function colorizeTraces()
	String traces = TraceNameList("", ",", 1)
	//traces = SortList(traces,",",16)
	Variable numoftraces=ItemsInList(traces,",")
	Variable i=0
	do
		String tracename = StringFromList(i, traces,",")
		if(strlen(tracename)==0)
			break
		endif
		variable r,g,b
		String farbcode = colorizeTracesGenColor (i,numoftraces)
		r = str2num(StringFromList(0, farbcode,","))
		g = str2num(StringFromList(1, farbcode,","))
		b = str2num(StringFromList(2, farbcode,","))
		ModifyGraph rgb($tracename)=(r,g,b)
 		i+=1
	while(i)
	AddLegend()
end
function /S colorizeTracesGenColor (index,anztraces)
	variable index // 0,1,2,3... anztraces-1
	variable anztraces
	String farbcode = ""
	index = mod(index,10)
	switch (index)
	// color codes taken from the Package KBColorizTraces
	case 0:
		farbcode = "00000,00000,00000"
		break
	case 1:
		farbcode = "65535,16385,16385"
		break
	case 2:
		farbcode = "000002,39321,00001"
		break
	case 3:
		farbcode = "00000,00000,65535"
		break
	case 4:
		farbcode = "39321,00001,31457"
		break
	case 5:
		farbcode = "48059,48059,48059"
		break
	case 6:
		farbcode = "65535,32768,32768"
		break
	case 7:
		farbcode = "00000,65535,00000"
		break
	case 8:
		farbcode = "16385,65535,65535"
		break
	case 9:
		farbcode = "65535,32768,58981"
		break
	endswitch
	return farbcode
end //colorizeTracesGenColor

Function LabelGraph()	
	String title = ""
	String bottom = ""
	String left = ""
	Prompt title, "Title of Graph"
	Prompt bottom, "Label of bottom-axis"
	Prompt left, "Label of left-axis"
	DoPrompt "", title, bottom, left
	if (V_flag == 1)
		return -1
	endif
	If (! StringMatch(title , ""))
		title = "\JR"+title
		TextBox/C/N=text_titel/Z=1/D={1,1,0}/A=RT/X=0.00/Y=0.00 title
	EndIf
	If (! StringMatch(bottom , ""))
		Label bottom bottom
	EndIf
	If (! StringMatch(left , ""))
		Label left left
	EndIf
end

Function AddLegend()
	Legend/C/N=text_legend/X=0.00/Y=0.00
end

Function exportPNG()
	SavePICT/E=-5/B=288/M/W=(0,0,20,15)
End
Function exportPNGScreen()//resulution=screen
	SavePICT/E=-5/B=72/M/W=(0,0,12,9)
End

Function killall()
	String Filter = "*"
	Prompt Filter, "Name Match String"
	String RegExp = "^.*$"
	Prompt RegExp, "Regular Expression Filter"
	String sType //1=graph, 2=table, 4=layout
	Prompt sType , "Choose Type?", popup, "Graphs;Tables;Layouts;All of Them"
	DoPrompt "What do you want to kill today?",sType,Filter,RegExp
	If (V_flag==1) // cancel clicked
		Return 0
	EndIf
	Variable Type
	If(StringMatch(sType,"Graphs") )
		Type = 1
	ElseIf(StringMatch(sType,"Tables") )
		Type = 2
	ElseIf(StringMatch(sType,"Layouts") )
		Type = 4
	ElseIf(StringMatch(sType,"All of them") )
		Type = 7
	EndIF
	String allItems = GrepList ( WinList(Filter, ";","WIN: "+num2str(Type)) , RegExp)
	Variable numOfItems = ItemsInList(allItems)
	DoAlert 1, "Are you SURE to delete all "  + num2str(numOfItems)+ " items?"
	If (V_flag!=1) // no clicked
		Return 0
	EndIf
	Variable itemCounter
	For (itemCounter=0; itemCounter < numOfitems; itemCounter+=1)
		String oneitem = StringFromList(itemCounter, allitems, ";")
		DoWindow/K $oneitem
	EndFor
End

Function ForEachGraph()
	String GraphNameMatch = "*"
	Prompt GraphNameMatch, "Only graph names matching"
	String RegExp = ".*"
	Prompt RegExp, "Regular Expression Filter"
	String Cmd = ""
	Cmd += "DoWindow /F %n%"
	Prompt Cmd, "Command"
	DoPrompt "", GraphNameMatch,RegExp, Cmd
	String List = GrepList ( WinList(GraphNameMatch, ";","WIN: 1") , RegExp)
	Variable i
	For (i=0; i < ItemsInList(List); i+=1)
		String name = StringFromList(i, List, ";")
		String ThisCmd = ReplaceString("%n%",Cmd,name)
		Execute ThisCmd
//		SetAxis left 0,*
//		SetAxis bottom 1.45,1.90
	EndFor
End

Function ForEachGraphTrace()
	String graphList = WinList("*", ";","WIN: 1")
	Variable graphCounter
	For (graphCounter=0; graphCounter < ItemsInList(graphList); graphCounter+=1)
		String NameOfGraph = StringFromList(graphCounter, graphList, ";")
		print NameOfGraph
		DoWindow/F $NameOfGraph //bring to front
		String traceList = TraceNameList(NameOfGraph, ";", 1)
		Variable traceCounter
		For (traceCounter=0; traceCounter < ItemsInList(traceList); traceCounter+=1)
			String NameOfTrace
		EndFor
//		String data = StringFromList(0,traces,";")
//		String fit = StringFromList(1,traces,";")
//		String peak1 = StringFromList(2,traces,";")
//		String peak2 = StringFromList(3,traces,";")
//		String peak3 = StringFromList(4,traces,";")
//		ModifyGraph rgb($data)=(0,0,0)
//		ModifyGraph rgb($fit)=(65280,43520,0)
//		ModifyGraph rgb($peak1)=(65280,0,0)
//		ModifyGraph rgb($peak2)=(0,65280,0)
//		ModifyGraph rgb($peak3)=(0,0,65280)
	endfor
end

Styles

menu "GraphStyles"
	"Intensity vs. Energy", Style_IvE()
	"Intensity vs. Wavelength", Style_IvL()
	"Intensity vs. Time", Style_IvT()
	"Energy vs. Time", Style_EvT()
end

Proc Style_Defaults()
	PauseUpdate; Silent 1		// modifying window...
	ModifyGraph/Z mirror=1
	ModifyGraph/Z tick=2
	ModifyGraph/Z grid=2,nticks=4,minor=1
	ModifyGraph/Z standoff=0
EndMacro

Proc Style_IvE() : GraphStyle
	PauseUpdate; Silent 1		// modifying window...
	Style_Defaults()
	SetAxis left 0,*
	ModifyGraph prescaleExp(left)=-3
	Label/Z left "PL Intensity (a.u.)"
	Label/Z bottom "Energy (eV)"
EndMacro

Proc Style_IvL() : GraphStyle
	PauseUpdate; Silent 1		// modifying window...
	SetAxis left 0,*
	ModifyGraph prescaleExp(left)=-3
	Style_Defaults()
	Label/Z left "PL Intensity (a.u.)"
	Label/Z bottom "Wavelength (nm)"
EndMacro

Proc Style_IvT() : GraphStyle
	PauseUpdate; Silent 1		// modifying window...
	SetAxis left 0,*
	ModifyGraph prescaleExp(left)=-3
	Style_Defaults()
	Label/Z left "PL Intensity (a.u.)"
	Label/Z bottom "Time (s)"
EndMacro

Proc Style_EvT() : GraphStyle
	PauseUpdate; Silent 1		// modifying window...
	ModifyGraph/Z mirror=1
	ModifyGraph/Z tick=2
	ModifyGraph/Z grid=0,nticks=4,minor=1
	ModifyGraph/Z standoff=0
	Label/Z left "Energy (eV)"
	Label/Z bottom "Time (s)"
EndMacro

Fitting

menu "Werkzeugkiste"
	"Gauss-Fit on many waves ", machVieleGaussFits() 
	"Create Gauss-Curve", makeGaussPrompt()
	"-"
end

//reads x-scaling from a wave
//TODO: read x-scaling from scaled waves
function makeGaussPrompt()
	// Gauss: offset + amp + Exp(- (x-pos)^2/width)
	String NameDesGauss = "gauss1_m01"
	Variable offset = 0
	Variable amp = 42964
	Variable pos = 2.0805
	Variable width = 0.13698
	Prompt NameDesGauss, "Name of Output Wave"
	Prompt offset, "Gauss Parameter 0: Offset"
	Prompt amp, "Gauss Parameter 1: Amplitude"
	Prompt pos, "Gauss Parameter 2: Position"
	Prompt width, "Gauss Parameter 3: Width"
	DoPrompt "TITEL", NameDesGauss, offset, amp, pos, width
	if (V_Flag != 0) 
		return 0 
	endif 
	makeGauss2(NameDesGauss, offset, amp, pos, width)
end
function makeGauss2(NameDesGauss, offset, amp, pos, width)
	String NameDesGauss
	Variable offset
	Variable amp
	Variable pos
	Variable width

	Variable relBreite = 2
	Variable punkte = 128
	Variable startx=pos - relBreite*width //relBreite = 5
	Variable endx  =pos + relBreite*width
	Make /N=(punkte) $NameDesGauss
	Wave w = $NameDesGauss
	SetScale/I x startx,endx,"", w
	w = offset + amp * Exp(- ((x-pos)/width)^2)
end


Function machVieleGaussFits()
	// Does a Gauss-Fit on all waves in current folder, matching a certain name
	// results can be found in Fit_Offset, Fit_Ampl, Fit_Pos, Fit_Width
	String MatchName = "*"
	Prompt MatchName , "Wave names matching:"
	String RegExp = "^.*$"
	Prompt RegExp, "Regular Expression Filter"

	DoPrompt "Filter Waves", MatchName, RegExp
	If (V_flag==1)
		return -1
	EndIf
	
	String Liste = SortList (GrepList (  WaveList(MatchName,";","") , RegExp) , ";" , 2 )
	Variable AnzWaves = itemsinlist(Liste)
	Make /O/N=(AnzWaves) Fit_Offset ; Wave Fit_Offset ; Fit_Offset=0
	Make /O/N=(AnzWaves) Fit_Ampl   ; Wave Fit_Ampl   ; Fit_Ampl=0
	Make /O/N=(AnzWaves) Fit_Pos    ; Wave Fit_Pos    ; Fit_Pos=0
	Make /O/N=(AnzWaves) Fit_Width  ; Wave Fit_Width  ; Fit_Width=0
	If (DataFolderExists ("tempfit"))
		DoAlert 0, "DataFolder \"tempfit\" does already exist, so quitting"
		return -1
	EndIf
	NewDataFolder /S/O tempfit
	Variable i
	For (i=0;i<AnzWaves;i+=1)
		String name = "::" + StringFromList(i,Liste)
		Wave w = $name
		CurveFit/N/M=0/W=0/Q gauss, w
		Wave W_coef
		Fit_Offset[i] = W_coef[0]
		Fit_Ampl[i]   = W_coef[1]
		Fit_Pos[i]    = W_coef[2]
		Fit_Width[i]  = W_coef[3]
	EndFor
	SetDataFolder ::
	KillDataFolder tempfit
End